blob: 0b1968765300a7c64fac16ca1e12ddad48e01604 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Jonathan Scott92335342019-12-17 14:46:26 +000031import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Galia Peycheva45f48d32020-02-20 15:39:10 +010034import static android.app.WindowConfiguration.ACTIVITY_TYPE_DREAM;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070035import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
36import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070037import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
38import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
39import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070042import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070043import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070044import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
45import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070047import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070048import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
49import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
50import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070051import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070052import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080053import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070054import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070055import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
57import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070058import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
59import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070060import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040061import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.view.Display.DEFAULT_DISPLAY;
63import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070064import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070065
Yunfan Chen79b96062018-10-17 12:45:23 -070066import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
67import static com.android.server.am.ActivityManagerService.MY_PID;
68import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
69import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwalef342f062020-01-27 07:34:13 -080070import static com.android.server.am.ActivityManagerServiceDumpActivitiesProto.ROOT_WINDOW_CONTAINER;
Wale Ogunwale31913b52018-10-13 08:29:31 -070071import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
72import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080081import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Jeff Changd136e772019-11-05 20:33:52 +080085import static com.android.server.am.EventLogTags.writeBootProgressEnableScreen;
86import static com.android.server.am.EventLogTags.writeConfigurationChanged;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070087import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
88import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
91import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Louis Chang149d5c82019-12-30 09:47:39 +0800119import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
Louis Changcdec0802019-11-11 11:45:07 +0800121import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
Louis Changa009c762020-02-26 11:21:31 +0800124import static com.android.server.wm.WindowContainer.POSITION_TOP;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800127import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700128import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.annotation.Nullable;
130import android.annotation.UserIdInt;
131import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700132import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700133import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.ActivityOptions;
135import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700136import android.app.ActivityThread;
137import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700138import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100139import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700140import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700141import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700142import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.IApplicationThread;
144import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400146import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700148import android.app.Notification;
149import android.app.NotificationManager;
150import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700151import android.app.PictureInPictureParams;
152import android.app.ProfilerInfo;
153import android.app.RemoteAction;
154import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700155import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.app.admin.DevicePolicyCache;
157import android.app.assist.AssistContent;
158import android.app.assist.AssistStructure;
jorgegil@google.com06bc3232019-10-31 14:51:22 -0700159import android.app.servertransaction.ClientTransaction;
160import android.app.servertransaction.EnterPipRequestedItem;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700161import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.ActivityNotFoundException;
163import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700164import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700165import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700166import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700167import android.content.IIntentSender;
168import android.content.Intent;
169import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700170import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900171import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700172import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700174import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.content.pm.ParceledListSlice;
176import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700177import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700179import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700180import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700181import android.graphics.Bitmap;
182import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700183import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700184import android.metrics.LogMaker;
185import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700186import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700187import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700188import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700189import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700190import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700194import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800195import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700196import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700197import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700198import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700199import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100200import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700201import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700203import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.SystemClock;
205import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700207import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700209import android.os.UserManager;
210import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700211import android.os.storage.IStorageManager;
212import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700213import android.provider.Settings;
Galia Peycheva6861e912019-08-21 10:20:23 +0200214import android.service.dreams.DreamActivity;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700215import android.service.voice.IVoiceInteractionSession;
216import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900217import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700218import android.telecom.TelecomManager;
219import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100220import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700222import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700223import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700224import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700225import android.util.SparseArray;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700226import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700227import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700228import android.view.IRecentsAnimationRunner;
229import android.view.RemoteAnimationAdapter;
230import android.view.RemoteAnimationDefinition;
Louis Changa009c762020-02-26 11:21:31 +0800231import android.view.WindowManager;
Wale Ogunwale568f9f412020-03-21 22:27:35 -0700232import android.window.IWindowOrganizerController;
Wale Ogunwale57946582020-03-21 14:29:07 -0700233import android.window.WindowContainerTransaction;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700234
Evan Rosky4505b352018-09-06 11:20:40 -0700235import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700236import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.app.AssistUtils;
238import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700239import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700242import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
243import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700245import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700246import com.android.internal.policy.IKeyguardDismissCallback;
247import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700248import com.android.internal.util.ArrayUtils;
249import com.android.internal.util.FastPrintWriter;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800250import com.android.internal.util.FrameworkStatsLog;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800251import com.android.internal.util.function.pooled.PooledConsumer;
252import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700253import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700254import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700255import com.android.server.LocalServices;
256import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700257import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800258import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700259import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700260import com.android.server.am.ActivityManagerService;
Wale Ogunwale59507092018-10-29 09:00:30 -0700261import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
262import com.android.server.am.AppTimeTracker;
263import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700264import com.android.server.am.PendingIntentController;
265import com.android.server.am.PendingIntentRecord;
266import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700267import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700268import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700269import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800270import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700271import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700275import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700277import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700279import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700280import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700281import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800282import java.lang.annotation.ElementType;
283import java.lang.annotation.Retention;
284import java.lang.annotation.RetentionPolicy;
285import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700286import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700288import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700289import java.util.Arrays;
Jeff Sharkey8b0cff72020-03-09 15:49:01 -0600290import java.util.Collection;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700291import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400292import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700293import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700295import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700296import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000297import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700298import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700299
300/**
301 * System service for managing activities and their containers (task, stacks, displays,... ).
302 *
303 * {@hide}
304 */
305public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700306 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800307 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000308 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700309 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
310 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
311 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
312 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700313 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700314
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700316 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700318 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100319 // How long we permit background activity starts after an activity in the process
320 // started or finished.
321 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700322
Wale Ogunwale98875612018-10-12 07:53:02 -0700323 /** Used to indicate that an app transition should be animated. */
324 static final boolean ANIMATE = true;
325
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700326 /** Hardware-reported OpenGLES version. */
327 final int GL_ES_VERSION;
328
Wale Ogunwale31913b52018-10-13 08:29:31 -0700329 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
330 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
331 public static final String DUMP_LASTANR_CMD = "lastanr" ;
332 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
333 public static final String DUMP_STARTER_CMD = "starter" ;
334 public static final String DUMP_CONTAINERS_CMD = "containers" ;
335 public static final String DUMP_RECENTS_CMD = "recents" ;
336 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
337
Wale Ogunwale64258362018-10-16 15:13:37 -0700338 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
339 public static final int RELAUNCH_REASON_NONE = 0;
340 /** This activity is being relaunched due to windowing mode change. */
341 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
342 /** This activity is being relaunched due to a free-resize operation. */
343 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
344
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700345 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700346
Wale Ogunwalef6733932018-06-27 05:14:34 -0700347 /**
348 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
349 * change at runtime. Use mContext for non-UI purposes.
350 */
351 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700352 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700353 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700354 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700355 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700356 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700357 private PackageManagerInternal mPmInternal;
Darryl L Johnsona0982222020-02-18 18:21:51 -0800358 /** The cached sys ui service component name from package manager. */
359 private ComponentName mSysUiServiceComponent;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800360 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800361 @VisibleForTesting
362 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700363 PowerManagerInternal mPowerManagerInternal;
364 private UsageStatsManagerInternal mUsageStatsInternal;
365
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700366 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700367 IntentFirewall mIntentFirewall;
368
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700369 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800370 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800371 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700372 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800373 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
374 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
375 *
376 * @see WindowManagerThreadPriorityBooster
377 */
378 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700379 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800380 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700381 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700382 private UserManagerService mUserManager;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800383 private AppOpsManager mAppOpsManager;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700384 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800385 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700386 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700387 /** All processes currently running that might have a window organized by name. */
388 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100389 /** All processes we currently have running mapped by pid and uid */
390 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700391 /** This is the process holding what we currently consider to be the "home" activity. */
392 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700393 /** The currently running heavy-weight process, if any. */
394 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700395 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700396 /**
397 * This is the process holding the activity the user last visited that is in a different process
398 * from the one they are currently in.
399 */
400 WindowProcessController mPreviousProcess;
401 /** The time at which the previous process was last visible. */
402 long mPreviousProcessVisibleTime;
403
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700404 /** List of intents that were used to start the most recent tasks. */
405 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700406 /** State of external calls telling us if the device is awake or asleep. */
407 private boolean mKeyguardShown = false;
408
409 // Wrapper around VoiceInteractionServiceManager
410 private AssistUtils mAssistUtils;
411
412 // VoiceInteraction session ID that changes for each new request except when
413 // being called for multi-window assist in a single session.
414 private int mViSessionId = 1000;
415
416 // How long to wait in getAssistContextExtras for the activity and foreground services
417 // to respond with the result.
418 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
419
420 // How long top wait when going through the modern assist (which doesn't need to block
421 // on getting this result before starting to launch its UI).
422 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
423
424 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
425 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
426
Alison Cichowlas3e340502018-08-07 17:15:01 -0400427 // Permission tokens are used to temporarily granted a trusted app the ability to call
428 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
429 // showing any appropriate error messages to the user.
430 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
431 10 * MINUTE_IN_MILLIS;
432
433 // How long before the service actually expires a token. This is slightly longer than
434 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
435 // expiration exception.
436 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
437 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
438
439 // How long the service will remember expired tokens, for the purpose of providing error
440 // messaging when a client uses an expired token.
441 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
442 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
443
444 // Activity tokens of system activities that are delegating their call to
445 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
446 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
447
448 // Permission tokens that have expired, but we remember for error reporting.
449 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
450
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700451 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
452
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700453 // Keeps track of the active voice interaction service component, notified from
454 // VoiceInteractionManagerService
455 ComponentName mActiveVoiceInteractionServiceComponent;
456
Michal Karpinskida34cd42019-04-02 19:46:52 +0100457 // A map userId and all its companion app uids
458 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000459
Wale Ogunwalee2172292018-10-25 10:11:10 -0700460 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700461 KeyguardController mKeyguardController;
462 private final ClientLifecycleManager mLifecycleManager;
463 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700464 /** The controller for all operations related to locktask. */
465 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700466 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700467
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700468 boolean mSuppressResizeConfigChanges;
469
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700470 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700471 new UpdateConfigurationResult();
472
473 static final class UpdateConfigurationResult {
474 // Configuration changes that were updated.
475 int changes;
476 // If the activity was relaunched to match the new configuration.
477 boolean activityRelaunched;
478
479 void reset() {
480 changes = 0;
481 activityRelaunched = false;
482 }
483 }
484
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700485 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700486 private int mConfigurationSeq;
487 // To cache the list of supported system locales
488 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700489
490 /**
491 * Temp object used when global and/or display override configuration is updated. It is also
492 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
493 * anyone...
494 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700495 private Configuration mTempConfig = new Configuration();
496
Wale Ogunwalef6733932018-06-27 05:14:34 -0700497 /** Temporary to avoid allocations. */
498 final StringBuilder mStringBuilder = new StringBuilder(256);
499
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700500 // Amount of time after a call to stopAppSwitches() during which we will
501 // prevent further untrusted switches from happening.
502 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
503
504 /**
505 * The time at which we will allow normal application switches again,
506 * after a call to {@link #stopAppSwitches()}.
507 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700508 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700509 /**
510 * This is set to true after the first switch after mAppSwitchesAllowedTime
511 * is set; any switches after that will clear the time.
512 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700513 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700514
Ricky Wai906af482019-06-03 17:25:28 +0100515 /**
516 * Last stop app switches time, apps finished before this time cannot start background activity
517 * even if they are in grace period.
518 */
519 private long mLastStopAppSwitchesTime;
520
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700521 IActivityController mController = null;
522 boolean mControllerIsAMonkey = false;
523
Wale Ogunwale214f3482018-10-04 11:00:47 -0700524 final int mFactoryTest;
525
526 /** Used to control how we initialize the service. */
527 ComponentName mTopComponent;
528 String mTopAction = Intent.ACTION_MAIN;
529 String mTopData;
530
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800531 /** Profiling app information. */
532 String mProfileApp = null;
533 WindowProcessController mProfileProc = null;
534 ProfilerInfo mProfilerInfo = null;
535
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700536 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700537 * Dump of the activity state at the time of the last ANR. Cleared after
538 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
539 */
540 String mLastANRState;
541
542 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700543 * Used to retain an update lock when the foreground activity is in
544 * immersive mode.
545 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700546 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700547
548 /**
549 * Packages that are being allowed to perform unrestricted app switches. Mapping is
550 * User -> Type -> uid.
551 */
552 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
553
554 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700555 private int mThumbnailWidth;
556 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700557
558 /**
559 * Flag that indicates if multi-window is enabled.
560 *
561 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
562 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
563 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
564 * At least one of the forms of multi-window must be enabled in order for this flag to be
565 * initialized to 'true'.
566 *
567 * @see #mSupportsSplitScreenMultiWindow
568 * @see #mSupportsFreeformWindowManagement
569 * @see #mSupportsPictureInPicture
570 * @see #mSupportsMultiDisplay
571 */
572 boolean mSupportsMultiWindow;
573 boolean mSupportsSplitScreenMultiWindow;
574 boolean mSupportsFreeformWindowManagement;
575 boolean mSupportsPictureInPicture;
576 boolean mSupportsMultiDisplay;
577 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700578 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700579
580 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
581
582 // VR Vr2d Display Id.
583 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700584
Wale Ogunwalef6733932018-06-27 05:14:34 -0700585 /**
586 * Set while we are wanting to sleep, to prevent any
587 * activities from being started/resumed.
588 *
589 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
590 *
591 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
592 * while in the sleep state until there is a pending transition out of sleep, in which case
593 * mSleeping is set to false, and remains false while awake.
594 *
595 * Whether mSleeping can quickly toggled between true/false without the device actually
596 * display changing states is undefined.
597 */
598 private boolean mSleeping = false;
599
600 /**
Galia Peycheva480275a2020-03-18 17:33:42 +0100601 * The mDreaming state is set by the {@link DreamManagerService} when it receives a request to
602 * start/stop the dream. It is set to true shortly before the {@link DreamService} is started.
603 * It is set to false after the {@link DreamService} is stopped.
604 */
605 private boolean mDreaming = false;
606
607 /**
Wale Ogunwalef6733932018-06-27 05:14:34 -0700608 * The process state used for processes that are running the top activities.
609 * This changes between TOP and TOP_SLEEPING to following mSleeping.
610 */
611 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
612
Riddle Hsua0022cd2019-09-09 21:12:41 +0800613 @Retention(RetentionPolicy.SOURCE)
614 @IntDef({
615 LAYOUT_REASON_CONFIG_CHANGED,
616 LAYOUT_REASON_VISIBILITY_CHANGED,
617 })
618 @interface LayoutReason {}
619 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
620 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
621
622 /** The reasons to perform surface placement. */
623 @LayoutReason
624 private int mLayoutReasons;
625
Wale Ogunwalef6733932018-06-27 05:14:34 -0700626 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
627 // automatically. Important for devices without direct input devices.
628 private boolean mShowDialogs = true;
629
630 /** Set if we are shutting down the system, similar to sleeping. */
631 boolean mShuttingDown = false;
632
633 /**
634 * We want to hold a wake lock while running a voice interaction session, since
635 * this may happen with the screen off and we need to keep the CPU running to
636 * be able to continue to interact with the user.
637 */
638 PowerManager.WakeLock mVoiceWakeLock;
639
640 /**
641 * Set while we are running a voice interaction. This overrides sleeping while it is active.
642 */
643 IVoiceInteractionSession mRunningVoice;
644
645 /**
646 * The last resumed activity. This is identical to the current resumed activity most
647 * of the time but could be different when we're pausing one activity before we resume
648 * another activity.
649 */
650 ActivityRecord mLastResumedActivity;
651
652 /**
653 * The activity that is currently being traced as the active resumed activity.
654 *
655 * @see #updateResumedAppTrace
656 */
657 private @Nullable ActivityRecord mTracedResumedActivity;
658
659 /** If non-null, we are tracking the time the user spends in the currently focused app. */
660 AppTimeTracker mCurAppTimeTracker;
661
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700662 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700663
Wale Ogunwale53783742018-09-16 10:21:51 -0700664 /**
665 * Packages that the user has asked to have run in screen size
666 * compatibility mode instead of filling the screen.
667 */
668 CompatModePackages mCompatModePackages;
669
Wale Ogunwalef6733932018-06-27 05:14:34 -0700670 private FontScaleSettingObserver mFontScaleSettingObserver;
671
Wale Ogunwale568f9f412020-03-21 22:27:35 -0700672 WindowOrganizerController mWindowOrganizerController;
673 TaskOrganizerController mTaskOrganizerController;
Robert Carr8a2f9132019-11-11 15:03:15 -0800674
Ricky Wai96f5c352019-04-10 18:40:17 +0100675 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000676
Wale Ogunwalef6733932018-06-27 05:14:34 -0700677 private final class FontScaleSettingObserver extends ContentObserver {
678 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
679 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
680
681 public FontScaleSettingObserver() {
682 super(mH);
683 final ContentResolver resolver = mContext.getContentResolver();
684 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
685 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
686 UserHandle.USER_ALL);
687 }
688
689 @Override
Jeff Sharkey8b0cff72020-03-09 15:49:01 -0600690 public void onChange(boolean selfChange, Collection<Uri> uris, int flags,
Riddle Hsu9c024d12020-03-09 16:10:07 +0800691 @UserIdInt int userId) {
692 for (Uri uri : uris) {
693 if (mFontScaleUri.equals(uri)) {
694 updateFontScaleIfNeeded(userId);
695 } else if (mHideErrorDialogsUri.equals(uri)) {
696 synchronized (mGlobalLock) {
697 updateShouldShowDialogsLocked(getGlobalConfiguration());
698 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700699 }
700 }
701 }
702 }
703
Riddle Hsua0536432019-02-16 00:38:59 +0800704 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
705 @Target(ElementType.METHOD)
706 @Retention(RetentionPolicy.SOURCE)
707 @interface HotPath {
708 int NONE = 0;
709 int OOM_ADJUSTMENT = 1;
710 int LRU_UPDATE = 2;
711 int PROCESS_CHANGE = 3;
712 int caller() default NONE;
713 }
714
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800715 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
716 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900717 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800718 mAmInternal.updateOomAdj();
719 }
720 };
721
Charles Chen8d98dd22018-12-26 17:36:54 +0800722 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
723 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700724 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700725 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700726 mSystemThread = ActivityThread.currentActivityThread();
727 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700728 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800729 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700730 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale568f9f412020-03-21 22:27:35 -0700731 mWindowOrganizerController = new WindowOrganizerController(this);
732 mTaskOrganizerController = mWindowOrganizerController.mTaskOrganizerController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700733 }
734
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700735 public void onSystemReady() {
736 synchronized (mGlobalLock) {
737 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
738 PackageManager.FEATURE_CANT_SAVE_STATE);
739 mAssistUtils = new AssistUtils(mContext);
740 mVrController.onSystemReady();
741 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700742 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700743 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700744 }
745
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700746 public void onInitPowerManagement() {
747 synchronized (mGlobalLock) {
748 mStackSupervisor.initPowerManagement();
749 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
750 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
751 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
752 mVoiceWakeLock.setReferenceCounted(false);
753 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700754 }
755
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700756 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700757 mFontScaleSettingObserver = new FontScaleSettingObserver();
758 }
759
Wale Ogunwale59507092018-10-29 09:00:30 -0700760 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700761 final boolean freeformWindowManagement =
762 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
763 || Settings.Global.getInt(
764 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
765
766 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
767 final boolean supportsPictureInPicture = supportsMultiWindow &&
768 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
769 final boolean supportsSplitScreenMultiWindow =
770 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
771 final boolean supportsMultiDisplay = mContext.getPackageManager()
772 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700773 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
774 final boolean forceResizable = Settings.Global.getInt(
775 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700776 final boolean sizeCompatFreeform = Settings.Global.getInt(
777 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700778
779 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900780 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700781
782 final Configuration configuration = new Configuration();
783 Settings.System.getConfiguration(resolver, configuration);
784 if (forceRtl) {
785 // This will take care of setting the correct layout direction flags
786 configuration.setLayoutDirection(configuration.locale);
787 }
788
789 synchronized (mGlobalLock) {
790 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700791 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700792 final boolean multiWindowFormEnabled = freeformWindowManagement
793 || supportsSplitScreenMultiWindow
794 || supportsPictureInPicture
795 || supportsMultiDisplay;
796 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
797 mSupportsMultiWindow = true;
798 mSupportsFreeformWindowManagement = freeformWindowManagement;
799 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
800 mSupportsPictureInPicture = supportsPictureInPicture;
801 mSupportsMultiDisplay = supportsMultiDisplay;
802 } else {
803 mSupportsMultiWindow = false;
804 mSupportsFreeformWindowManagement = false;
805 mSupportsSplitScreenMultiWindow = false;
806 mSupportsPictureInPicture = false;
807 mSupportsMultiDisplay = false;
808 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700809 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700810 // This happens before any activities are started, so we can change global configuration
811 // in-place.
812 updateConfigurationLocked(configuration, null, true);
813 final Configuration globalConfig = getGlobalConfiguration();
814 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
815
816 // Load resources only after the current configuration has been set.
817 final Resources res = mContext.getResources();
818 mThumbnailWidth = res.getDimensionPixelSize(
819 com.android.internal.R.dimen.thumbnail_width);
820 mThumbnailHeight = res.getDimensionPixelSize(
821 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700822 }
823 }
824
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800825 public WindowManagerGlobalLock getGlobalLock() {
826 return mGlobalLock;
827 }
828
Yunfan Chen585f2932019-01-29 16:04:45 +0900829 /** For test purpose only. */
830 @VisibleForTesting
831 public ActivityTaskManagerInternal getAtmInternal() {
832 return mInternal;
833 }
834
Riddle Hsud93a6c42018-11-29 21:50:06 +0800835 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
836 Looper looper) {
837 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700838 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700839 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700840 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800841 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700842 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700843 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700844 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700845
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700846 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700847 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700848 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700849 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700850 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700851 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700852 mKeyguardController = mStackSupervisor.getKeyguardController();
853 }
854
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700855 public void onActivityManagerInternalAdded() {
856 synchronized (mGlobalLock) {
857 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
858 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
859 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700860 }
861
Yunfan Chen75157d72018-07-27 14:47:21 +0900862 int increaseConfigurationSeqLocked() {
863 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
864 return mConfigurationSeq;
865 }
866
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700867 protected ActivityStackSupervisor createStackSupervisor() {
868 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
869 supervisor.initialize();
870 return supervisor;
871 }
872
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800873 protected AppWarnings createAppWarnings(
874 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
875 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
876 }
877
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700878 public void setWindowManager(WindowManagerService wm) {
879 synchronized (mGlobalLock) {
880 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800881 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800882 mTempConfig.setToDefaults();
883 mTempConfig.setLocales(LocaleList.getDefault());
884 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800885 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700886 mLockTaskController.setWindowManager(wm);
887 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800888 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700889 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700890 }
891
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700892 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
893 synchronized (mGlobalLock) {
894 mUsageStatsInternal = usageStatsManager;
895 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700896 }
897
Wale Ogunwalef6733932018-06-27 05:14:34 -0700898 UserManagerService getUserManager() {
899 if (mUserManager == null) {
900 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
901 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
902 }
903 return mUserManager;
904 }
905
Philip P. Moltmannee295092020-02-10 08:46:26 -0800906 AppOpsManager getAppOpsManager() {
907 if (mAppOpsManager == null) {
908 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Wale Ogunwalef6733932018-06-27 05:14:34 -0700909 }
Philip P. Moltmannee295092020-02-10 08:46:26 -0800910 return mAppOpsManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700911 }
912
913 boolean hasUserRestriction(String restriction, int userId) {
914 return getUserManager().hasUserRestriction(restriction, userId);
915 }
916
Michal Karpinski15486842019-04-25 17:33:42 +0100917 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
Philip P. Moltmannee295092020-02-10 08:46:26 -0800918 final int mode = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
919 callingUid, callingPackage, /* featureId */ null, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100920 if (mode == AppOpsManager.MODE_DEFAULT) {
921 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
922 == PERMISSION_GRANTED;
923 }
924 return mode == AppOpsManager.MODE_ALLOWED;
925 }
926
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700927 @VisibleForTesting
928 protected void setRecentTasks(RecentTasks recentTasks) {
929 mRecentTasks = recentTasks;
930 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700931 }
932
933 RecentTasks getRecentTasks() {
934 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700935 }
936
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700937 ClientLifecycleManager getLifecycleManager() {
938 return mLifecycleManager;
939 }
940
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700941 ActivityStartController getActivityStartController() {
942 return mActivityStartController;
943 }
944
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700945 TaskChangeNotificationController getTaskChangeNotificationController() {
946 return mTaskChangeNotificationController;
947 }
948
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700949 LockTaskController getLockTaskController() {
950 return mLockTaskController;
951 }
952
Yunfan Chen75157d72018-07-27 14:47:21 +0900953 /**
954 * Return the global configuration used by the process corresponding to the input pid. This is
955 * usually the global configuration with some overrides specific to that process.
956 */
957 Configuration getGlobalConfigurationForCallingPid() {
958 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800959 return getGlobalConfigurationForPid(pid);
960 }
961
962 /**
963 * Return the global configuration used by the process corresponding to the given pid.
964 */
965 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900966 if (pid == MY_PID || pid < 0) {
967 return getGlobalConfiguration();
968 }
969 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100970 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900971 return app != null ? app.getConfiguration() : getGlobalConfiguration();
972 }
973 }
974
975 /**
976 * Return the device configuration info used by the process corresponding to the input pid.
977 * The value is consistent with the global configuration for the process.
978 */
979 @Override
980 public ConfigurationInfo getDeviceConfigurationInfo() {
981 ConfigurationInfo config = new ConfigurationInfo();
982 synchronized (mGlobalLock) {
983 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
984 config.reqTouchScreen = globalConfig.touchscreen;
985 config.reqKeyboardType = globalConfig.keyboard;
986 config.reqNavigation = globalConfig.navigation;
987 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
988 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
989 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
990 }
991 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
992 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
993 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
994 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700995 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900996 }
997 return config;
998 }
999
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001000 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -07001001 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001002 }
1003
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001004 public static final class Lifecycle extends SystemService {
1005 private final ActivityTaskManagerService mService;
1006
1007 public Lifecycle(Context context) {
1008 super(context);
1009 mService = new ActivityTaskManagerService(context);
1010 }
1011
1012 @Override
1013 public void onStart() {
1014 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001015 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001016 }
1017
Garfield Tan891146c2018-10-09 12:14:00 -07001018 @Override
1019 public void onUnlockUser(int userId) {
1020 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001021 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001022 }
1023 }
1024
1025 @Override
1026 public void onCleanupUser(int userId) {
1027 synchronized (mService.getGlobalLock()) {
1028 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1029 }
1030 }
1031
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001032 public ActivityTaskManagerService getService() {
1033 return mService;
1034 }
1035 }
1036
1037 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038 public final int startActivity(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001039 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1040 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1041 Bundle bOptions) {
1042 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1043 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044 UserHandle.getCallingUserId());
1045 }
1046
1047 @Override
1048 public final int startActivities(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001049 String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
1050 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001051 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001052 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001053 enforceNotIsolatedCaller(reason);
1054 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001055 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001056 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001057 callingFeatureId, intents, resolvedTypes, resultTo,
1058 SafeActivityOptions.fromBundle(bOptions), userId, reason,
1059 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060 }
1061
1062 @Override
1063 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001064 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1065 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1066 Bundle bOptions, int userId) {
1067 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1068 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001069 true /*validateIncomingUser*/);
1070 }
1071
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001072 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001073 @Nullable String callingFeatureId, Intent intent, String resolvedType,
1074 IBinder resultTo, String resultWho, int requestCode, int startFlags,
1075 ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001076 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001077 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001078
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001079 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001080 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1081
1082 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001083 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001084 .setCaller(caller)
1085 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001086 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001087 .setResolvedType(resolvedType)
1088 .setResultTo(resultTo)
1089 .setResultWho(resultWho)
1090 .setRequestCode(requestCode)
1091 .setStartFlags(startFlags)
1092 .setProfilerInfo(profilerInfo)
1093 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001094 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001095 .execute();
1096
1097 }
1098
1099 @Override
1100 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1101 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001102 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1103 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001104 // Refuse possible leaked file descriptors
1105 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1106 throw new IllegalArgumentException("File descriptors passed in Intent");
1107 }
1108
1109 if (!(target instanceof PendingIntentRecord)) {
1110 throw new IllegalArgumentException("Bad PendingIntent object");
1111 }
1112
1113 PendingIntentRecord pir = (PendingIntentRecord)target;
1114
1115 synchronized (mGlobalLock) {
1116 // If this is coming from the currently resumed activity, it is
1117 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001118 final ActivityStack stack = getTopDisplayFocusedStack();
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001119 if (stack != null && stack.mResumedActivity != null
1120 && stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001121 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001122 }
1123 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001124 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001125 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001126 }
1127
1128 @Override
1129 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1130 Bundle bOptions) {
1131 // Refuse possible leaked file descriptors
1132 if (intent != null && intent.hasFileDescriptors()) {
1133 throw new IllegalArgumentException("File descriptors passed in Intent");
1134 }
1135 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1136
1137 synchronized (mGlobalLock) {
1138 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1139 if (r == null) {
1140 SafeActivityOptions.abort(options);
1141 return false;
1142 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001143 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001144 // The caller is not running... d'oh!
1145 SafeActivityOptions.abort(options);
1146 return false;
1147 }
1148 intent = new Intent(intent);
1149 // The caller is not allowed to change the data.
1150 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1151 // And we are resetting to find the next component...
1152 intent.setComponent(null);
1153
1154 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1155
1156 ActivityInfo aInfo = null;
1157 try {
1158 List<ResolveInfo> resolves =
1159 AppGlobals.getPackageManager().queryIntentActivities(
1160 intent, r.resolvedType,
1161 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1162 UserHandle.getCallingUserId()).getList();
1163
1164 // Look for the original activity in the list...
1165 final int N = resolves != null ? resolves.size() : 0;
1166 for (int i=0; i<N; i++) {
1167 ResolveInfo rInfo = resolves.get(i);
1168 if (rInfo.activityInfo.packageName.equals(r.packageName)
1169 && rInfo.activityInfo.name.equals(r.info.name)) {
1170 // We found the current one... the next matching is
1171 // after it.
1172 i++;
1173 if (i<N) {
1174 aInfo = resolves.get(i).activityInfo;
1175 }
1176 if (debug) {
1177 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1178 + "/" + r.info.name);
1179 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1180 ? "null" : aInfo.packageName + "/" + aInfo.name));
1181 }
1182 break;
1183 }
1184 }
1185 } catch (RemoteException e) {
1186 }
1187
1188 if (aInfo == null) {
1189 // Nobody who is next!
1190 SafeActivityOptions.abort(options);
1191 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1192 return false;
1193 }
1194
1195 intent.setComponent(new ComponentName(
1196 aInfo.applicationInfo.packageName, aInfo.name));
1197 intent.setFlags(intent.getFlags()&~(
1198 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1199 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1200 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1201 FLAG_ACTIVITY_NEW_TASK));
1202
1203 // Okay now we need to start the new activity, replacing the currently running activity.
1204 // This is a little tricky because we want to start the new one as if the current one is
1205 // finished, but not finish the current one first so that there is no flicker.
1206 // And thus...
1207 final boolean wasFinishing = r.finishing;
1208 r.finishing = true;
1209
1210 // Propagate reply information over to the new activity.
1211 final ActivityRecord resultTo = r.resultTo;
1212 final String resultWho = r.resultWho;
1213 final int requestCode = r.requestCode;
1214 r.resultTo = null;
1215 if (resultTo != null) {
1216 resultTo.removeResultsLocked(r, resultWho, requestCode);
1217 }
1218
1219 final long origId = Binder.clearCallingIdentity();
1220 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001221 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001222 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001223 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001224 .setResolvedType(r.resolvedType)
1225 .setActivityInfo(aInfo)
1226 .setResultTo(resultTo != null ? resultTo.appToken : null)
1227 .setResultWho(resultWho)
1228 .setRequestCode(requestCode)
1229 .setCallingPid(-1)
1230 .setCallingUid(r.launchedFromUid)
1231 .setCallingPackage(r.launchedFromPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001232 .setCallingFeatureId(r.launchedFromFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001233 .setRealCallingPid(-1)
1234 .setRealCallingUid(r.launchedFromUid)
1235 .setActivityOptions(options)
1236 .execute();
1237 Binder.restoreCallingIdentity(origId);
1238
1239 r.finishing = wasFinishing;
1240 if (res != ActivityManager.START_SUCCESS) {
1241 return false;
1242 }
1243 return true;
1244 }
1245 }
1246
Galia Peychevaed401cc2020-03-19 20:28:09 +01001247 private void enforceCallerIsDream(String callerPackageName) {
Galia Peycheva52e89222020-02-18 23:41:43 +01001248 final long origId = Binder.clearCallingIdentity();
Galia Peychevaed401cc2020-03-19 20:28:09 +01001249 try {
1250 if (!ActivityRecord.canLaunchDreamActivity(callerPackageName)) {
1251 throw new SecurityException("The dream activity can be started only when the device"
1252 + " is dreaming and only by the active dream package.");
1253 }
1254 } finally {
1255 Binder.restoreCallingIdentity(origId);
Galia Peycheva52e89222020-02-18 23:41:43 +01001256 }
Galia Peychevaed401cc2020-03-19 20:28:09 +01001257 }
1258
1259 @Override
1260 public boolean startDreamActivity(@NonNull Intent intent) {
1261 assertPackageMatchesCallingUid(intent.getPackage());
1262 enforceCallerIsDream(intent.getPackage());
Galia Peycheva52e89222020-02-18 23:41:43 +01001263
Galia Peycheva6861e912019-08-21 10:20:23 +02001264 final ActivityInfo a = new ActivityInfo();
1265 a.theme = com.android.internal.R.style.Theme_Dream;
1266 a.exported = true;
1267 a.name = DreamActivity.class.getName();
Galia Peycheva6861e912019-08-21 10:20:23 +02001268 a.enabled = true;
1269 a.launchMode = ActivityInfo.LAUNCH_SINGLE_INSTANCE;
Galia Peycheva6861e912019-08-21 10:20:23 +02001270 a.persistableMode = ActivityInfo.PERSIST_NEVER;
1271 a.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1272 a.colorMode = ActivityInfo.COLOR_MODE_DEFAULT;
1273 a.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1274
Galia Peycheva45f48d32020-02-20 15:39:10 +01001275 final ActivityOptions options = ActivityOptions.makeBasic();
1276 options.setLaunchActivityType(ACTIVITY_TYPE_DREAM);
1277
Galia Peychevaed401cc2020-03-19 20:28:09 +01001278 synchronized (mGlobalLock) {
1279 final WindowProcessController process = mProcessMap.getProcess(Binder.getCallingPid());
1280
1281 a.packageName = process.mInfo.packageName;
1282 a.applicationInfo = process.mInfo;
1283 a.processName = process.mInfo.processName;
1284 a.uiOptions = process.mInfo.uiOptions;
1285 a.taskAffinity = "android:" + a.packageName + "/dream";
1286
1287 final int callingUid = Binder.getCallingUid();
1288 final int callingPid = Binder.getCallingPid();
1289
1290 final long origId = Binder.clearCallingIdentity();
1291 try {
1292 getActivityStartController().obtainStarter(intent, "dream")
1293 .setCallingUid(callingUid)
1294 .setCallingPid(callingPid)
1295 .setActivityInfo(a)
1296 .setActivityOptions(options.toBundle())
1297 // To start the dream from background, we need to start it from a persistent
1298 // system process. Here we set the real calling uid to the system server uid
1299 .setRealCallingUid(Binder.getCallingUid())
1300 .setAllowBackgroundActivityStart(true)
1301 .execute();
1302 return true;
1303 } finally {
1304 Binder.restoreCallingIdentity(origId);
1305 }
Galia Peycheva6861e912019-08-21 10:20:23 +02001306 }
1307 }
1308
1309 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001310 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001311 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1312 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1313 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001314 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001315 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001316 enforceNotIsolatedCaller("startActivityAndWait");
1317 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1318 userId, "startActivityAndWait");
1319 // TODO: Switch to user app stacks here.
1320 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1321 .setCaller(caller)
1322 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001323 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001324 .setResolvedType(resolvedType)
1325 .setResultTo(resultTo)
1326 .setResultWho(resultWho)
1327 .setRequestCode(requestCode)
1328 .setStartFlags(startFlags)
1329 .setActivityOptions(bOptions)
1330 .setUserId(userId)
1331 .setProfilerInfo(profilerInfo)
1332 .setWaitResult(res)
1333 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001334 return res;
1335 }
1336
1337 @Override
1338 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001339 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1340 String resultWho, int requestCode, int startFlags, Configuration config,
1341 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001342 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001343 enforceNotIsolatedCaller("startActivityWithConfig");
1344 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1345 "startActivityWithConfig");
1346 // TODO: Switch to user app stacks here.
1347 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1348 .setCaller(caller)
1349 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001350 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001351 .setResolvedType(resolvedType)
1352 .setResultTo(resultTo)
1353 .setResultWho(resultWho)
1354 .setRequestCode(requestCode)
1355 .setStartFlags(startFlags)
1356 .setGlobalConfiguration(config)
1357 .setActivityOptions(bOptions)
1358 .setUserId(userId)
1359 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001360 }
1361
Robert Carr8a2f9132019-11-11 15:03:15 -08001362 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001363 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1364 int callingUid = Binder.getCallingUid();
1365 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1366 throw new SecurityException("Only the system process can request a permission token, "
1367 + "received request from uid: " + callingUid);
1368 }
1369 IBinder permissionToken = new Binder();
1370 synchronized (mGlobalLock) {
1371 mStartActivitySources.put(permissionToken, delegatorToken);
1372 }
1373
1374 Message expireMsg = PooledLambda.obtainMessage(
1375 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1376 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1377
1378 Message forgetMsg = PooledLambda.obtainMessage(
1379 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1380 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1381
1382 return permissionToken;
1383 }
1384
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001385 @Override
1386 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1387 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001388 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1389 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001390 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001391 // permission grants) as any app that may launch one of your own activities. So we only
1392 // allow this in two cases:
1393 // 1) The caller is an activity that is part of the core framework, and then only when it
1394 // is running as the system.
1395 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1396 // can only be requested by a system activity, which may then delegate this call to
1397 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001398 final ActivityRecord sourceRecord;
1399 final int targetUid;
1400 final String targetPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001401 final String targetFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001402 final boolean isResolver;
1403 synchronized (mGlobalLock) {
1404 if (resultTo == null) {
1405 throw new SecurityException("Must be called from an activity");
1406 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001407 final IBinder sourceToken;
1408 if (permissionToken != null) {
1409 // To even attempt to use a permissionToken, an app must also have this signature
1410 // permission.
1411 mAmInternal.enforceCallingPermission(
1412 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1413 "startActivityAsCaller");
1414 // If called with a permissionToken, we want the sourceRecord from the delegator
1415 // activity that requested this token.
1416 sourceToken = mStartActivitySources.remove(permissionToken);
1417 if (sourceToken == null) {
1418 // Invalid permissionToken, check if it recently expired.
1419 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1420 throw new SecurityException("Called with expired permission token: "
1421 + permissionToken);
1422 } else {
1423 throw new SecurityException("Called with invalid permission token: "
1424 + permissionToken);
1425 }
1426 }
1427 } else {
1428 // This method was called directly by the source.
1429 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001430 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001431
Louis Chang149d5c82019-12-30 09:47:39 +08001432 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001433 if (sourceRecord == null) {
1434 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001435 }
1436 if (sourceRecord.app == null) {
1437 throw new SecurityException("Called without a process attached to activity");
1438 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001439
1440 // Whether called directly or from a delegate, the source activity must be from the
1441 // android package.
1442 if (!sourceRecord.info.packageName.equals("android")) {
1443 throw new SecurityException("Must be called from an activity that is "
1444 + "declared in the android package");
1445 }
1446
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001447 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001448 // This is still okay, as long as this activity is running under the
1449 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001450 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001451 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001452 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 + " must be system uid or original calling uid "
1454 + sourceRecord.launchedFromUid);
1455 }
1456 }
1457 if (ignoreTargetSecurity) {
1458 if (intent.getComponent() == null) {
1459 throw new SecurityException(
1460 "Component must be specified with ignoreTargetSecurity");
1461 }
1462 if (intent.getSelector() != null) {
1463 throw new SecurityException(
1464 "Selector not allowed with ignoreTargetSecurity");
1465 }
1466 }
1467 targetUid = sourceRecord.launchedFromUid;
1468 targetPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001469 targetFeatureId = sourceRecord.launchedFromFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001470 isResolver = sourceRecord.isResolverOrChildActivity();
1471 }
1472
1473 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001474 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001475 }
1476
1477 // TODO: Switch to user app stacks here.
1478 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001479 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001480 .setCallingUid(targetUid)
1481 .setCallingPackage(targetPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001482 .setCallingFeatureId(targetFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001483 .setResolvedType(resolvedType)
1484 .setResultTo(resultTo)
1485 .setResultWho(resultWho)
1486 .setRequestCode(requestCode)
1487 .setStartFlags(startFlags)
1488 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001489 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001490 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1491 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001492 // The target may well be in the background, which would normally prevent it
1493 // from starting an activity. Here we definitely want the start to succeed.
1494 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001495 .execute();
1496 } catch (SecurityException e) {
1497 // XXX need to figure out how to propagate to original app.
1498 // A SecurityException here is generally actually a fault of the original
1499 // calling activity (such as a fairly granting permissions), so propagate it
1500 // back to them.
1501 /*
1502 StringBuilder msg = new StringBuilder();
1503 msg.append("While launching");
1504 msg.append(intent.toString());
1505 msg.append(": ");
1506 msg.append(e.getMessage());
1507 */
1508 throw e;
1509 }
1510 }
1511
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001512 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1513 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001514 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001515 }
1516
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001517 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001518 public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1519 int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001520 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1521 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001522 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001523 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001524 if (session == null || interactor == null) {
1525 throw new NullPointerException("null session or interactor");
1526 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001527 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001528 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001529 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001530 .setCallingUid(callingUid)
1531 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001532 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001533 .setResolvedType(resolvedType)
1534 .setVoiceSession(session)
1535 .setVoiceInteractor(interactor)
1536 .setStartFlags(startFlags)
1537 .setProfilerInfo(profilerInfo)
1538 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001539 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001540 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001541 .execute();
1542 }
1543
1544 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001545 public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1546 int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1547 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001548 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001549 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1550 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001552 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001553 .setCallingUid(callingUid)
1554 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001555 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001556 .setResolvedType(resolvedType)
1557 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001558 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001559 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001560 .execute();
1561 }
1562
Riddle Hsu609a8e22019-06-27 16:46:29 -06001563 /**
1564 * Start the recents activity to perform the recents animation.
1565 *
1566 * @param intent The intent to start the recents activity.
1567 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1568 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001569 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001570 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1571 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001572 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001573 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001574 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001575 final long origId = Binder.clearCallingIdentity();
1576 try {
1577 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001578 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
Philip P. Moltmannee295092020-02-10 08:46:26 -08001579 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001580 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001581 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001582
1583 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001584 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001585 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001586 recentsFeatureId, recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001587 if (recentsAnimationRunner == null) {
1588 anim.preloadRecentsActivity();
1589 } else {
1590 anim.startRecentsActivity(recentsAnimationRunner);
1591 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001592 }
1593 } finally {
1594 Binder.restoreCallingIdentity(origId);
1595 }
1596 }
1597
1598 @Override
1599 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001600 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001601 "startActivityFromRecents()");
1602
1603 final int callingPid = Binder.getCallingPid();
1604 final int callingUid = Binder.getCallingUid();
1605 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1606 final long origId = Binder.clearCallingIdentity();
1607 try {
1608 synchronized (mGlobalLock) {
1609 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1610 safeOptions);
1611 }
1612 } finally {
1613 Binder.restoreCallingIdentity(origId);
1614 }
1615 }
1616
1617 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001618 * Public API to check if the client is allowed to start an activity on specified display.
1619 *
1620 * If the target display is private or virtual, some restrictions will apply.
1621 *
1622 * @param displayId Target display id.
1623 * @param intent Intent used to launch the activity.
1624 * @param resolvedType The MIME type of the intent.
1625 * @param userId The id of the user for whom the call is made.
1626 * @return {@code true} if a call to start an activity on the target display should succeed and
1627 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1628 */
1629 @Override
1630 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1631 String resolvedType, int userId) {
1632 final int callingUid = Binder.getCallingUid();
1633 final int callingPid = Binder.getCallingPid();
1634 final long origId = Binder.clearCallingIdentity();
1635
1636 try {
1637 // Collect information about the target of the Intent.
1638 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1639 0 /* startFlags */, null /* profilerInfo */, userId,
1640 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1641 UserHandle.USER_NULL));
1642 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1643
1644 synchronized (mGlobalLock) {
1645 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1646 aInfo);
1647 }
1648 } finally {
1649 Binder.restoreCallingIdentity(origId);
1650 }
1651 }
1652
1653 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001654 * This is the internal entry point for handling Activity.finish().
1655 *
1656 * @param token The Binder token referencing the Activity we want to finish.
1657 * @param resultCode Result code, if any, from this Activity.
1658 * @param resultData Result data (Intent), if any, from this Activity.
1659 * @param finishTask Whether to finish the task associated with this Activity.
1660 *
1661 * @return Returns true if the activity successfully finished, or false if it is still running.
1662 */
1663 @Override
1664 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1665 int finishTask) {
1666 // Refuse possible leaked file descriptors
1667 if (resultData != null && resultData.hasFileDescriptors()) {
1668 throw new IllegalArgumentException("File descriptors passed in Intent");
1669 }
1670
1671 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001672 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001673 if (r == null) {
1674 return true;
1675 }
1676 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001677 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001678 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001679 if (rootR == null) {
1680 Slog.w(TAG, "Finishing task with all activities already finished");
1681 }
1682 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1683 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001684 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001685 return false;
1686 }
1687
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001688 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1689 // We should consolidate.
1690 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001691 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001692 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001693 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001694 if (next != null) {
1695 // ask watcher if this is allowed
1696 boolean resumeOK = true;
1697 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001698 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001699 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001700 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001701 Watchdog.getInstance().setActivityController(null);
1702 }
1703
1704 if (!resumeOK) {
1705 Slog.i(TAG, "Not finishing activity because controller resumed");
1706 return false;
1707 }
1708 }
1709 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001710
1711 // note down that the process has finished an activity and is in background activity
1712 // starts grace period
1713 if (r.app != null) {
1714 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1715 }
1716
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001717 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001718 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001719 try {
1720 boolean res;
1721 final boolean finishWithRootActivity =
1722 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1723 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1724 || (finishWithRootActivity && r == rootR)) {
1725 // If requested, remove the task that is associated to this activity only if it
1726 // was the root activity in the task. The result code and data is ignored
1727 // because we don't support returning them across task boundaries. Also, to
1728 // keep backwards compatibility we remove the task from recents when finishing
1729 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001730 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001731 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001732 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001733 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001734 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001735 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001736 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001737 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001738 if (!res) {
1739 Slog.i(TAG, "Failed to finish by app-request");
1740 }
1741 }
1742 return res;
1743 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001744 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001745 Binder.restoreCallingIdentity(origId);
1746 }
1747 }
1748 }
1749
1750 @Override
1751 public boolean finishActivityAffinity(IBinder token) {
1752 synchronized (mGlobalLock) {
1753 final long origId = Binder.clearCallingIdentity();
1754 try {
1755 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1756 if (r == null) {
1757 return false;
1758 }
1759
1760 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1761 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001762 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001763 return false;
1764 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001765
1766 final PooledFunction p = PooledLambda.obtainFunction(
1767 ActivityRecord::finishIfSameAffinity, r,
1768 PooledLambda.__(ActivityRecord.class));
1769 r.getTask().forAllActivities(
1770 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1771 p.recycle();
1772
Andrii Kuliande93eff2019-07-12 12:21:27 -07001773 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001774 } finally {
1775 Binder.restoreCallingIdentity(origId);
1776 }
1777 }
1778 }
1779
1780 @Override
1781 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1782 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001783 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001784 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001785 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001786 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1787 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001788 return;
1789 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001790 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1791 false /* processPausingActivities */, config);
1792 if (stopProfiling && r.hasProcess()) {
1793 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001794 }
1795 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001796 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001797 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001798 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001799 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 }
1801
1802 @Override
1803 public final void activityResumed(IBinder token) {
1804 final long origId = Binder.clearCallingIdentity();
1805 synchronized (mGlobalLock) {
1806 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001807 }
1808 Binder.restoreCallingIdentity(origId);
1809 }
1810
1811 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001812 public final void activityTopResumedStateLost() {
1813 final long origId = Binder.clearCallingIdentity();
1814 synchronized (mGlobalLock) {
1815 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1816 }
1817 Binder.restoreCallingIdentity(origId);
1818 }
1819
1820 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001821 public final void activityPaused(IBinder token) {
1822 final long origId = Binder.clearCallingIdentity();
1823 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001824 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001825 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1826 if (r != null) {
1827 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001828 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001829 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001830 }
1831 Binder.restoreCallingIdentity(origId);
1832 }
1833
1834 @Override
1835 public final void activityStopped(IBinder token, Bundle icicle,
1836 PersistableBundle persistentState, CharSequence description) {
1837 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1838
1839 // Refuse possible leaked file descriptors
1840 if (icicle != null && icicle.hasFileDescriptors()) {
1841 throw new IllegalArgumentException("File descriptors passed in Bundle");
1842 }
1843
1844 final long origId = Binder.clearCallingIdentity();
1845
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001846 String restartingName = null;
1847 int restartingUid = 0;
1848 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001849 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001850 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001851 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001852 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001853 if (r.attachedToProcess()
1854 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1855 // The activity was requested to restart from
1856 // {@link #restartActivityProcessIfVisible}.
1857 restartingName = r.app.mName;
1858 restartingUid = r.app.mUid;
1859 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001860 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001861 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001862 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001863 }
1864
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001865 if (restartingName != null) {
1866 // In order to let the foreground activity can be restarted with its saved state from
1867 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1868 // until the activity reports stopped with the state. And the activity record will be
1869 // kept because the record state is restarting, then the activity will be restarted
1870 // immediately if it is still the top one.
1871 mStackSupervisor.removeRestartTimeouts(r);
1872 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1873 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001874 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001875
1876 Binder.restoreCallingIdentity(origId);
1877 }
1878
1879 @Override
1880 public final void activityDestroyed(IBinder token) {
1881 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1882 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001883 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001884 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001885 try {
1886 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1887 if (activity != null) {
1888 activity.destroyed("activityDestroyed");
1889 }
1890 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001891 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001892 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893 }
1894 }
1895 }
1896
1897 @Override
1898 public final void activityRelaunched(IBinder token) {
1899 final long origId = Binder.clearCallingIdentity();
1900 synchronized (mGlobalLock) {
1901 mStackSupervisor.activityRelaunchedLocked(token);
1902 }
1903 Binder.restoreCallingIdentity(origId);
1904 }
1905
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001906 @Override
1907 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1908 synchronized (mGlobalLock) {
1909 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1910 if (r == null) {
1911 return;
1912 }
1913 final long origId = Binder.clearCallingIdentity();
1914 try {
1915 r.setRequestedOrientation(requestedOrientation);
1916 } finally {
1917 Binder.restoreCallingIdentity(origId);
1918 }
1919 }
1920 }
1921
1922 @Override
1923 public int getRequestedOrientation(IBinder token) {
1924 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001925 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1926 return (r != null)
1927 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001928 }
1929 }
1930
1931 @Override
1932 public void setImmersive(IBinder token, boolean immersive) {
1933 synchronized (mGlobalLock) {
1934 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1935 if (r == null) {
1936 throw new IllegalArgumentException();
1937 }
1938 r.immersive = immersive;
1939
1940 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001941 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001942 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001943 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001944 }
1945 }
1946 }
1947
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001948 void applyUpdateLockStateLocked(ActivityRecord r) {
1949 // Modifications to the UpdateLock state are done on our handler, outside
1950 // the activity manager's locks. The new state is determined based on the
1951 // state *now* of the relevant activity record. The object is passed to
1952 // the handler solely for logging detail, not to be consulted/modified.
1953 final boolean nextState = r != null && r.immersive;
1954 mH.post(() -> {
1955 if (mUpdateLock.isHeld() != nextState) {
1956 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1957 "Applying new update lock state '" + nextState + "' for " + r);
1958 if (nextState) {
1959 mUpdateLock.acquire();
1960 } else {
1961 mUpdateLock.release();
1962 }
1963 }
1964 });
1965 }
1966
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001967 @Override
1968 public boolean isImmersive(IBinder token) {
1969 synchronized (mGlobalLock) {
1970 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1971 if (r == null) {
1972 throw new IllegalArgumentException();
1973 }
1974 return r.immersive;
1975 }
1976 }
1977
1978 @Override
1979 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001980 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001981 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001982 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
1983 if (topFocusedStack == null) {
1984 return false;
1985 }
1986
1987 final ActivityRecord r = topFocusedStack.topRunningActivity();
1988 return r != null && r.immersive;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001989 }
1990 }
1991
1992 @Override
1993 public void overridePendingTransition(IBinder token, String packageName,
1994 int enterAnim, int exitAnim) {
1995 synchronized (mGlobalLock) {
1996 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1997 if (self == null) {
1998 return;
1999 }
2000
2001 final long origId = Binder.clearCallingIdentity();
2002
2003 if (self.isState(
2004 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08002005 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08002006 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002007 }
2008
2009 Binder.restoreCallingIdentity(origId);
2010 }
2011 }
2012
2013 @Override
2014 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002015 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002016 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002017 final ActivityStack stack = getTopDisplayFocusedStack();
2018 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002019 if (r == null) {
2020 return ActivityManager.COMPAT_MODE_UNKNOWN;
2021 }
Wale Ogunwale53783742018-09-16 10:21:51 -07002022 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002023 }
2024 }
2025
2026 @Override
2027 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002028 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002029 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002030 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002031 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002032 final ActivityStack stack = getTopDisplayFocusedStack();
2033 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002034 if (r == null) {
2035 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
2036 return;
2037 }
2038 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07002039 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 }
2041 }
2042
2043 @Override
2044 public int getLaunchedFromUid(IBinder activityToken) {
2045 ActivityRecord srec;
2046 synchronized (mGlobalLock) {
2047 srec = ActivityRecord.forTokenLocked(activityToken);
2048 }
2049 if (srec == null) {
2050 return -1;
2051 }
2052 return srec.launchedFromUid;
2053 }
2054
2055 @Override
2056 public String getLaunchedFromPackage(IBinder activityToken) {
2057 ActivityRecord srec;
2058 synchronized (mGlobalLock) {
2059 srec = ActivityRecord.forTokenLocked(activityToken);
2060 }
2061 if (srec == null) {
2062 return null;
2063 }
2064 return srec.launchedFromPackage;
2065 }
2066
2067 @Override
2068 public boolean convertFromTranslucent(IBinder token) {
2069 final long origId = Binder.clearCallingIdentity();
2070 try {
2071 synchronized (mGlobalLock) {
2072 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2073 if (r == null) {
2074 return false;
2075 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002076 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002077 }
2078 } finally {
2079 Binder.restoreCallingIdentity(origId);
2080 }
2081 }
2082
2083 @Override
2084 public boolean convertToTranslucent(IBinder token, Bundle options) {
2085 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2086 final long origId = Binder.clearCallingIdentity();
2087 try {
2088 synchronized (mGlobalLock) {
2089 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2090 if (r == null) {
2091 return false;
2092 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002093 final ActivityRecord under = r.getTask().getActivityBelow(r);
2094 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002095 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2096 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002097 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002098 }
2099 } finally {
2100 Binder.restoreCallingIdentity(origId);
2101 }
2102 }
2103
2104 @Override
2105 public void notifyActivityDrawn(IBinder token) {
2106 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2107 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002108 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002109 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002110 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002111 }
2112 }
2113 }
2114
2115 @Override
2116 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2117 synchronized (mGlobalLock) {
2118 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2119 if (r == null) {
2120 return;
2121 }
2122 r.reportFullyDrawnLocked(restoredFromBundle);
2123 }
2124 }
2125
2126 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002127 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002128 synchronized (mGlobalLock) {
2129 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002130 if (stack != null) {
2131 final int displayId = stack.getDisplayId();
2132 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002133 }
2134 return DEFAULT_DISPLAY;
2135 }
2136 }
2137
2138 @Override
2139 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002140 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002141 long ident = Binder.clearCallingIdentity();
2142 try {
2143 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002144 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002145 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002146 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002147 }
2148 return null;
2149 }
2150 } finally {
2151 Binder.restoreCallingIdentity(ident);
2152 }
2153 }
2154
2155 @Override
2156 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002157 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002158 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2159 final long callingId = Binder.clearCallingIdentity();
2160 try {
2161 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002162 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002163 if (stack == null) {
2164 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2165 return;
2166 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002167 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002168 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002169 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002170 }
2171 }
2172 } finally {
2173 Binder.restoreCallingIdentity(callingId);
2174 }
2175 }
2176
2177 @Override
2178 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002179 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002180 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2181 final long callingId = Binder.clearCallingIdentity();
2182 try {
2183 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002184 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002185 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002186 if (task == null) {
2187 return;
2188 }
2189 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002190 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002191 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002192 }
2193 }
2194 } finally {
2195 Binder.restoreCallingIdentity(callingId);
2196 }
2197 }
2198
2199 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002200 public void restartActivityProcessIfVisible(IBinder activityToken) {
2201 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2202 final long callingId = Binder.clearCallingIdentity();
2203 try {
2204 synchronized (mGlobalLock) {
2205 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2206 if (r == null) {
2207 return;
2208 }
2209 r.restartProcessIfVisible();
2210 }
2211 } finally {
2212 Binder.restoreCallingIdentity(callingId);
2213 }
2214 }
2215
2216 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002217 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002218 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002219 synchronized (mGlobalLock) {
2220 final long ident = Binder.clearCallingIdentity();
2221 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002222 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002223 "remove-task");
2224 } finally {
2225 Binder.restoreCallingIdentity(ident);
2226 }
2227 }
2228 }
2229
2230 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002231 public void removeAllVisibleRecentTasks() {
2232 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2233 synchronized (mGlobalLock) {
2234 final long ident = Binder.clearCallingIdentity();
2235 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002236 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002237 } finally {
2238 Binder.restoreCallingIdentity(ident);
2239 }
2240 }
2241 }
2242
2243 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002244 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2245 synchronized (mGlobalLock) {
2246 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2247 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002248 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002249 }
2250 }
2251 return false;
2252 }
2253
2254 @Override
2255 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2256 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002257
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002258 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002259 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2260 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002261 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002262 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002263 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002264 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002265 }
2266 }
2267
2268 /**
2269 * Attempts to move a task backwards in z-order (the order of activities within the task is
2270 * unchanged).
2271 *
2272 * There are several possible results of this call:
2273 * - if the task is locked, then we will show the lock toast
2274 * - if there is a task behind the provided task, then that task is made visible and resumed as
2275 * this task is moved to the back
2276 * - otherwise, if there are no other tasks in the stack:
2277 * - if this task is in the pinned stack, then we remove the stack completely, which will
2278 * have the effect of moving the task to the top or bottom of the fullscreen stack
2279 * (depending on whether it is visible)
2280 * - otherwise, we simply return home and hide this task
2281 *
2282 * @param token A reference to the activity we wish to move
2283 * @param nonRoot If false then this only works if the activity is the root
2284 * of a task; if true it will work for any activity in a task.
2285 * @return Returns true if the move completed, false if not.
2286 */
2287 @Override
2288 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002289 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002290 synchronized (mGlobalLock) {
2291 final long origId = Binder.clearCallingIdentity();
2292 try {
2293 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002294 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002295 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002296 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002297 }
2298 } finally {
2299 Binder.restoreCallingIdentity(origId);
2300 }
2301 }
2302 return false;
2303 }
2304
2305 @Override
2306 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002307 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002308 long ident = Binder.clearCallingIdentity();
2309 Rect rect = new Rect();
2310 try {
2311 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002312 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002313 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2314 if (task == null) {
2315 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2316 return rect;
2317 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002318 if (task.getParent() != null) {
2319 rect.set(task.getBounds());
2320 } else if (task.mLastNonFullscreenBounds != null) {
2321 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002322 }
2323 }
2324 } finally {
2325 Binder.restoreCallingIdentity(ident);
2326 }
2327 return rect;
2328 }
2329
2330 @Override
2331 public ActivityManager.TaskDescription getTaskDescription(int id) {
2332 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002333 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002334 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002335 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002336 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2337 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002338 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002339 }
2340 }
2341 return null;
2342 }
2343
2344 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002345 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002346 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08002347 return setTaskWindowingModeSplitScreenPrimary(taskId, toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002348 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002349 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002350 synchronized (mGlobalLock) {
2351 final long ident = Binder.clearCallingIdentity();
2352 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002353 if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2354 return setTaskWindowingModeSplitScreen(taskId, windowingMode, toTop);
2355 }
Louis Chang149d5c82019-12-30 09:47:39 +08002356 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002357 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002358 if (task == null) {
2359 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002360 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002361 }
2362
2363 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2364 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2365
2366 if (!task.isActivityTypeStandardOrUndefined()) {
2367 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2368 + " non-standard task " + taskId + " to windowing mode="
2369 + windowingMode);
2370 }
2371
2372 final ActivityStack stack = task.getStack();
2373 if (toTop) {
2374 stack.moveToFront("setTaskWindowingMode", task);
2375 }
Louis Changa009c762020-02-26 11:21:31 +08002376 // Convert some windowing-mode changes into root-task reparents for split-screen.
2377 if (stack.inSplitScreenWindowingMode()) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07002378 stack.getDisplayArea().onSplitScreenModeDismissed();
Louis Changa009c762020-02-26 11:21:31 +08002379
2380 } else {
2381 stack.setWindowingMode(windowingMode);
2382 stack.getDisplay().ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2383 true /* notifyClients */);
2384 }
Winson Chung7ccc6812020-01-23 16:15:10 -08002385 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002386 } finally {
2387 Binder.restoreCallingIdentity(ident);
2388 }
2389 }
2390 }
2391
2392 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002393 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002394 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002395 ActivityRecord r = getCallingRecordLocked(token);
2396 return r != null ? r.info.packageName : null;
2397 }
2398 }
2399
2400 @Override
2401 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002402 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002403 ActivityRecord r = getCallingRecordLocked(token);
2404 return r != null ? r.intent.getComponent() : null;
2405 }
2406 }
2407
2408 private ActivityRecord getCallingRecordLocked(IBinder token) {
2409 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2410 if (r == null) {
2411 return null;
2412 }
2413 return r.resultTo;
2414 }
2415
2416 @Override
2417 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002418 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002419
2420 synchronized (mGlobalLock) {
2421 final long origId = Binder.clearCallingIdentity();
2422 try {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002423 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
2424 if (topFocusedStack != null) {
2425 topFocusedStack.unhandledBackLocked();
2426 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002427 } finally {
2428 Binder.restoreCallingIdentity(origId);
2429 }
2430 }
2431 }
2432
Mark Renouf446251d2019-04-26 10:22:41 -04002433 @Override
2434 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2435 synchronized (mGlobalLock) {
2436 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2437 if (r == null) {
2438 return;
2439 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002440 ActivityStack stack = r.getRootTask();
Winson Chunga1f869d2020-03-21 23:02:48 -07002441 final TaskOrganizerController taskOrgController =
2442 mWindowOrganizerController.mTaskOrganizerController;
2443 if (taskOrgController.handleInterceptBackPressedOnTaskRoot(stack)) {
2444 // This task is handled by a task organizer that has requested the back pressed
2445 // callback
2446 } else if (stack != null && (stack.isSingleTaskInstance())) {
Mark Renouf446251d2019-04-26 10:22:41 -04002447 // Single-task stacks are used for activities which are presented in floating
2448 // windows above full screen activities. Instead of directly finishing the
2449 // task, a task change listener is used to notify SystemUI so the action can be
2450 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002451 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002452 mTaskChangeNotificationController
2453 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2454 } else {
2455 try {
2456 callback.requestFinish();
2457 } catch (RemoteException e) {
2458 Slog.e(TAG, "Failed to invoke request finish callback", e);
2459 }
2460 }
2461 }
2462 }
2463
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002464 /**
2465 * TODO: Add mController hook
2466 */
2467 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002468 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2469 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002470 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002471
2472 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2473 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002474 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2475 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002476 }
2477 }
2478
Ricky Waiaca8a772019-04-04 16:01:06 +01002479 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2480 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002481 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002482 final int callingPid = Binder.getCallingPid();
2483 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002484 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002485 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002486 SafeActivityOptions.abort(options);
2487 return;
2488 }
2489 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002490 WindowProcessController callerApp = null;
2491 if (appThread != null) {
2492 callerApp = getProcessController(appThread);
2493 }
2494 final ActivityStarter starter = getActivityStartController().obtainStarter(
2495 null /* intent */, "moveTaskToFront");
2496 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
Galia Peychevaed401cc2020-03-19 20:28:09 +01002497 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002498 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002499 return;
2500 }
2501 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002502 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002503 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002504 if (task == null) {
2505 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002506 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002507 return;
2508 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002509 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002510 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002511 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002512 return;
2513 }
2514 ActivityOptions realOptions = options != null
2515 ? options.getOptions(mStackSupervisor)
2516 : null;
2517 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2518 false /* forceNonResizable */);
2519
Wale Ogunwale21e06482019-11-18 05:14:15 -08002520 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002521 if (topActivity != null) {
2522
2523 // We are reshowing a task, use a starting window to hide the initial draw delay
2524 // so the transition can start earlier.
2525 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2526 true /* taskSwitch */, fromRecents);
2527 }
2528 } finally {
2529 Binder.restoreCallingIdentity(origId);
2530 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002531 }
2532
Ricky Waiaca8a772019-04-04 16:01:06 +01002533 /**
2534 * Return true if callingUid is system, or packageName belongs to that callingUid.
2535 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002536 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002537 try {
2538 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2539 if (packageName == null) {
2540 return false;
2541 }
2542 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2543 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2544 UserHandle.getUserId(callingUid));
2545 return UserHandle.isSameApp(callingUid, uid);
2546 }
2547 } catch (RemoteException e) {
2548 // Should not happen
2549 }
2550 return true;
2551 }
2552
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002553 /**
2554 * Checks that the provided package name matches the current calling UID, throws a security
2555 * exception if it doesn't.
2556 */
2557 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2558 final int callingUid = Binder.getCallingUid();
2559 if (isSameApp(callingUid, packageName)) {
2560 return;
2561 }
2562 final String msg = "Permission Denial: package=" + packageName
2563 + " does not belong to uid=" + callingUid;
2564 Slog.w(TAG, msg);
2565 throw new SecurityException(msg);
2566 }
2567
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002568 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2569 int callingPid, int callingUid, String name) {
2570 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2571 return true;
2572 }
2573
2574 if (getRecentTasks().isCallerRecents(sourceUid)) {
2575 return true;
2576 }
2577
2578 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2579 if (perm == PackageManager.PERMISSION_GRANTED) {
2580 return true;
2581 }
2582 if (checkAllowAppSwitchUid(sourceUid)) {
2583 return true;
2584 }
2585
2586 // If the actual IPC caller is different from the logical source, then
2587 // also see if they are allowed to control app switches.
2588 if (callingUid != -1 && callingUid != sourceUid) {
2589 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2590 if (perm == PackageManager.PERMISSION_GRANTED) {
2591 return true;
2592 }
2593 if (checkAllowAppSwitchUid(callingUid)) {
2594 return true;
2595 }
2596 }
2597
2598 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2599 return false;
2600 }
2601
2602 private boolean checkAllowAppSwitchUid(int uid) {
2603 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2604 if (types != null) {
2605 for (int i = types.size() - 1; i >= 0; i--) {
2606 if (types.valueAt(i).intValue() == uid) {
2607 return true;
2608 }
2609 }
2610 }
2611 return false;
2612 }
2613
2614 @Override
2615 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2616 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2617 "setActivityController()");
2618 synchronized (mGlobalLock) {
2619 mController = controller;
2620 mControllerIsAMonkey = imAMonkey;
2621 Watchdog.getInstance().setActivityController(controller);
2622 }
2623 }
2624
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002625 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002626 synchronized (mGlobalLock) {
2627 return mController != null && mControllerIsAMonkey;
2628 }
2629 }
2630
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002631 @Override
2632 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2633 synchronized (mGlobalLock) {
2634 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2635 }
2636 }
2637
2638 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002639 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
Winson Chunge5ab0172020-03-21 23:00:24 -07002640 return getFilteredTasks(maxNum, false /* filterForVisibleRecents */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002641 }
2642
Winson Chunge5ab0172020-03-21 23:00:24 -07002643 /**
2644 * @param filterOnlyVisibleRecents whether to filter the tasks based on whether they would ever
2645 * be visible in the recent task list in systemui
2646 */
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002647 @Override
2648 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
Winson Chunge5ab0172020-03-21 23:00:24 -07002649 boolean filterOnlyVisibleRecents) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002650 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002651 final int callingPid = Binder.getCallingPid();
2652 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002653 final int[] profileIds = getUserManager().getProfileIds(
2654 UserHandle.getUserId(callingUid), true);
2655 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2656 for (int i = 0; i < profileIds.length; i++) {
2657 callingProfileIds.add(profileIds[i]);
2658 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002659 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2660
2661 synchronized (mGlobalLock) {
2662 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2663
Nicholas Sauer0259e532019-08-30 08:24:55 -07002664 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Winson Chunge5ab0172020-03-21 23:00:24 -07002665 mRootWindowContainer.getRunningTasks(maxNum, list, filterOnlyVisibleRecents, callingUid,
2666 allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002667 }
2668
2669 return list;
2670 }
2671
2672 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002673 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2674 synchronized (mGlobalLock) {
2675 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002676 try {
2677 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2678 if (r == null) return;
2679
2680 final PooledConsumer c = PooledLambda.obtainConsumer(
2681 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2682 r, resultWho, requestCode);
2683 // TODO: This should probably only loop over the task since you need to be in the
2684 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002685 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002686 c.recycle();
2687
2688 updateOomAdj();
2689 } finally {
2690 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002691 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002692 }
2693 }
2694
2695 @Override
2696 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002697 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002698 ActivityStack stack = ActivityRecord.getStackLocked(token);
2699 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002700 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002701 }
2702 return false;
2703 }
2704 }
2705
2706 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002707 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002708 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002709 synchronized (mGlobalLock) {
2710 final long ident = Binder.clearCallingIdentity();
2711 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002712 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002713 if (task == null) {
2714 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2715 return;
2716 }
2717
2718 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2719 + " to stackId=" + stackId + " toTop=" + toTop);
2720
Louis Chang149d5c82019-12-30 09:47:39 +08002721 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002722 if (stack == null) {
2723 throw new IllegalStateException(
2724 "moveTaskToStack: No stack for stackId=" + stackId);
2725 }
2726 if (!stack.isActivityTypeStandardOrUndefined()) {
2727 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2728 + taskId + " to stack " + stackId);
2729 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002730 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2731 "moveTaskToStack");
2732 } finally {
2733 Binder.restoreCallingIdentity(ident);
2734 }
2735 }
2736 }
2737
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002738 /**
2739 * Moves the specified task to the primary-split-screen stack.
2740 *
2741 * @param taskId Id of task to move.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002742 * @param toTop If the task and stack should be moved to the top.
Winson Chung7ccc6812020-01-23 16:15:10 -08002743 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002744 */
2745 @Override
Evan Rosky73a7fe92019-11-18 18:28:01 -08002746 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002747 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002748 "setTaskWindowingModeSplitScreenPrimary()");
2749 synchronized (mGlobalLock) {
2750 final long ident = Binder.clearCallingIdentity();
2751 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002752 return setTaskWindowingModeSplitScreen(taskId, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY,
2753 toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002754 } finally {
2755 Binder.restoreCallingIdentity(ident);
2756 }
2757 }
2758 }
2759
2760 /**
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002761 * Moves the specified task into a split-screen tile.
2762 */
2763 private boolean setTaskWindowingModeSplitScreen(int taskId, int windowingMode, boolean toTop) {
2764 if (!WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2765 throw new IllegalArgumentException("Calling setTaskWindowingModeSplitScreen with non"
2766 + "split-screen mode: " + windowingMode);
2767 }
2768 if (isInLockTaskMode()) {
2769 Slog.w(TAG, "setTaskWindowingModeSplitScreen: Is in lock task mode="
2770 + getLockTaskModeState());
2771 return false;
2772 }
2773
2774 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2775 MATCH_TASK_IN_STACKS_ONLY);
2776 if (task == null) {
2777 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2778 return false;
2779 }
2780 if (!task.isActivityTypeStandardOrUndefined()) {
2781 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2782 + " non-standard task " + taskId + " to split-screen windowing mode");
2783 }
Wale Ogunwale0d465192020-01-23 19:14:44 -08002784 if (!task.supportsSplitScreenWindowingMode()) {
2785 return false;
2786 }
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002787
2788 final int prevMode = task.getWindowingMode();
Louis Changa009c762020-02-26 11:21:31 +08002789 moveTaskToSplitScreenPrimaryTask(task, toTop);
Wale Ogunwale0d465192020-01-23 19:14:44 -08002790 return prevMode != task.getWindowingMode();
2791 }
2792
Louis Changa009c762020-02-26 11:21:31 +08002793 void moveTaskToSplitScreenPrimaryTask(Task task, boolean toTop) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07002794 final TaskDisplayArea taskDisplayArea = task.getDisplayArea();
2795 final ActivityStack primarySplitTask = taskDisplayArea.getRootSplitScreenPrimaryTask();
Louis Changa009c762020-02-26 11:21:31 +08002796 if (primarySplitTask == null) {
2797 throw new IllegalStateException("Can't enter split without associated organized task");
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002798 }
Louis Changa009c762020-02-26 11:21:31 +08002799
2800 if (toTop) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07002801 taskDisplayArea.positionStackAt(POSITION_TOP, primarySplitTask,
Andrii Kulian9ea12da2020-03-27 17:16:38 -07002802 false /* includingParents */);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002803 }
2804 WindowContainerTransaction wct = new WindowContainerTransaction();
Wale Ogunwale465b1e12020-03-31 12:15:51 -07002805 // Clear out current windowing mode before reparenting to split taks.
2806 wct.setWindowingMode(
2807 task.getStack().mRemoteToken.toWindowContainerToken(), WINDOWING_MODE_UNDEFINED);
Wale Ogunwaleadf116e2020-03-27 16:36:01 -07002808 wct.reparent(task.getStack().mRemoteToken.toWindowContainerToken(),
2809 primarySplitTask.mRemoteToken.toWindowContainerToken(), toTop);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07002810 mWindowOrganizerController.applyTransaction(wct);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002811 }
2812
2813 /**
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002814 * Removes stacks in the input windowing modes from the system if they are of activity type
2815 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2816 */
2817 @Override
2818 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002819 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002820 "removeStacksInWindowingModes()");
2821
2822 synchronized (mGlobalLock) {
2823 final long ident = Binder.clearCallingIdentity();
2824 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002825 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002826 } finally {
2827 Binder.restoreCallingIdentity(ident);
2828 }
2829 }
2830 }
2831
2832 @Override
2833 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002834 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002835 "removeStacksWithActivityTypes()");
2836
2837 synchronized (mGlobalLock) {
2838 final long ident = Binder.clearCallingIdentity();
2839 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002840 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002841 } finally {
2842 Binder.restoreCallingIdentity(ident);
2843 }
2844 }
2845 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002846
2847 @Override
2848 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2849 int userId) {
2850 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002851 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2852 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002853 callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002854 synchronized (mGlobalLock) {
Winson Chung66b08f02020-03-03 14:32:35 -08002855 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, userId, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002856 }
2857 }
2858
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002859 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002860 @Override
2861 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002862 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002863 long ident = Binder.clearCallingIdentity();
2864 try {
2865 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002866 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002867 }
2868 } finally {
2869 Binder.restoreCallingIdentity(ident);
2870 }
2871 }
2872
2873 @Override
2874 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002875 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002876 long ident = Binder.clearCallingIdentity();
2877 try {
2878 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002879 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880 }
2881 } finally {
2882 Binder.restoreCallingIdentity(ident);
2883 }
2884 }
2885
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002886 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002887 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002888 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2889 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2890 long ident = Binder.clearCallingIdentity();
2891 try {
2892 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002893 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002894 }
2895 } finally {
2896 Binder.restoreCallingIdentity(ident);
2897 }
2898 }
2899
2900 @Override
2901 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2902 int displayId) {
2903 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2904 long ident = Binder.clearCallingIdentity();
2905 try {
2906 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002907 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002908 }
2909 } finally {
2910 Binder.restoreCallingIdentity(ident);
2911 }
2912 }
2913
2914 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002915 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002916 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002917 final long callingUid = Binder.getCallingUid();
2918 final long origId = Binder.clearCallingIdentity();
2919 try {
2920 synchronized (mGlobalLock) {
2921 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002922 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002923 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2924 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2925 }
2926 } finally {
2927 Binder.restoreCallingIdentity(origId);
2928 }
2929 }
2930
2931 @Override
2932 public void startLockTaskModeByToken(IBinder token) {
2933 synchronized (mGlobalLock) {
2934 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2935 if (r == null) {
2936 return;
2937 }
Louis Changcdec0802019-11-11 11:45:07 +08002938 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002939 }
2940 }
2941
2942 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002943 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002944 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002945 // This makes inner call to look as if it was initiated by system.
2946 long ident = Binder.clearCallingIdentity();
2947 try {
2948 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002949 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002950 MATCH_TASK_IN_STACKS_ONLY);
2951 if (task == null) {
2952 return;
2953 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002954
2955 // When starting lock task mode the stack must be in front and focused
2956 task.getStack().moveToFront("startSystemLockTaskMode");
2957 startLockTaskModeLocked(task, true /* isSystemCaller */);
2958 }
2959 } finally {
2960 Binder.restoreCallingIdentity(ident);
2961 }
2962 }
2963
2964 @Override
2965 public void stopLockTaskModeByToken(IBinder token) {
2966 synchronized (mGlobalLock) {
2967 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2968 if (r == null) {
2969 return;
2970 }
Louis Changcdec0802019-11-11 11:45:07 +08002971 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002972 }
2973 }
2974
2975 /**
2976 * This API should be called by SystemUI only when user perform certain action to dismiss
2977 * lock task mode. We should only dismiss pinned lock task mode in this case.
2978 */
2979 @Override
2980 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002981 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2983 }
2984
Louis Changcdec0802019-11-11 11:45:07 +08002985 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002986 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2987 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2988 return;
2989 }
2990
Louis Chang149d5c82019-12-30 09:47:39 +08002991 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002992 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002993 throw new IllegalArgumentException("Invalid task, not in foreground");
2994 }
2995
2996 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2997 // system or a specific app.
2998 // * System-initiated requests will only start the pinned mode (screen pinning)
2999 // * App-initiated requests
3000 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
3001 // - will start the pinned mode, otherwise
3002 final int callingUid = Binder.getCallingUid();
3003 long ident = Binder.clearCallingIdentity();
3004 try {
3005 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08003006 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003007
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003008 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003009 } finally {
3010 Binder.restoreCallingIdentity(ident);
3011 }
3012 }
3013
Louis Changcdec0802019-11-11 11:45:07 +08003014 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003015 final int callingUid = Binder.getCallingUid();
3016 long ident = Binder.clearCallingIdentity();
3017 try {
3018 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003019 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003020 }
3021 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
3022 // task and jumping straight into a call in the case of emergency call back.
3023 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
3024 if (tm != null) {
3025 tm.showInCallScreen(false);
3026 }
3027 } finally {
3028 Binder.restoreCallingIdentity(ident);
3029 }
3030 }
3031
3032 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003033 public void updateLockTaskPackages(int userId, String[] packages) {
3034 final int callingUid = Binder.getCallingUid();
3035 if (callingUid != 0 && callingUid != SYSTEM_UID) {
3036 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
3037 "updateLockTaskPackages()");
3038 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08003039 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003040 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
3041 + Arrays.toString(packages));
3042 getLockTaskController().updateLockTaskPackages(userId, packages);
3043 }
3044 }
3045
3046 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003047 public boolean isInLockTaskMode() {
3048 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3049 }
3050
3051 @Override
3052 public int getLockTaskModeState() {
3053 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003054 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003055 }
3056 }
3057
3058 @Override
3059 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3060 synchronized (mGlobalLock) {
3061 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3062 if (r != null) {
3063 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003064 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003065 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003066 }
3067 }
3068 }
3069
3070 @Override
3071 public Bundle getActivityOptions(IBinder token) {
3072 final long origId = Binder.clearCallingIdentity();
3073 try {
3074 synchronized (mGlobalLock) {
3075 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3076 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003077 final ActivityOptions activityOptions = r.takeOptionsLocked(
3078 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003079 return activityOptions == null ? null : activityOptions.toBundle();
3080 }
3081 return null;
3082 }
3083 } finally {
3084 Binder.restoreCallingIdentity(origId);
3085 }
3086 }
3087
3088 @Override
3089 public List<IBinder> getAppTasks(String callingPackage) {
3090 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003091 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003092 long ident = Binder.clearCallingIdentity();
3093 try {
3094 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003095 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003096 }
3097 } finally {
3098 Binder.restoreCallingIdentity(ident);
3099 }
3100 }
3101
3102 @Override
3103 public void finishVoiceTask(IVoiceInteractionSession session) {
3104 synchronized (mGlobalLock) {
3105 final long origId = Binder.clearCallingIdentity();
3106 try {
3107 // TODO: VI Consider treating local voice interactions and voice tasks
3108 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003109 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003110 } finally {
3111 Binder.restoreCallingIdentity(origId);
3112 }
3113 }
3114
3115 }
3116
3117 @Override
3118 public boolean isTopOfTask(IBinder token) {
3119 synchronized (mGlobalLock) {
3120 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003121 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003122 }
3123 }
3124
3125 @Override
3126 public void notifyLaunchTaskBehindComplete(IBinder token) {
3127 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3128 }
3129
3130 @Override
3131 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003132 mH.post(() -> {
3133 synchronized (mGlobalLock) {
3134 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003135 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003136 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003137 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003138 } catch (RemoteException e) {
3139 }
3140 }
3141 }
3142
3143 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003144 }
3145
3146 /** Called from an app when assist data is ready. */
3147 @Override
3148 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3149 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003150 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003151 synchronized (pae) {
3152 pae.result = extras;
3153 pae.structure = structure;
3154 pae.content = content;
3155 if (referrer != null) {
3156 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3157 }
3158 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003159 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003160 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003161 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003162 structure.setHomeActivity(pae.isHome);
3163 }
3164 pae.haveResult = true;
3165 pae.notifyAll();
3166 if (pae.intent == null && pae.receiver == null) {
3167 // Caller is just waiting for the result.
3168 return;
3169 }
3170 }
3171 // We are now ready to launch the assist activity.
3172 IAssistDataReceiver sendReceiver = null;
3173 Bundle sendBundle = null;
3174 synchronized (mGlobalLock) {
3175 buildAssistBundleLocked(pae, extras);
3176 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003177 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003178 if (!exists) {
3179 // Timed out.
3180 return;
3181 }
3182
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003183 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003184 // Caller wants result sent back to them.
3185 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003186 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003187 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003188 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3189 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003190 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3191 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3192 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3193 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3194 }
3195 }
3196 if (sendReceiver != null) {
3197 try {
3198 sendReceiver.onHandleAssistData(sendBundle);
3199 } catch (RemoteException e) {
3200 }
3201 return;
3202 }
3203
3204 final long ident = Binder.clearCallingIdentity();
3205 try {
3206 if (TextUtils.equals(pae.intent.getAction(),
3207 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003208 // Start voice interaction through VoiceInteractionManagerService.
3209 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3210 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003211 } else {
3212 pae.intent.replaceExtras(pae.extras);
3213 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3214 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3215 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003216 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003217
3218 try {
3219 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3220 } catch (ActivityNotFoundException e) {
3221 Slog.w(TAG, "No activity to handle assist action.", e);
3222 }
3223 }
3224 } finally {
3225 Binder.restoreCallingIdentity(ident);
3226 }
3227 }
3228
3229 @Override
3230 public int addAppTask(IBinder activityToken, Intent intent,
3231 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3232 final int callingUid = Binder.getCallingUid();
3233 final long callingIdent = Binder.clearCallingIdentity();
3234
3235 try {
3236 synchronized (mGlobalLock) {
3237 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3238 if (r == null) {
3239 throw new IllegalArgumentException("Activity does not exist; token="
3240 + activityToken);
3241 }
3242 ComponentName comp = intent.getComponent();
3243 if (comp == null) {
3244 throw new IllegalArgumentException("Intent " + intent
3245 + " must specify explicit component");
3246 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003247 if (thumbnail.getWidth() != mThumbnailWidth
3248 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003249 throw new IllegalArgumentException("Bad thumbnail size: got "
3250 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003251 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003252 }
3253 if (intent.getSelector() != null) {
3254 intent.setSelector(null);
3255 }
3256 if (intent.getSourceBounds() != null) {
3257 intent.setSourceBounds(null);
3258 }
3259 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3260 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3261 // The caller has added this as an auto-remove task... that makes no
3262 // sense, so turn off auto-remove.
3263 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3264 }
3265 }
3266 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3267 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3268 if (ainfo.applicationInfo.uid != callingUid) {
3269 throw new SecurityException(
3270 "Can't add task for another application: target uid="
3271 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3272 }
3273
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003274 final ActivityStack stack = r.getRootTask();
Andrii Kulian86d676c2020-03-27 19:34:54 -07003275 final Task task = stack.getDisplayArea().createStack(stack.getWindowingMode(),
3276 stack.getActivityType(), !ON_TOP, ainfo, intent,
Louis Changa009c762020-02-26 11:21:31 +08003277 false /* createdByOrganizer */);
Wale Ogunwale0d465192020-01-23 19:14:44 -08003278
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003279 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003280 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003281 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003282 return INVALID_TASK_ID;
3283 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003284 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003285
3286 // TODO: Send the thumbnail to WM to store it.
3287
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003288 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003289 }
3290 } finally {
3291 Binder.restoreCallingIdentity(callingIdent);
3292 }
3293 }
3294
3295 @Override
3296 public Point getAppTaskThumbnailSize() {
3297 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003298 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003299 }
3300 }
3301
3302 @Override
3303 public void setTaskResizeable(int taskId, int resizeableMode) {
3304 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003305 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003306 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3307 if (task == null) {
3308 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3309 return;
3310 }
3311 task.setResizeMode(resizeableMode);
3312 }
3313 }
3314
3315 @Override
3316 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003317 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003318 long ident = Binder.clearCallingIdentity();
3319 try {
3320 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003321 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003322 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003323 if (task == null) {
3324 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3325 return;
3326 }
3327 // Place the task in the right stack if it isn't there already based on
3328 // the requested bounds.
3329 // The stack transition logic is:
3330 // - a null bounds on a freeform task moves that task to fullscreen
3331 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3332 // that task to freeform
3333 // - otherwise the task is not moved
3334 ActivityStack stack = task.getStack();
3335 if (!task.getWindowConfiguration().canResizeTask()) {
3336 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3337 }
3338 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07003339 stack = stack.getDisplayArea().getOrCreateStack(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003340 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3341 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07003342 stack = stack.getDisplayArea().getOrCreateStack(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003343 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3344 }
3345
3346 // Reparent the task to the right stack if necessary
3347 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3348 if (stack != task.getStack()) {
3349 // Defer resume until the task is resized below
3350 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3351 DEFER_RESUME, "resizeTask");
3352 preserveWindow = false;
3353 }
3354
3355 // After reparenting (which only resizes the task to the stack bounds), resize the
3356 // task to the actual bounds provided
3357 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3358 }
3359 } finally {
3360 Binder.restoreCallingIdentity(ident);
3361 }
3362 }
3363
3364 @Override
3365 public boolean releaseActivityInstance(IBinder token) {
3366 synchronized (mGlobalLock) {
3367 final long origId = Binder.clearCallingIdentity();
3368 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003369 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3370 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003371 return false;
3372 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003373 r.destroyImmediately(true /* removeFromApp */, "app-req");
3374 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003375 } finally {
3376 Binder.restoreCallingIdentity(origId);
3377 }
3378 }
3379 }
3380
3381 @Override
3382 public void releaseSomeActivities(IApplicationThread appInt) {
3383 synchronized (mGlobalLock) {
3384 final long origId = Binder.clearCallingIdentity();
3385 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003386 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003387 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003388 } finally {
3389 Binder.restoreCallingIdentity(origId);
3390 }
3391 }
3392 }
3393
3394 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003395 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003396 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003397 != PackageManager.PERMISSION_GRANTED) {
3398 throw new SecurityException("Requires permission "
3399 + android.Manifest.permission.DEVICE_POWER);
3400 }
3401
3402 synchronized (mGlobalLock) {
3403 long ident = Binder.clearCallingIdentity();
3404 if (mKeyguardShown != keyguardShowing) {
3405 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003406 final Message msg = PooledLambda.obtainMessage(
3407 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3408 keyguardShowing);
3409 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003410 }
3411 try {
wilsonshih177261f2019-02-22 12:02:18 +08003412 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003413 } finally {
3414 Binder.restoreCallingIdentity(ident);
3415 }
3416 }
3417
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003418 mH.post(() -> {
3419 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3420 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3421 }
3422 });
3423 }
3424
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003425 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003426 mH.post(() -> {
3427 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3428 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3429 }
3430 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003431 }
3432
3433 @Override
3434 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003435 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3436 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003437
3438 final File passedIconFile = new File(filePath);
3439 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3440 passedIconFile.getName());
3441 if (!legitIconFile.getPath().equals(filePath)
3442 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3443 throw new IllegalArgumentException("Bad file path: " + filePath
3444 + " passed for userId " + userId);
3445 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003446 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003447 }
3448
3449 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003450 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003451 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003452 synchronized (mGlobalLock) {
3453 final long ident = Binder.clearCallingIdentity();
3454 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003455 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003456 if (stack == null) {
3457 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3458 return;
3459 }
3460 if (!stack.isActivityTypeStandardOrUndefined()) {
3461 throw new IllegalArgumentException(
3462 "Removing non-standard stack is not allowed.");
3463 }
3464 mStackSupervisor.removeStack(stack);
3465 } finally {
3466 Binder.restoreCallingIdentity(ident);
3467 }
3468 }
3469 }
3470
3471 @Override
3472 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003473 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003474
3475 synchronized (mGlobalLock) {
3476 final long ident = Binder.clearCallingIdentity();
3477 try {
3478 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3479 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003480 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003481 } finally {
3482 Binder.restoreCallingIdentity(ident);
3483 }
3484 }
3485 }
3486
3487 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003488 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003489 synchronized (mGlobalLock) {
3490 long ident = Binder.clearCallingIdentity();
3491 try {
3492 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3493 if (r == null) {
3494 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003495 "toggleFreeformWindowingMode: No activity record matching token="
3496 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003497 }
3498
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003499 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003500 if (stack == null) {
3501 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3502 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003503 }
3504
Yunfan Chend967af82019-01-17 18:30:18 +09003505 if (!stack.inFreeformWindowingMode()
3506 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3507 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3508 + "toggle between fullscreen and freeform.");
3509 }
3510
3511 if (stack.inFreeformWindowingMode()) {
3512 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003513 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003514 throw new IllegalStateException("Size-compat windows are currently not"
3515 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003516 } else if (stack.getParent().inFreeformWindowingMode()) {
3517 // If the window is on a freeform display, set it to undefined. It will be
3518 // resolved to freeform and it can adjust windowing mode when the display mode
3519 // changes in runtime.
3520 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003521 } else {
3522 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3523 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003524 } finally {
3525 Binder.restoreCallingIdentity(ident);
3526 }
3527 }
3528 }
3529
3530 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3531 @Override
3532 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003533 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003534 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003535 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003536 }
3537
3538 /** Unregister a task stack listener so that it stops receiving callbacks. */
3539 @Override
3540 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003541 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003542 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003543 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003544 }
3545
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003546 @Override
3547 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3548 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3549 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3550 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3551 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3552 }
3553
3554 @Override
3555 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3556 IBinder activityToken, int flags) {
3557 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3558 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3559 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3560 }
3561
3562 @Override
3563 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3564 Bundle args) {
3565 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3566 true /* focused */, true /* newSessionId */, userHandle, args,
3567 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3568 }
3569
3570 @Override
3571 public Bundle getAssistContextExtras(int requestType) {
3572 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3573 null, null, true /* focused */, true /* newSessionId */,
3574 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3575 if (pae == null) {
3576 return null;
3577 }
3578 synchronized (pae) {
3579 while (!pae.haveResult) {
3580 try {
3581 pae.wait();
3582 } catch (InterruptedException e) {
3583 }
3584 }
3585 }
3586 synchronized (mGlobalLock) {
3587 buildAssistBundleLocked(pae, pae.result);
3588 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003589 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003590 }
3591 return pae.extras;
3592 }
3593
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003594 /**
3595 * Binder IPC calls go through the public entry point.
3596 * This can be called with or without the global lock held.
3597 */
3598 private static int checkCallingPermission(String permission) {
3599 return checkPermission(
3600 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3601 }
3602
3603 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003604 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003605 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3606 mAmInternal.enforceCallingPermission(permission, func);
3607 }
3608 }
3609
3610 @VisibleForTesting
3611 int checkGetTasksPermission(String permission, int pid, int uid) {
3612 return checkPermission(permission, pid, uid);
3613 }
3614
3615 static int checkPermission(String permission, int pid, int uid) {
3616 if (permission == null) {
3617 return PackageManager.PERMISSION_DENIED;
3618 }
3619 return checkComponentPermission(permission, pid, uid, -1, true);
3620 }
3621
Wale Ogunwale214f3482018-10-04 11:00:47 -07003622 public static int checkComponentPermission(String permission, int pid, int uid,
3623 int owningUid, boolean exported) {
3624 return ActivityManagerService.checkComponentPermission(
3625 permission, pid, uid, owningUid, exported);
3626 }
3627
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003628 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3629 if (getRecentTasks().isCallerRecents(callingUid)) {
3630 // Always allow the recents component to get tasks
3631 return true;
3632 }
3633
3634 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3635 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3636 if (!allowed) {
3637 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3638 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3639 // Temporary compatibility: some existing apps on the system image may
3640 // still be requesting the old permission and not switched to the new
3641 // one; if so, we'll still allow them full access. This means we need
3642 // to see if they are holding the old permission and are a system app.
3643 try {
3644 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3645 allowed = true;
3646 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3647 + " is using old GET_TASKS but privileged; allowing");
3648 }
3649 } catch (RemoteException e) {
3650 }
3651 }
3652 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3653 + " does not hold REAL_GET_TASKS; limiting output");
3654 }
3655 return allowed;
3656 }
3657
Nicholas Sauer0259e532019-08-30 08:24:55 -07003658 boolean isCrossUserAllowed(int pid, int uid) {
3659 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3660 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3661 }
3662
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003663 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3664 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3665 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3666 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003667 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003668 "enqueueAssistContext()");
3669
3670 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08003671 final ActivityStack stack = getTopDisplayFocusedStack();
3672 ActivityRecord activity = stack != null ? stack.getTopNonFinishingActivity() : null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003673 if (activity == null) {
3674 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3675 return null;
3676 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003677 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003678 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3679 return null;
3680 }
3681 if (focused) {
3682 if (activityToken != null) {
3683 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3684 if (activity != caller) {
3685 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3686 + " is not current top " + activity);
3687 return null;
3688 }
3689 }
3690 } else {
3691 activity = ActivityRecord.forTokenLocked(activityToken);
3692 if (activity == null) {
3693 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3694 + " couldn't be found");
3695 return null;
3696 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003697 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003698 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3699 return null;
3700 }
3701 }
3702
3703 PendingAssistExtras pae;
3704 Bundle extras = new Bundle();
3705 if (args != null) {
3706 extras.putAll(args);
3707 }
3708 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003709 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003710
3711 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3712 userHandle);
3713 pae.isHome = activity.isActivityTypeHome();
3714
3715 // Increment the sessionId if necessary
3716 if (newSessionId) {
3717 mViSessionId++;
3718 }
3719 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003720 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3721 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003722 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003723 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003724 } catch (RemoteException e) {
3725 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3726 return null;
3727 }
3728 return pae;
3729 }
3730 }
3731
3732 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3733 if (result != null) {
3734 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3735 }
3736 if (pae.hint != null) {
3737 pae.extras.putBoolean(pae.hint, true);
3738 }
3739 }
3740
3741 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3742 IAssistDataReceiver receiver;
3743 synchronized (mGlobalLock) {
3744 mPendingAssistExtras.remove(pae);
3745 receiver = pae.receiver;
3746 }
3747 if (receiver != null) {
3748 // Caller wants result sent back to them.
3749 Bundle sendBundle = new Bundle();
3750 // At least return the receiver extras
3751 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3752 try {
3753 pae.receiver.onHandleAssistData(sendBundle);
3754 } catch (RemoteException e) {
3755 }
3756 }
3757 }
3758
3759 public class PendingAssistExtras extends Binder implements Runnable {
3760 public final ActivityRecord activity;
3761 public boolean isHome;
3762 public final Bundle extras;
3763 public final Intent intent;
3764 public final String hint;
3765 public final IAssistDataReceiver receiver;
3766 public final int userHandle;
3767 public boolean haveResult = false;
3768 public Bundle result = null;
3769 public AssistStructure structure = null;
3770 public AssistContent content = null;
3771 public Bundle receiverExtras;
3772
3773 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3774 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3775 int _userHandle) {
3776 activity = _activity;
3777 extras = _extras;
3778 intent = _intent;
3779 hint = _hint;
3780 receiver = _receiver;
3781 receiverExtras = _receiverExtras;
3782 userHandle = _userHandle;
3783 }
3784
3785 @Override
3786 public void run() {
3787 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3788 synchronized (this) {
3789 haveResult = true;
3790 notifyAll();
3791 }
3792 pendingAssistExtrasTimedOut(this);
3793 }
3794 }
3795
3796 @Override
3797 public boolean isAssistDataAllowedOnCurrentActivity() {
3798 int userId;
3799 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003800 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003801 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3802 return false;
3803 }
3804
Wale Ogunwale21e06482019-11-18 05:14:15 -08003805 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003806 if (activity == null) {
3807 return false;
3808 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003809 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003810 }
3811 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3812 }
3813
3814 @Override
3815 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3816 long ident = Binder.clearCallingIdentity();
3817 try {
3818 synchronized (mGlobalLock) {
3819 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003820 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003821 if (top != caller) {
3822 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3823 + " is not current top " + top);
3824 return false;
3825 }
3826 if (!top.nowVisible) {
3827 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3828 + " is not visible");
3829 return false;
3830 }
3831 }
3832 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3833 token);
3834 } finally {
3835 Binder.restoreCallingIdentity(ident);
3836 }
3837 }
3838
3839 @Override
3840 public boolean isRootVoiceInteraction(IBinder token) {
3841 synchronized (mGlobalLock) {
3842 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3843 if (r == null) {
3844 return false;
3845 }
3846 return r.rootVoiceInteraction;
3847 }
3848 }
3849
Wale Ogunwalef6733932018-06-27 05:14:34 -07003850 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3851 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3852 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3853 if (activityToCallback == null) return;
3854 activityToCallback.setVoiceSessionLocked(voiceSession);
3855
3856 // Inform the activity
3857 try {
3858 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3859 voiceInteractor);
3860 long token = Binder.clearCallingIdentity();
3861 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003862 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003863 } finally {
3864 Binder.restoreCallingIdentity(token);
3865 }
3866 // TODO: VI Should we cache the activity so that it's easier to find later
3867 // rather than scan through all the stacks and activities?
3868 } catch (RemoteException re) {
3869 activityToCallback.clearVoiceSessionLocked();
3870 // TODO: VI Should this terminate the voice session?
3871 }
3872 }
3873
3874 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3875 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3876 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3877 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3878 boolean wasRunningVoice = mRunningVoice != null;
3879 mRunningVoice = session;
3880 if (!wasRunningVoice) {
3881 mVoiceWakeLock.acquire();
3882 updateSleepIfNeededLocked();
3883 }
3884 }
3885 }
3886
3887 void finishRunningVoiceLocked() {
3888 if (mRunningVoice != null) {
3889 mRunningVoice = null;
3890 mVoiceWakeLock.release();
3891 updateSleepIfNeededLocked();
3892 }
3893 }
3894
3895 @Override
3896 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3897 synchronized (mGlobalLock) {
3898 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3899 if (keepAwake) {
3900 mVoiceWakeLock.acquire();
3901 } else {
3902 mVoiceWakeLock.release();
3903 }
3904 }
3905 }
3906 }
3907
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003908 @Override
3909 public ComponentName getActivityClassForToken(IBinder token) {
3910 synchronized (mGlobalLock) {
3911 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3912 if (r == null) {
3913 return null;
3914 }
3915 return r.intent.getComponent();
3916 }
3917 }
3918
3919 @Override
3920 public String getPackageForToken(IBinder token) {
3921 synchronized (mGlobalLock) {
3922 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3923 if (r == null) {
3924 return null;
3925 }
3926 return r.packageName;
3927 }
3928 }
3929
3930 @Override
3931 public void showLockTaskEscapeMessage(IBinder token) {
3932 synchronized (mGlobalLock) {
3933 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3934 if (r == null) {
3935 return;
3936 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003937 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003938 }
3939 }
3940
3941 @Override
3942 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003943 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003944 final long token = Binder.clearCallingIdentity();
3945 try {
3946 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003947 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003948 }
3949 } finally {
3950 Binder.restoreCallingIdentity(token);
3951 }
3952 }
3953
3954 /**
3955 * Try to place task to provided position. The final position might be different depending on
3956 * current user and stacks state. The task will be moved to target stack if it's currently in
3957 * different stack.
3958 */
3959 @Override
3960 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003961 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003962 synchronized (mGlobalLock) {
3963 long ident = Binder.clearCallingIdentity();
3964 try {
3965 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3966 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003967 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003968 if (task == null) {
3969 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3970 + taskId);
3971 }
3972
Louis Chang149d5c82019-12-30 09:47:39 +08003973 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003974
3975 if (stack == null) {
3976 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3977 + stackId);
3978 }
3979 if (!stack.isActivityTypeStandardOrUndefined()) {
3980 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3981 + " the position of task " + taskId + " in/to non-standard stack");
3982 }
3983
3984 // TODO: Have the callers of this API call a separate reparent method if that is
3985 // what they intended to do vs. having this method also do reparenting.
3986 if (task.getStack() == stack) {
3987 // Change position in current stack.
3988 stack.positionChildAt(task, position);
3989 } else {
3990 // Reparent to new stack.
3991 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3992 !DEFER_RESUME, "positionTaskInStack");
3993 }
3994 } finally {
3995 Binder.restoreCallingIdentity(ident);
3996 }
3997 }
3998 }
3999
4000 @Override
4001 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
4002 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
4003 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09004004 + Arrays.toString(horizontalSizeConfiguration) + " "
4005 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004006 synchronized (mGlobalLock) {
4007 ActivityRecord record = ActivityRecord.isInStackLocked(token);
4008 if (record == null) {
4009 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
4010 + "found for: " + token);
4011 }
4012 record.setSizeConfigurations(horizontalSizeConfiguration,
4013 verticalSizeConfigurations, smallestSizeConfigurations);
4014 }
4015 }
4016
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004017 @Override
4018 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004019 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004020 synchronized (mGlobalLock) {
4021 mSuppressResizeConfigChanges = suppress;
4022 }
4023 }
4024
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004025 @Override
4026 // TODO: API should just be about changing windowing modes...
4027 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004028 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004029 "moveTasksToFullscreenStack()");
4030 synchronized (mGlobalLock) {
4031 final long origId = Binder.clearCallingIdentity();
4032 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004033 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004034 if (stack != null){
4035 if (!stack.isActivityTypeStandardOrUndefined()) {
4036 throw new IllegalArgumentException(
4037 "You can't move tasks from non-standard stacks.");
4038 }
4039 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4040 }
4041 } finally {
4042 Binder.restoreCallingIdentity(origId);
4043 }
4044 }
4045 }
4046
4047 /**
4048 * Moves the top activity in the input stackId to the pinned stack.
4049 *
4050 * @param stackId Id of stack to move the top activity to pinned stack.
4051 * @param bounds Bounds to use for pinned stack.
4052 *
4053 * @return True if the top activity of the input stack was successfully moved to the pinned
4054 * stack.
4055 */
4056 @Override
4057 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004058 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004059 "moveTopActivityToPinnedStack()");
4060 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004061 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004062 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4063 + "Device doesn't support picture-in-picture mode");
4064 }
4065
4066 long ident = Binder.clearCallingIdentity();
4067 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004068 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004069 } finally {
4070 Binder.restoreCallingIdentity(ident);
4071 }
4072 }
4073 }
4074
4075 @Override
4076 public boolean isInMultiWindowMode(IBinder token) {
4077 final long origId = Binder.clearCallingIdentity();
4078 try {
4079 synchronized (mGlobalLock) {
4080 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4081 if (r == null) {
4082 return false;
4083 }
4084 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4085 return r.inMultiWindowMode();
4086 }
4087 } finally {
4088 Binder.restoreCallingIdentity(origId);
4089 }
4090 }
4091
4092 @Override
4093 public boolean isInPictureInPictureMode(IBinder token) {
4094 final long origId = Binder.clearCallingIdentity();
4095 try {
4096 synchronized (mGlobalLock) {
4097 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4098 }
4099 } finally {
4100 Binder.restoreCallingIdentity(origId);
4101 }
4102 }
4103
4104 private boolean isInPictureInPictureMode(ActivityRecord r) {
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004105 return r != null
4106 && r.getRootTask() != null
4107 && r.inPinnedWindowingMode()
4108 && r.getRootTask().isInStackLocked(r) != null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004109 }
4110
4111 @Override
4112 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4113 final long origId = Binder.clearCallingIdentity();
4114 try {
4115 synchronized (mGlobalLock) {
4116 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4117 "enterPictureInPictureMode", token, params);
4118
4119 // If the activity is already in picture in picture mode, then just return early
4120 if (isInPictureInPictureMode(r)) {
4121 return true;
4122 }
4123
4124 // Activity supports picture-in-picture, now check that we can enter PiP at this
4125 // point, if it is
4126 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4127 false /* beforeStopping */)) {
4128 return false;
4129 }
4130
4131 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004132 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004133 if (r.getParent() == null) {
4134 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4135 return;
4136 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004137 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004138 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004139 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4140 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4141 // Adjust the source bounds by the insets for the transition down
4142 final Rect sourceBounds = new Rect(
4143 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004144 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004145 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004146 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004147 stack.setPictureInPictureAspectRatio(aspectRatio);
4148 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004149 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4150 r.info.applicationInfo.uid, r.shortComponentName,
4151 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004152 logPictureInPictureArgs(params);
4153 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004154 };
4155
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004156 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004157 // If the keyguard is showing or occluded, then try and dismiss it before
4158 // entering picture-in-picture (this will prompt the user to authenticate if the
4159 // device is currently locked).
4160 dismissKeyguard(token, new KeyguardDismissCallback() {
4161 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004162 public void onDismissSucceeded() {
4163 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004164 }
4165 }, null /* message */);
4166 } else {
4167 // Enter picture in picture immediately otherwise
4168 enterPipRunnable.run();
4169 }
4170 return true;
4171 }
4172 } finally {
4173 Binder.restoreCallingIdentity(origId);
4174 }
4175 }
4176
4177 @Override
4178 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4179 final long origId = Binder.clearCallingIdentity();
4180 try {
4181 synchronized (mGlobalLock) {
4182 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4183 "setPictureInPictureParams", token, params);
4184
4185 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004186 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004187 if (r.inPinnedWindowingMode()) {
4188 // If the activity is already in picture-in-picture, update the pinned stack now
4189 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4190 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004191 final ActivityStack stack = r.getRootTask();
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004192 stack.setPictureInPictureAspectRatio(
4193 r.pictureInPictureArgs.getAspectRatio());
4194 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004195 }
4196 logPictureInPictureArgs(params);
4197 }
4198 } finally {
4199 Binder.restoreCallingIdentity(origId);
4200 }
4201 }
4202
4203 @Override
4204 public int getMaxNumPictureInPictureActions(IBinder token) {
4205 // Currently, this is a static constant, but later, we may change this to be dependent on
4206 // the context of the activity
4207 return 3;
4208 }
4209
4210 private void logPictureInPictureArgs(PictureInPictureParams params) {
4211 if (params.hasSetActions()) {
4212 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4213 params.getActions().size());
4214 }
4215 if (params.hasSetAspectRatio()) {
4216 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4217 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4218 MetricsLogger.action(lm);
4219 }
4220 }
4221
4222 /**
4223 * Checks the state of the system and the activity associated with the given {@param token} to
4224 * verify that picture-in-picture is supported for that activity.
4225 *
4226 * @return the activity record for the given {@param token} if all the checks pass.
4227 */
4228 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4229 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004230 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004231 throw new IllegalStateException(caller
4232 + ": Device doesn't support picture-in-picture mode.");
4233 }
4234
4235 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4236 if (r == null) {
4237 throw new IllegalStateException(caller
4238 + ": Can't find activity for token=" + token);
4239 }
4240
4241 if (!r.supportsPictureInPicture()) {
4242 throw new IllegalStateException(caller
4243 + ": Current activity does not support picture-in-picture.");
4244 }
4245
4246 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004247 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004248 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004249 final float minAspectRatio = mContext.getResources().getFloat(
4250 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4251 final float maxAspectRatio = mContext.getResources().getFloat(
4252 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4253 throw new IllegalArgumentException(String.format(caller
4254 + ": Aspect ratio is too extreme (must be between %f and %f).",
4255 minAspectRatio, maxAspectRatio));
4256 }
4257
4258 // Truncate the number of actions if necessary
4259 params.truncateActions(getMaxNumPictureInPictureActions(token));
4260
4261 return r;
4262 }
4263
4264 @Override
4265 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004266 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004267 synchronized (mGlobalLock) {
4268 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4269 if (r == null) {
4270 throw new IllegalArgumentException("Activity does not exist; token="
4271 + activityToken);
4272 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004273 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004274 }
4275 }
4276
Evan Rosky73a7fe92019-11-18 18:28:01 -08004277 // TODO(b/149338177): remove when CTS no-longer requires it
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004278 @Override
4279 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4280 Rect tempDockedTaskInsetBounds,
4281 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004282 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004283 long ident = Binder.clearCallingIdentity();
4284 try {
4285 synchronized (mGlobalLock) {
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -07004286 final TaskDisplayArea tc = mRootWindowContainer.getDefaultTaskDisplayArea();
4287 final Task primary = tc.getRootSplitScreenPrimaryTask();
4288 final Task secondary = tc.getTask(t -> t.mCreatedByOrganizer && t.isRootTask()
Louis Changa009c762020-02-26 11:21:31 +08004289 && t.inSplitScreenSecondaryWindowingMode());
Evan Rosky73a7fe92019-11-18 18:28:01 -08004290 if (primary == null || secondary == null) {
4291 return;
4292 }
4293 final WindowContainerTransaction wct = new WindowContainerTransaction();
4294 final Rect primaryRect =
4295 tempDockedTaskInsetBounds != null ? tempDockedTaskInsetBounds
4296 : (tempDockedTaskBounds != null ? tempDockedTaskBounds
4297 : dockedBounds);
Wale Ogunwaleadf116e2020-03-27 16:36:01 -07004298 wct.setBounds(primary.mRemoteToken.toWindowContainerToken(), primaryRect);
Evan Rosky73a7fe92019-11-18 18:28:01 -08004299 Rect otherRect = tempOtherTaskInsetBounds != null ? tempOtherTaskInsetBounds
4300 : tempOtherTaskBounds;
4301 if (otherRect == null) {
4302 // Temporary estimation... again this is just for tests.
4303 otherRect = new Rect(secondary.getBounds());
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -07004304 if (tc.getBounds().width() > tc.getBounds().height()) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08004305 otherRect.left = primaryRect.right + 6;
4306 } else {
4307 otherRect.top = primaryRect.bottom + 6;
4308 }
4309 }
Wale Ogunwaleadf116e2020-03-27 16:36:01 -07004310 wct.setBounds(secondary.mRemoteToken.toWindowContainerToken(), otherRect);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004311 mWindowOrganizerController.applyTransaction(wct);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004312 }
4313 } finally {
4314 Binder.restoreCallingIdentity(ident);
4315 }
4316 }
4317
4318 @Override
4319 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004320 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004321 final long ident = Binder.clearCallingIdentity();
4322 try {
4323 synchronized (mGlobalLock) {
4324 mStackSupervisor.setSplitScreenResizing(resizing);
4325 }
4326 } finally {
4327 Binder.restoreCallingIdentity(ident);
4328 }
4329 }
4330
Evan Rosky0037e5f2019-11-05 10:26:24 -08004331 @Override
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004332 public IWindowOrganizerController getWindowOrganizerController() {
Evan Rosky0037e5f2019-11-05 10:26:24 -08004333 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004334 "getWindowOrganizerController()");
4335 return mWindowOrganizerController;
Evan Rosky0037e5f2019-11-05 10:26:24 -08004336 }
4337
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004338 /**
4339 * Check that we have the features required for VR-related API calls, and throw an exception if
4340 * not.
4341 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004342 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004343 if (!mContext.getPackageManager().hasSystemFeature(
4344 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4345 throw new UnsupportedOperationException("VR mode not supported on this device!");
4346 }
4347 }
4348
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004349 @Override
4350 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004351 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004352
4353 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4354
4355 ActivityRecord r;
4356 synchronized (mGlobalLock) {
4357 r = ActivityRecord.isInStackLocked(token);
4358 }
4359
4360 if (r == null) {
4361 throw new IllegalArgumentException();
4362 }
4363
4364 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004365 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004366 VrManagerInternal.NO_ERROR) {
4367 return err;
4368 }
4369
4370 // Clear the binder calling uid since this path may call moveToTask().
4371 final long callingId = Binder.clearCallingIdentity();
4372 try {
4373 synchronized (mGlobalLock) {
4374 r.requestedVrComponent = (enabled) ? packageName : null;
4375
4376 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004377 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004378 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004379 }
4380 return 0;
4381 }
4382 } finally {
4383 Binder.restoreCallingIdentity(callingId);
4384 }
4385 }
4386
4387 @Override
4388 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4389 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4390 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004391 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004392 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4393 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4394 }
Louis Changcdec0802019-11-11 11:45:07 +08004395 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004396 || activity.voiceSession != null) {
4397 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4398 return;
4399 }
4400 if (activity.pendingVoiceInteractionStart) {
4401 Slog.w(TAG, "Pending start of voice interaction already.");
4402 return;
4403 }
4404 activity.pendingVoiceInteractionStart = true;
4405 }
4406 LocalServices.getService(VoiceInteractionManagerInternal.class)
4407 .startLocalVoiceInteraction(callingActivity, options);
4408 }
4409
4410 @Override
4411 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4412 LocalServices.getService(VoiceInteractionManagerInternal.class)
4413 .stopLocalVoiceInteraction(callingActivity);
4414 }
4415
4416 @Override
4417 public boolean supportsLocalVoiceInteraction() {
4418 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4419 .supportsLocalVoiceInteraction();
4420 }
4421
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004422 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004423 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004424 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004425
4426 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004427 if (mWindowManager == null) {
4428 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4429 return false;
4430 }
4431
4432 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004433 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004434 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004435 }
4436
Riddle Hsua0022cd2019-09-09 21:12:41 +08004437 mH.sendMessage(PooledLambda.obtainMessage(
4438 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4439 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004440
4441 final long origId = Binder.clearCallingIdentity();
4442 try {
4443 if (values != null) {
4444 Settings.System.clearConfiguration(values);
4445 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004446 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004447 UserHandle.USER_NULL, false /* deferResume */,
4448 mTmpUpdateConfigurationResult);
4449 return mTmpUpdateConfigurationResult.changes != 0;
4450 } finally {
4451 Binder.restoreCallingIdentity(origId);
4452 }
4453 }
4454 }
4455
4456 @Override
4457 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4458 CharSequence message) {
4459 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004460 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004461 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4462 }
4463 final long callingId = Binder.clearCallingIdentity();
4464 try {
4465 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004466 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004467 }
4468 } finally {
4469 Binder.restoreCallingIdentity(callingId);
4470 }
4471 }
4472
4473 @Override
4474 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004475 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004476 "cancelTaskWindowTransition()");
4477 final long ident = Binder.clearCallingIdentity();
4478 try {
4479 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004480 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004481 MATCH_TASK_IN_STACKS_ONLY);
4482 if (task == null) {
4483 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4484 return;
4485 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004486 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004487 }
4488 } finally {
4489 Binder.restoreCallingIdentity(ident);
4490 }
4491 }
4492
4493 @Override
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004494 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004495 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004496 final long ident = Binder.clearCallingIdentity();
4497 try {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004498 return getTaskSnapshot(taskId, isLowResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004499 } finally {
4500 Binder.restoreCallingIdentity(ident);
4501 }
4502 }
4503
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004504 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004505 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004506 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004507 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004508 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004509 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4510 if (task == null) {
4511 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4512 return null;
4513 }
4514 }
4515 // Don't call this while holding the lock as this operation might hit the disk.
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004516 return task.getSnapshot(isLowResolution, restoreFromDisk);
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004517 }
4518
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004519 @Override
4520 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4521 synchronized (mGlobalLock) {
4522 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4523 if (r == null) {
4524 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4525 + token);
4526 return;
4527 }
4528 final long origId = Binder.clearCallingIdentity();
4529 try {
4530 r.setDisablePreviewScreenshots(disable);
4531 } finally {
4532 Binder.restoreCallingIdentity(origId);
4533 }
4534 }
4535 }
4536
Riddle Hsu440f88b2019-11-06 22:17:35 +08004537 @Override
4538 public void invalidateHomeTaskSnapshot(IBinder token) {
4539 synchronized (mGlobalLock) {
4540 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4541 if (r == null || !r.isActivityTypeHome()) {
4542 return;
4543 }
4544 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4545 }
4546 }
4547
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004548 /** Return the user id of the last resumed activity. */
4549 @Override
4550 public @UserIdInt
4551 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004552 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004553 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4554 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004555 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004556 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004557 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004558 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004559 }
4560 }
4561
4562 @Override
4563 public void updateLockTaskFeatures(int userId, int flags) {
4564 final int callingUid = Binder.getCallingUid();
4565 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004566 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004567 "updateLockTaskFeatures()");
4568 }
4569 synchronized (mGlobalLock) {
4570 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4571 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004572 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004573 }
4574 }
4575
4576 @Override
4577 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4578 synchronized (mGlobalLock) {
4579 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4580 if (r == null) {
4581 return;
4582 }
4583 final long origId = Binder.clearCallingIdentity();
4584 try {
4585 r.setShowWhenLocked(showWhenLocked);
4586 } finally {
4587 Binder.restoreCallingIdentity(origId);
4588 }
4589 }
4590 }
4591
4592 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004593 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4594 synchronized (mGlobalLock) {
4595 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4596 if (r == null) {
4597 return;
4598 }
4599 final long origId = Binder.clearCallingIdentity();
4600 try {
4601 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4602 } finally {
4603 Binder.restoreCallingIdentity(origId);
4604 }
4605 }
4606 }
4607
4608 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004609 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4610 synchronized (mGlobalLock) {
4611 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4612 if (r == null) {
4613 return;
4614 }
4615 final long origId = Binder.clearCallingIdentity();
4616 try {
4617 r.setTurnScreenOn(turnScreenOn);
4618 } finally {
4619 Binder.restoreCallingIdentity(origId);
4620 }
4621 }
4622 }
4623
4624 @Override
4625 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004626 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004627 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004628 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004629 synchronized (mGlobalLock) {
4630 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4631 if (r == null) {
4632 return;
4633 }
4634 final long origId = Binder.clearCallingIdentity();
4635 try {
4636 r.registerRemoteAnimations(definition);
4637 } finally {
4638 Binder.restoreCallingIdentity(origId);
4639 }
4640 }
4641 }
4642
4643 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004644 public void unregisterRemoteAnimations(IBinder token) {
4645 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4646 "unregisterRemoteAnimations");
4647 synchronized (mGlobalLock) {
4648 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4649 if (r == null) {
4650 return;
4651 }
4652 final long origId = Binder.clearCallingIdentity();
4653 try {
4654 r.unregisterRemoteAnimations();
4655 } finally {
4656 Binder.restoreCallingIdentity(origId);
4657 }
4658 }
4659 }
4660
4661 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004662 public void registerRemoteAnimationForNextActivityStart(String packageName,
4663 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004664 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004665 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004666 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004667 synchronized (mGlobalLock) {
4668 final long origId = Binder.clearCallingIdentity();
4669 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004670 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004671 packageName, adapter);
4672 } finally {
4673 Binder.restoreCallingIdentity(origId);
4674 }
4675 }
4676 }
4677
Evan Rosky966759f2019-01-15 10:33:58 -08004678 @Override
4679 public void registerRemoteAnimationsForDisplay(int displayId,
4680 RemoteAnimationDefinition definition) {
4681 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4682 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004683 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004684 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004685 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004686 if (display == null) {
4687 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4688 return;
4689 }
4690 final long origId = Binder.clearCallingIdentity();
4691 try {
4692 display.mDisplayContent.registerRemoteAnimations(definition);
4693 } finally {
4694 Binder.restoreCallingIdentity(origId);
4695 }
4696 }
4697 }
4698
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004699 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4700 @Override
4701 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4702 synchronized (mGlobalLock) {
4703 final long origId = Binder.clearCallingIdentity();
4704 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004705 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004706 } finally {
4707 Binder.restoreCallingIdentity(origId);
4708 }
4709 }
4710 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004711
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004712 @Override
4713 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004714 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004715 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004716 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004717 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004718 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004719 }
4720 }
4721
4722 @Override
4723 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004724 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004725 != PERMISSION_GRANTED) {
4726 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4727 + Binder.getCallingPid()
4728 + ", uid=" + Binder.getCallingUid()
4729 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4730 Slog.w(TAG, msg);
4731 throw new SecurityException(msg);
4732 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004733 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004734 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004735 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004736 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004737 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004738 }
4739 }
4740
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004741 @Override
4742 public void stopAppSwitches() {
4743 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4744 synchronized (mGlobalLock) {
4745 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004746 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004747 mDidAppSwitch = false;
4748 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4749 }
4750 }
4751
4752 @Override
4753 public void resumeAppSwitches() {
4754 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4755 synchronized (mGlobalLock) {
4756 // Note that we don't execute any pending app switches... we will
4757 // let those wait until either the timeout, or the next start
4758 // activity request.
4759 mAppSwitchesAllowedTime = 0;
4760 }
4761 }
4762
Ricky Wai906af482019-06-03 17:25:28 +01004763 long getLastStopAppSwitchesTime() {
4764 return mLastStopAppSwitchesTime;
4765 }
4766
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004767 void onStartActivitySetDidAppSwitch() {
4768 if (mDidAppSwitch) {
4769 // This is the second allowed switch since we stopped switches, so now just generally
4770 // allow switches. Use case:
4771 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4772 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4773 // anyone to switch again).
4774 mAppSwitchesAllowedTime = 0;
4775 } else {
4776 mDidAppSwitch = true;
4777 }
4778 }
4779
4780 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004781 boolean shouldDisableNonVrUiLocked() {
4782 return mVrController.shouldDisableNonVrUiLocked();
4783 }
4784
Wale Ogunwale53783742018-09-16 10:21:51 -07004785 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004786 // VR apps are expected to run in a main display. If an app is turning on VR for
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004787 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004788 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004789 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4790 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004791 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004792 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004793 }
4794 mH.post(() -> {
4795 if (!mVrController.onVrModeChanged(r)) {
4796 return;
4797 }
4798 synchronized (mGlobalLock) {
4799 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4800 mWindowManager.disableNonVrUi(disableNonVrUi);
4801 if (disableNonVrUi) {
4802 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4803 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004804 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004805 }
4806 }
4807 });
4808 }
4809
Wale Ogunwale53783742018-09-16 10:21:51 -07004810 @Override
4811 public int getPackageScreenCompatMode(String packageName) {
4812 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4813 synchronized (mGlobalLock) {
4814 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4815 }
4816 }
4817
4818 @Override
4819 public void setPackageScreenCompatMode(String packageName, int mode) {
4820 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4821 "setPackageScreenCompatMode");
4822 synchronized (mGlobalLock) {
4823 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4824 }
4825 }
4826
4827 @Override
4828 public boolean getPackageAskScreenCompat(String packageName) {
4829 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4830 synchronized (mGlobalLock) {
4831 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4832 }
4833 }
4834
4835 @Override
4836 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4837 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4838 "setPackageAskScreenCompat");
4839 synchronized (mGlobalLock) {
4840 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4841 }
4842 }
4843
Wale Ogunwale64258362018-10-16 15:13:37 -07004844 public static String relaunchReasonToString(int relaunchReason) {
4845 switch (relaunchReason) {
4846 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4847 return "window_resize";
4848 case RELAUNCH_REASON_FREE_RESIZE:
4849 return "free_resize";
4850 default:
4851 return null;
4852 }
4853 }
4854
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004855 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004856 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004857 }
4858
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004859 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004860 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004861 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4862 }
4863
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004864 boolean isKeyguardLocked() {
4865 return mKeyguardController.isKeyguardLocked();
4866 }
4867
Garfield Tan01548632018-11-27 10:15:48 -08004868 /**
4869 * Clears launch params for the given package.
4870 * @param packageNames the names of the packages of which the launch params are to be cleared
4871 */
4872 @Override
4873 public void clearLaunchParamsForPackages(List<String> packageNames) {
4874 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4875 "clearLaunchParamsForPackages");
4876 synchronized (mGlobalLock) {
4877 for (int i = 0; i < packageNames.size(); ++i) {
4878 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4879 }
4880 }
4881 }
4882
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004883 /**
4884 * Makes the display with the given id a single task instance display. I.e the display can only
4885 * contain one task.
4886 */
4887 @Override
4888 public void setDisplayToSingleTaskInstance(int displayId) {
4889 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4890 "setDisplayToSingleTaskInstance");
4891 final long origId = Binder.clearCallingIdentity();
4892 try {
Louis Chang677921f2019-12-06 16:44:24 +08004893 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004894 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004895 if (display != null) {
4896 display.setDisplayToSingleTaskInstance();
4897 }
4898 } finally {
4899 Binder.restoreCallingIdentity(origId);
4900 }
4901 }
4902
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004903 /**
4904 * Requests that an activity should enter picture-in-picture mode if possible.
4905 */
4906 @Override
4907 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4908 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4909 "requestPictureInPictureMode");
4910 final long origId = Binder.clearCallingIdentity();
4911 try {
4912 synchronized (mGlobalLock) {
4913 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4914 if (activity == null) {
4915 return;
4916 }
4917
4918 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4919 "requestPictureInPictureMode", /* beforeStopping */ false);
4920 if (!canEnterPictureInPicture) {
4921 throw new IllegalStateException(
4922 "Requested PIP on an activity that doesn't support it");
4923 }
4924
4925 try {
4926 final ClientTransaction transaction = ClientTransaction.obtain(
4927 activity.app.getThread(),
4928 activity.token);
4929 transaction.addCallback(EnterPipRequestedItem.obtain());
4930 getLifecycleManager().scheduleTransaction(transaction);
4931 } catch (Exception e) {
4932 Slog.w(TAG, "Failed to send enter pip requested item: "
4933 + activity.intent.getComponent(), e);
4934 }
4935 }
4936 } finally {
4937 Binder.restoreCallingIdentity(origId);
4938 }
4939 }
4940
Wale Ogunwale31913b52018-10-13 08:29:31 -07004941 void dumpLastANRLocked(PrintWriter pw) {
4942 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4943 if (mLastANRState == null) {
4944 pw.println(" <no ANR has occurred since boot>");
4945 } else {
4946 pw.println(mLastANRState);
4947 }
4948 }
4949
4950 void dumpLastANRTracesLocked(PrintWriter pw) {
4951 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4952
4953 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4954 if (ArrayUtils.isEmpty(files)) {
4955 pw.println(" <no ANR has occurred since boot>");
4956 return;
4957 }
4958 // Find the latest file.
4959 File latest = null;
4960 for (File f : files) {
4961 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4962 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004963 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004964 }
4965 pw.print("File: ");
4966 pw.print(latest.getName());
4967 pw.println();
4968 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4969 String line;
4970 while ((line = in.readLine()) != null) {
4971 pw.println(line);
4972 }
4973 } catch (IOException e) {
4974 pw.print("Unable to read: ");
4975 pw.print(e);
4976 pw.println();
4977 }
4978 }
4979
4980 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4981 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4982 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4983 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4984 }
4985
4986 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4987 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4988 pw.println(header);
4989
Louis Chang149d5c82019-12-30 09:47:39 +08004990 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004991 dumpPackage);
4992 boolean needSep = printedAnything;
4993
4994 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08004995 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004996 " ResumedActivity: ");
4997 if (printed) {
4998 printedAnything = true;
4999 needSep = false;
5000 }
5001
5002 if (dumpPackage == null) {
5003 if (needSep) {
5004 pw.println();
5005 }
5006 printedAnything = true;
5007 mStackSupervisor.dump(pw, " ");
Winson Chung268eccb2020-03-26 13:43:44 -07005008 mTaskOrganizerController.dump(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005009 }
5010
5011 if (!printedAnything) {
5012 pw.println(" (nothing)");
5013 }
5014 }
5015
5016 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005017 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005018 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005019 pw.println(" ");
5020 }
5021
5022 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5023 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5024 getActivityStartController().dump(pw, "", dumpPackage);
5025 }
5026
5027 /**
5028 * There are three things that cmd can be:
5029 * - a flattened component name that matches an existing activity
5030 * - the cmd arg isn't the flattened component name of an existing activity:
5031 * dump all activity whose component contains the cmd as a substring
5032 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005033 * <p>
5034 * The caller should not hold lock when calling this method because it will wait for the
5035 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005036 *
5037 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5038 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5039 */
5040 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5041 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5042 ArrayList<ActivityRecord> activities;
5043
5044 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005045 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005046 dumpFocusedStackOnly);
5047 }
5048
5049 if (activities.size() <= 0) {
5050 return false;
5051 }
5052
5053 String[] newArgs = new String[args.length - opti];
5054 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5055
Louis Changcdec0802019-11-11 11:45:07 +08005056 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005057 boolean needSep = false;
5058 for (int i = activities.size() - 1; i >= 0; i--) {
5059 ActivityRecord r = activities.get(i);
5060 if (needSep) {
5061 pw.println();
5062 }
5063 needSep = true;
5064 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005065 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005066 if (lastTask != task) {
5067 lastTask = task;
5068 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005069 pw.print(" id="); pw.print(lastTask.mTaskId);
5070 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005071 if (dumpAll) {
5072 lastTask.dump(pw, " ");
5073 }
5074 }
5075 }
5076 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5077 }
5078 return true;
5079 }
5080
5081 /**
5082 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5083 * there is a thread associated with the activity.
5084 */
5085 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5086 final ActivityRecord r, String[] args, boolean dumpAll) {
5087 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005088 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005089 synchronized (mGlobalLock) {
5090 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5091 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5092 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005093 if (r.hasProcess()) {
5094 pw.println(r.app.getPid());
5095 appThread = r.app.getThread();
5096 } else {
5097 pw.println("(not running)");
5098 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005099 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005100 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005101 }
5102 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005103 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005104 // flush anything that is already in the PrintWriter since the thread is going
5105 // to write to the file descriptor directly
5106 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005107 try (TransferPipe tp = new TransferPipe()) {
5108 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5109 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005110 } catch (IOException e) {
5111 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5112 } catch (RemoteException e) {
5113 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5114 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005115 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005116 }
5117
sanryhuang498e77e2018-12-06 14:57:01 +08005118 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5119 boolean testPssMode) {
5120 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5121 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5122 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005123 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005124 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5125 st.toString());
5126 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005127 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5128 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5129 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005130 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5131 testPssMode);
5132 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005133 }
5134
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005135 int getCurrentUserId() {
5136 return mAmInternal.getCurrentUserId();
5137 }
5138
5139 private void enforceNotIsolatedCaller(String caller) {
5140 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5141 throw new SecurityException("Isolated process not allowed to call " + caller);
5142 }
5143 }
5144
Wale Ogunwalef6733932018-06-27 05:14:34 -07005145 public Configuration getConfiguration() {
5146 Configuration ci;
5147 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005148 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005149 ci.userSetLocale = false;
5150 }
5151 return ci;
5152 }
5153
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005154 /**
5155 * Current global configuration information. Contains general settings for the entire system,
5156 * also corresponds to the merged configuration of the default display.
5157 */
5158 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005159 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005160 // while initializing process record for system, see {@link
5161 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005162 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005163 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005164 }
5165
5166 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5167 boolean initLocale) {
5168 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5169 }
5170
5171 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5172 boolean initLocale, boolean deferResume) {
5173 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5174 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5175 UserHandle.USER_NULL, deferResume);
5176 }
5177
Wale Ogunwale59507092018-10-29 09:00:30 -07005178 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005179 final long origId = Binder.clearCallingIdentity();
5180 try {
5181 synchronized (mGlobalLock) {
5182 updateConfigurationLocked(values, null, false, true, userId,
5183 false /* deferResume */);
5184 }
5185 } finally {
5186 Binder.restoreCallingIdentity(origId);
5187 }
5188 }
5189
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005190 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5191 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5192 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5193 deferResume, null /* result */);
5194 }
5195
5196 /**
5197 * Do either or both things: (1) change the current configuration, and (2)
5198 * make sure the given activity is running with the (now) current
5199 * configuration. Returns true if the activity has been left running, or
5200 * false if <var>starting</var> is being destroyed to match the new
5201 * configuration.
5202 *
5203 * @param userId is only used when persistent parameter is set to true to persist configuration
5204 * for that particular user
5205 */
5206 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5207 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5208 ActivityTaskManagerService.UpdateConfigurationResult result) {
5209 int changes = 0;
5210 boolean kept = true;
5211
Riddle Hsua0022cd2019-09-09 21:12:41 +08005212 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005213 try {
5214 if (values != null) {
5215 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5216 deferResume);
5217 }
5218
5219 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5220 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005221 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005222 }
5223
5224 if (result != null) {
5225 result.changes = changes;
5226 result.activityRelaunched = !kept;
5227 }
5228 return kept;
5229 }
5230
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005231 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005232 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005233 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005234
Louis Chang677921f2019-12-06 16:44:24 +08005235 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005236 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005237
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005238 mTempConfig.setTo(getGlobalConfiguration());
5239 final int changes = mTempConfig.updateFrom(values);
5240 if (changes == 0) {
5241 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5242 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5243 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5244 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005245 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005246 return 0;
5247 }
5248
5249 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5250 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005251 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005252 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005253 values.colorMode,
5254 values.densityDpi,
5255 values.fontScale,
5256 values.hardKeyboardHidden,
5257 values.keyboard,
5258 values.keyboardHidden,
5259 values.mcc,
5260 values.mnc,
5261 values.navigation,
5262 values.navigationHidden,
5263 values.orientation,
5264 values.screenHeightDp,
5265 values.screenLayout,
5266 values.screenWidthDp,
5267 values.smallestScreenWidthDp,
5268 values.touchscreen,
5269 values.uiMode);
5270
5271
5272 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5273 final LocaleList locales = values.getLocales();
5274 int bestLocaleIndex = 0;
5275 if (locales.size() > 1) {
5276 if (mSupportedSystemLocales == null) {
5277 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5278 }
5279 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5280 }
5281 SystemProperties.set("persist.sys.locale",
5282 locales.get(bestLocaleIndex).toLanguageTag());
5283 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005284
5285 final Message m = PooledLambda.obtainMessage(
5286 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5287 locales.get(bestLocaleIndex));
5288 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005289 }
5290
Yunfan Chen75157d72018-07-27 14:47:21 +09005291 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005292
5293 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005294 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005295
5296 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5297 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005298 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005299
5300 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005301 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005302
5303 AttributeCache ac = AttributeCache.instance();
5304 if (ac != null) {
5305 ac.updateConfiguration(mTempConfig);
5306 }
5307
5308 // Make sure all resources in our process are updated right now, so that anyone who is going
5309 // to retrieve resource values after we return will be sure to get the new ones. This is
5310 // especially important during boot, where the first config change needs to guarantee all
5311 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005312 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005313
5314 // We need another copy of global config because we're scheduling some calls instead of
5315 // running them in place. We need to be sure that object we send will be handled unchanged.
5316 final Configuration configCopy = new Configuration(mTempConfig);
5317 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005318 final Message msg = PooledLambda.obtainMessage(
5319 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5320 this, userId, configCopy);
5321 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005322 }
5323
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005324 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5325 for (int i = pidMap.size() - 1; i >= 0; i--) {
5326 final int pid = pidMap.keyAt(i);
5327 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005328 if (DEBUG_CONFIGURATION) {
5329 Slog.v(TAG_CONFIGURATION, "Update process config of "
5330 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005331 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005332 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005333 }
5334
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005335 final Message msg = PooledLambda.obtainMessage(
5336 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5337 mAmInternal, changes, initLocale);
5338 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005339
5340 // Override configuration of the default display duplicates global config, so we need to
5341 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005342 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005343 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005344
5345 return changes;
5346 }
5347
Riddle Hsua0022cd2019-09-09 21:12:41 +08005348 /** @see WindowSurfacePlacer#deferLayout */
5349 void deferWindowLayout() {
5350 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5351 // Reset the reasons at the first entrance because we only care about the changes in the
5352 // deferred scope.
5353 mLayoutReasons = 0;
5354 }
5355
5356 mWindowManager.mWindowPlacerLocked.deferLayout();
5357 }
5358
5359 /** @see WindowSurfacePlacer#continueLayout */
5360 void continueWindowLayout() {
5361 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5362 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5363 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5364 }
5365 }
5366
5367 /**
5368 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5369 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5370 * defer count is gone.
5371 */
5372 void addWindowLayoutReasons(@LayoutReason int reasons) {
5373 mLayoutReasons |= reasons;
5374 }
5375
Wale Ogunwalef6733932018-06-27 05:14:34 -07005376 private void updateEventDispatchingLocked(boolean booted) {
5377 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5378 }
5379
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005380 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5381 final ContentResolver resolver = mContext.getContentResolver();
5382 Settings.System.putConfigurationForUser(resolver, config, userId);
5383 }
5384
5385 private void sendLocaleToMountDaemonMsg(Locale l) {
5386 try {
5387 IBinder service = ServiceManager.getService("mount");
5388 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5389 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5390 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5391 } catch (RemoteException e) {
5392 Log.e(TAG, "Error storing locale for decryption UI", e);
5393 }
5394 }
5395
Alison Cichowlas3e340502018-08-07 17:15:01 -04005396 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5397 mStartActivitySources.remove(permissionToken);
5398 mExpiredStartAsCallerTokens.add(permissionToken);
5399 }
5400
5401 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5402 mExpiredStartAsCallerTokens.remove(permissionToken);
5403 }
5404
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005405 boolean isActivityStartsLoggingEnabled() {
5406 return mAmInternal.isActivityStartsLoggingEnabled();
5407 }
5408
Michal Karpinski8596ded2018-11-14 14:43:48 +00005409 boolean isBackgroundActivityStartsEnabled() {
5410 return mAmInternal.isBackgroundActivityStartsEnabled();
5411 }
5412
Wale Ogunwalef6733932018-06-27 05:14:34 -07005413 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005414 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005415 mWindowManager.enableScreenAfterBoot();
5416
5417 synchronized (mGlobalLock) {
5418 updateEventDispatchingLocked(booted);
5419 }
5420 }
5421
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005422 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5423 if (r == null || !r.hasProcess()) {
5424 return KEY_DISPATCHING_TIMEOUT_MS;
5425 }
5426 return getInputDispatchingTimeoutLocked(r.app);
5427 }
5428
5429 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005430 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005431 }
5432
Wale Ogunwalef6733932018-06-27 05:14:34 -07005433 /**
5434 * Decide based on the configuration whether we should show the ANR,
5435 * crash, etc dialogs. The idea is that if there is no affordance to
5436 * press the on-screen buttons, or the user experience would be more
5437 * greatly impacted than the crash itself, we shouldn't show the dialog.
5438 *
5439 * A thought: SystemUI might also want to get told about this, the Power
5440 * dialog / global actions also might want different behaviors.
5441 */
5442 private void updateShouldShowDialogsLocked(Configuration config) {
5443 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5444 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5445 && config.navigation == Configuration.NAVIGATION_NONAV);
5446 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5447 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5448 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5449 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5450 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5451 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5452 HIDE_ERROR_DIALOGS, 0) != 0;
5453 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5454 }
5455
5456 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5457 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5458 FONT_SCALE, 1.0f, userId);
5459
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005460 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005461 if (getGlobalConfiguration().fontScale == scaleFactor) {
5462 return;
5463 }
5464
5465 final Configuration configuration
5466 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5467 configuration.fontScale = scaleFactor;
5468 updatePersistentConfiguration(configuration, userId);
5469 }
5470 }
5471
5472 // Actually is sleeping or shutting down or whatever else in the future
5473 // is an inactive state.
5474 boolean isSleepingOrShuttingDownLocked() {
5475 return isSleepingLocked() || mShuttingDown;
5476 }
5477
5478 boolean isSleepingLocked() {
5479 return mSleeping;
5480 }
5481
Riddle Hsu16567132018-08-16 21:37:47 +08005482 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005483 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005484 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005485 if (task.isActivityTypeStandard()) {
5486 if (mCurAppTimeTracker != r.appTimeTracker) {
5487 // We are switching app tracking. Complete the current one.
5488 if (mCurAppTimeTracker != null) {
5489 mCurAppTimeTracker.stop();
5490 mH.obtainMessage(
5491 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005492 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005493 mCurAppTimeTracker = null;
5494 }
5495 if (r.appTimeTracker != null) {
5496 mCurAppTimeTracker = r.appTimeTracker;
5497 startTimeTrackingFocusedActivityLocked();
5498 }
5499 } else {
5500 startTimeTrackingFocusedActivityLocked();
5501 }
5502 } else {
5503 r.appTimeTracker = null;
5504 }
5505 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5506 // TODO: Probably not, because we don't want to resume voice on switching
5507 // back to this activity
5508 if (task.voiceInteractor != null) {
5509 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5510 } else {
5511 finishRunningVoiceLocked();
5512
5513 if (mLastResumedActivity != null) {
5514 final IVoiceInteractionSession session;
5515
Louis Changcdec0802019-11-11 11:45:07 +08005516 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005517 if (lastResumedActivityTask != null
5518 && lastResumedActivityTask.voiceSession != null) {
5519 session = lastResumedActivityTask.voiceSession;
5520 } else {
5521 session = mLastResumedActivity.voiceSession;
5522 }
5523
5524 if (session != null) {
5525 // We had been in a voice interaction session, but now focused has
5526 // move to something different. Just finish the session, we can't
5527 // return to it and retain the proper state and synchronization with
5528 // the voice interaction service.
5529 finishVoiceTask(session);
5530 }
5531 }
5532 }
5533
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005534 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5535 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005536 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005537 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5538
Wale Ogunwalef6733932018-06-27 05:14:34 -07005539 updateResumedAppTrace(r);
5540 mLastResumedActivity = r;
5541
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005542 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005543
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005544 if (prevTask == null || task != prevTask) {
5545 if (prevTask != null) {
5546 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5547 }
5548 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5549 }
5550
Wale Ogunwalef6733932018-06-27 05:14:34 -07005551 applyUpdateLockStateLocked(r);
5552 applyUpdateVrModeLocked(r);
5553
Jeff Changd136e772019-11-05 20:33:52 +08005554 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005555 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005556 r == null ? "NULL" : r.shortComponentName,
5557 reason);
5558 }
5559
5560 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5561 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005562 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005563 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005564 updateSleepIfNeededLocked();
5565 return token;
5566 }
5567 }
5568
5569 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005570 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005571 final boolean wasSleeping = mSleeping;
5572 boolean updateOomAdj = false;
5573
5574 if (!shouldSleep) {
5575 // If wasSleeping is true, we need to wake up activity manager state from when
5576 // we started sleeping. In either case, we need to apply the sleep tokens, which
5577 // will wake up stacks or put them to sleep as appropriate.
5578 if (wasSleeping) {
5579 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005580 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5581 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005582 startTimeTrackingFocusedActivityLocked();
5583 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005584 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005585 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5586 }
Louis Chang149d5c82019-12-30 09:47:39 +08005587 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005588 if (wasSleeping) {
5589 updateOomAdj = true;
5590 }
5591 } else if (!mSleeping && shouldSleep) {
5592 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005593 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5594 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005595 if (mCurAppTimeTracker != null) {
5596 mCurAppTimeTracker.stop();
5597 }
5598 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005599 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005600 mStackSupervisor.goingToSleepLocked();
5601 updateResumedAppTrace(null /* resumed */);
5602 updateOomAdj = true;
5603 }
5604 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005605 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005606 }
5607 }
5608
5609 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005610 mH.removeCallbacks(mUpdateOomAdjRunnable);
5611 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005612 }
5613
Wale Ogunwale53783742018-09-16 10:21:51 -07005614 void updateCpuStats() {
5615 mH.post(mAmInternal::updateCpuStats);
5616 }
5617
Hui Yu03d12402018-12-06 18:00:37 -08005618 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5619 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005620 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5621 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005622 mH.sendMessage(m);
5623 }
5624
Hui Yu03d12402018-12-06 18:00:37 -08005625 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005626 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005627 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005628 if (task != null) {
5629 final ActivityRecord rootActivity = task.getRootActivity();
5630 if (rootActivity != null) {
5631 taskRoot = rootActivity.mActivityComponent;
5632 }
5633 }
5634
Hui Yu03d12402018-12-06 18:00:37 -08005635 final Message m = PooledLambda.obtainMessage(
5636 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005637 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005638 mH.sendMessage(m);
5639 }
5640
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005641 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5642 String hostingType) {
5643 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005644 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5645 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005646 + activity.processName);
5647 }
5648 // Post message to start process to avoid possible deadlock of calling into AMS with the
5649 // ATMS lock held.
5650 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5651 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5652 isTop, hostingType, activity.intent.getComponent());
5653 mH.sendMessage(m);
5654 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005655 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005656 }
5657 }
5658
Wale Ogunwale53783742018-09-16 10:21:51 -07005659 void setBooting(boolean booting) {
5660 mAmInternal.setBooting(booting);
5661 }
5662
5663 boolean isBooting() {
5664 return mAmInternal.isBooting();
5665 }
5666
5667 void setBooted(boolean booted) {
5668 mAmInternal.setBooted(booted);
5669 }
5670
5671 boolean isBooted() {
5672 return mAmInternal.isBooted();
5673 }
5674
5675 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5676 mH.post(() -> {
5677 if (finishBooting) {
5678 mAmInternal.finishBooting();
5679 }
5680 if (enableScreen) {
5681 mInternal.enableScreenAfterBoot(isBooted());
5682 }
5683 });
5684 }
5685
5686 void setHeavyWeightProcess(ActivityRecord root) {
5687 mHeavyWeightProcess = root.app;
5688 final Message m = PooledLambda.obtainMessage(
5689 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005690 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005691 mH.sendMessage(m);
5692 }
5693
5694 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5695 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5696 return;
5697 }
5698
5699 mHeavyWeightProcess = null;
5700 final Message m = PooledLambda.obtainMessage(
5701 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5702 proc.mUserId);
5703 mH.sendMessage(m);
5704 }
5705
5706 private void cancelHeavyWeightProcessNotification(int userId) {
5707 final INotificationManager inm = NotificationManager.getService();
5708 if (inm == null) {
5709 return;
5710 }
5711 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005712 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005713 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5714 } catch (RuntimeException e) {
5715 Slog.w(TAG, "Error canceling notification for service", e);
5716 } catch (RemoteException e) {
5717 }
5718
5719 }
5720
5721 private void postHeavyWeightProcessNotification(
5722 WindowProcessController proc, Intent intent, int userId) {
5723 if (proc == null) {
5724 return;
5725 }
5726
5727 final INotificationManager inm = NotificationManager.getService();
5728 if (inm == null) {
5729 return;
5730 }
5731
5732 try {
5733 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5734 String text = mContext.getString(R.string.heavy_weight_notification,
5735 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5736 Notification notification =
5737 new Notification.Builder(context,
5738 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5739 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5740 .setWhen(0)
5741 .setOngoing(true)
5742 .setTicker(text)
5743 .setColor(mContext.getColor(
5744 com.android.internal.R.color.system_notification_accent_color))
5745 .setContentTitle(text)
5746 .setContentText(
5747 mContext.getText(R.string.heavy_weight_notification_detail))
5748 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5749 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5750 new UserHandle(userId)))
5751 .build();
5752 try {
5753 inm.enqueueNotificationWithTag("android", "android", null,
5754 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5755 } catch (RuntimeException e) {
5756 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5757 } catch (RemoteException e) {
5758 }
5759 } catch (PackageManager.NameNotFoundException e) {
5760 Slog.w(TAG, "Unable to create context for heavy notification", e);
5761 }
5762
5763 }
5764
Philip P. Moltmannee295092020-02-10 08:46:26 -08005765 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5766 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5767 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005768
5769 ActivityRecord activity = null;
5770 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5771 activity = ActivityRecord.isInStackLocked(token);
5772 if (activity == null) {
5773 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5774 return null;
5775 }
5776 if (activity.finishing) {
5777 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5778 return null;
5779 }
5780 }
5781
5782 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005783 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5784 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005785 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5786 if (noCreate) {
5787 return rec;
5788 }
5789 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5790 if (activity.pendingResults == null) {
5791 activity.pendingResults = new HashSet<>();
5792 }
5793 activity.pendingResults.add(rec.ref);
5794 }
5795 return rec;
5796 }
5797
Andrii Kulian52d255c2018-07-13 11:32:19 -07005798 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005799 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005800 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005801 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5802 mCurAppTimeTracker.start(resumedActivity.packageName);
5803 }
5804 }
5805
5806 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5807 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005808 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005809 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5810 }
5811 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005812 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005813 constructResumedTraceName(resumed.packageName), 0);
5814 }
5815 mTracedResumedActivity = resumed;
5816 }
5817
5818 private String constructResumedTraceName(String packageName) {
5819 return "focused app: " + packageName;
5820 }
5821
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005822 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005823 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005824 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005825 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005826 // mainStack is null during startup.
5827 if (mainStack != null) {
5828 if (changes != 0 && starting == null) {
5829 // If the configuration changed, and the caller is not already
5830 // in the process of starting an activity, then find the top
5831 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005832 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005833 }
5834
5835 if (starting != null) {
5836 kept = starting.ensureActivityConfiguration(changes,
5837 false /* preserveWindow */);
5838 // And we need to make sure at this point that all other activities
5839 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005840 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005841 !PRESERVE_WINDOWS);
5842 }
5843 }
5844
5845 return kept;
5846 }
5847
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005848 void scheduleAppGcsLocked() {
5849 mH.post(() -> mAmInternal.scheduleAppGcs());
5850 }
5851
Wale Ogunwale53783742018-09-16 10:21:51 -07005852 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5853 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5854 }
5855
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005856 /**
5857 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5858 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5859 * on demand.
5860 */
5861 IPackageManager getPackageManager() {
5862 return AppGlobals.getPackageManager();
5863 }
5864
5865 PackageManagerInternal getPackageManagerInternalLocked() {
5866 if (mPmInternal == null) {
5867 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5868 }
5869 return mPmInternal;
5870 }
5871
Darryl L Johnsona0982222020-02-18 18:21:51 -08005872 ComponentName getSysUiServiceComponentLocked() {
5873 if (mSysUiServiceComponent == null) {
5874 final PackageManagerInternal pm = getPackageManagerInternalLocked();
5875 mSysUiServiceComponent = pm.getSystemUiServiceComponent();
5876 }
5877 return mSysUiServiceComponent;
5878 }
5879
Hai Zhangf4da9be2019-05-01 13:46:06 +08005880 PermissionPolicyInternal getPermissionPolicyInternal() {
5881 if (mPermissionPolicyInternal == null) {
5882 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5883 }
5884 return mPermissionPolicyInternal;
5885 }
5886
Wale Ogunwale008163e2018-07-23 23:11:08 -07005887 AppWarnings getAppWarningsLocked() {
5888 return mAppWarnings;
5889 }
5890
Wale Ogunwale214f3482018-10-04 11:00:47 -07005891 Intent getHomeIntent() {
5892 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5893 intent.setComponent(mTopComponent);
5894 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5895 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5896 intent.addCategory(Intent.CATEGORY_HOME);
5897 }
5898 return intent;
5899 }
5900
Chilun2ef71f72018-11-16 17:57:15 +08005901 /**
5902 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5903 * activities.
5904 *
Chilun939b05c2020-02-19 14:50:59 +08005905 * @param preferredPackage Specify a preferred package name, otherwise use the package name
5906 * defined in config_secondaryHomePackage.
Chilun2ef71f72018-11-16 17:57:15 +08005907 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5908 */
5909 Intent getSecondaryHomeIntent(String preferredPackage) {
5910 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005911 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5912 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5913 if (preferredPackage == null || useSystemProvidedLauncher) {
Chilun939b05c2020-02-19 14:50:59 +08005914 // Using the package name stored in config if no preferred package name or forced.
5915 final String secondaryHomePackage = mContext.getResources().getString(
5916 com.android.internal.R.string.config_secondaryHomePackage);
5917 intent.setPackage(secondaryHomePackage);
Chilun2ef71f72018-11-16 17:57:15 +08005918 } else {
5919 intent.setPackage(preferredPackage);
5920 }
5921 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5922 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5923 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5924 }
5925 return intent;
5926 }
5927
Wale Ogunwale214f3482018-10-04 11:00:47 -07005928 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5929 if (info == null) return null;
5930 ApplicationInfo newInfo = new ApplicationInfo(info);
5931 newInfo.initForUser(userId);
5932 return newInfo;
5933 }
5934
Wale Ogunwale9c103022018-10-18 07:44:54 -07005935 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005936 if (uid == SYSTEM_UID) {
5937 // The system gets to run in any process. If there are multiple processes with the same
5938 // uid, just pick the first (this should never happen).
5939 final SparseArray<WindowProcessController> procs =
5940 mProcessNames.getMap().get(processName);
5941 if (procs == null) return null;
5942 final int procCount = procs.size();
5943 for (int i = 0; i < procCount; i++) {
5944 final int procUid = procs.keyAt(i);
5945 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5946 // Don't use an app process or different user process for system component.
5947 continue;
5948 }
5949 return procs.valueAt(i);
5950 }
5951 }
5952
5953 return mProcessNames.get(processName, uid);
5954 }
5955
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005956 WindowProcessController getProcessController(IApplicationThread thread) {
5957 if (thread == null) {
5958 return null;
5959 }
5960
5961 final IBinder threadBinder = thread.asBinder();
5962 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5963 for (int i = pmap.size()-1; i >= 0; i--) {
5964 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5965 for (int j = procs.size() - 1; j >= 0; j--) {
5966 final WindowProcessController proc = procs.valueAt(j);
5967 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5968 return proc;
5969 }
5970 }
5971 }
5972
5973 return null;
5974 }
5975
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005976 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005977 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005978 if (proc == null) return null;
5979 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5980 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005981 }
5982 return null;
5983 }
5984
Riddle Hsua0536432019-02-16 00:38:59 +08005985 int getUidState(int uid) {
5986 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005987 }
5988
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005989 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005990 // A uid is considered to be foreground if it has a visible non-toast window.
5991 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005992 }
5993
Ricky Wai96f5c352019-04-10 18:40:17 +01005994 boolean isDeviceOwner(int uid) {
5995 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005996 }
5997
Ricky Wai96f5c352019-04-10 18:40:17 +01005998 void setDeviceOwnerUid(int uid) {
5999 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006000 }
6001
Wale Ogunwale9de19442018-10-18 19:05:03 -07006002 /**
6003 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6004 * the whitelist
6005 */
6006 String getPendingTempWhitelistTagForUidLocked(int uid) {
6007 return mPendingTempWhitelist.get(uid);
6008 }
6009
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006010 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6011 if (true || Build.IS_USER) {
6012 return;
6013 }
6014
6015 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6016 StrictMode.allowThreadDiskWrites();
6017 try {
6018 File tracesDir = new File("/data/anr");
6019 File tracesFile = null;
6020 try {
6021 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6022
6023 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006024 String timeString =
6025 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6026 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006027 sb.append(": ");
6028 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6029 sb.append(" since ");
6030 sb.append(msg);
6031 FileOutputStream fos = new FileOutputStream(tracesFile);
6032 fos.write(sb.toString().getBytes());
6033 if (app == null) {
6034 fos.write("\n*** No application process!".getBytes());
6035 }
6036 fos.close();
6037 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6038 } catch (IOException e) {
6039 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6040 return;
6041 }
6042
6043 if (app != null && app.getPid() > 0) {
6044 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6045 firstPids.add(app.getPid());
6046 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6047 }
6048
6049 File lastTracesFile = null;
6050 File curTracesFile = null;
6051 for (int i=9; i>=0; i--) {
6052 String name = String.format(Locale.US, "slow%02d.txt", i);
6053 curTracesFile = new File(tracesDir, name);
6054 if (curTracesFile.exists()) {
6055 if (lastTracesFile != null) {
6056 curTracesFile.renameTo(lastTracesFile);
6057 } else {
6058 curTracesFile.delete();
6059 }
6060 }
6061 lastTracesFile = curTracesFile;
6062 }
6063 tracesFile.renameTo(curTracesFile);
6064 } finally {
6065 StrictMode.setThreadPolicy(oldPolicy);
6066 }
6067 }
6068
Michal Karpinskida34cd42019-04-02 19:46:52 +01006069 boolean isAssociatedCompanionApp(int userId, int uid) {
6070 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6071 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006072 return false;
6073 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006074 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006075 }
6076
Issei Suzuki734bc942019-06-05 13:59:52 +02006077 void notifySingleTaskDisplayEmpty(int displayId) {
6078 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6079 }
6080
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006081 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006082 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006083
6084
Wale Ogunwale98875612018-10-12 07:53:02 -07006085 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6086 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006087
Riddle Hsud93a6c42018-11-29 21:50:06 +08006088 H(Looper looper) {
6089 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006090 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006091
6092 @Override
6093 public void handleMessage(Message msg) {
6094 switch (msg.what) {
6095 case REPORT_TIME_TRACKER_MSG: {
6096 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6097 tracker.deliverResult(mContext);
6098 } break;
6099 }
6100 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006101 }
6102
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006103 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006104 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006105
6106 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006107 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006108 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006109
6110 @Override
6111 public void handleMessage(Message msg) {
6112 switch (msg.what) {
6113 case DISMISS_DIALOG_UI_MSG: {
6114 final Dialog d = (Dialog) msg.obj;
6115 d.dismiss();
6116 break;
6117 }
6118 }
6119 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006120 }
6121
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006122 final class LocalService extends ActivityTaskManagerInternal {
6123 @Override
6124 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006125 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006126 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006127 }
6128
6129 @Override
6130 public ComponentName getHomeActivityForUser(int userId) {
6131 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006132 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006133 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006134 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006135 }
6136 }
6137
6138 @Override
6139 public void onLocalVoiceInteractionStarted(IBinder activity,
6140 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6141 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006142 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006143 }
6144 }
6145
6146 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006147 public void notifySingleTaskDisplayDrawn(int displayId) {
6148 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6149 }
6150
6151 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006152 public void notifyAppTransitionFinished() {
6153 synchronized (mGlobalLock) {
6154 mStackSupervisor.notifyAppTransitionDone();
6155 }
6156 }
6157
6158 @Override
6159 public void notifyAppTransitionCancelled() {
6160 synchronized (mGlobalLock) {
6161 mStackSupervisor.notifyAppTransitionDone();
6162 }
6163 }
6164
6165 @Override
6166 public List<IBinder> getTopVisibleActivities() {
6167 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006168 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006169 }
6170 }
6171
6172 @Override
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00006173 public boolean hasResumedActivity(int uid) {
6174 synchronized (mGlobalLock) {
6175 final ArraySet<WindowProcessController> processes = mProcessMap.getProcesses(uid);
6176 for (int i = 0, n = processes.size(); i < n; i++) {
6177 final WindowProcessController process = processes.valueAt(i);
6178 if (process.hasResumedActivity()) {
6179 return true;
6180 }
6181 }
6182 }
6183 return false;
6184 }
6185
6186 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006187 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6188 int userId, Intent[] intents, Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006189 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006190 final String[] resolvedTypes = new String[intents.length];
6191
6192 // UID of the package on user userId.
6193 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6194 // packageUid may not be initialized.
6195 int packageUid = 0;
6196 final long ident = Binder.clearCallingIdentity();
6197
6198 try {
6199 for (int i = 0; i < intents.length; i++) {
6200 resolvedTypes[i] =
6201 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6202 }
6203
6204 packageUid = AppGlobals.getPackageManager().getPackageUid(
6205 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6206 } catch (RemoteException e) {
6207 // Shouldn't happen.
6208 } finally {
6209 Binder.restoreCallingIdentity(ident);
6210 }
6211
Riddle Hsu591bf612019-02-14 17:55:31 +08006212 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006213 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006214 intents, resolvedTypes, null /* resultTo */,
6215 SafeActivityOptions.fromBundle(bOptions), userId,
6216 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6217 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006218 }
6219
6220 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006221 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006222 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6223 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6224 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006225 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006226 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006227 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006228 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006229 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6230 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006231 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006232 }
6233 }
6234
6235 @Override
6236 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006237 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6238 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6239 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6240 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006241 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006242 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006243 synchronized (mGlobalLock) {
6244 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006245 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6246 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6247 reason, validateIncomingUser, originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006248 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006249 }
6250 }
6251
6252 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006253 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006254 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6255 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006256 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006257 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006258 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006259 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006260 false /*validateIncomingUser*/);
6261 }
6262
6263 @Override
lumark588a3e82018-07-20 18:53:54 +08006264 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006265 synchronized (mGlobalLock) {
6266
6267 // We might change the visibilities here, so prepare an empty app transition which
6268 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006269 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006270 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006271 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006272 return;
6273 }
Louis Chang677921f2019-12-06 16:44:24 +08006274 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006275 final boolean wasTransitionSet =
6276 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006277 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006278 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006279 }
Louis Chang149d5c82019-12-30 09:47:39 +08006280 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006281
6282 // If there was a transition set already we don't want to interfere with it as we
6283 // might be starting it too early.
6284 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006285 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006286 }
6287 }
6288 if (callback != null) {
6289 callback.run();
6290 }
6291 }
6292
6293 @Override
6294 public void notifyKeyguardTrustedChanged() {
6295 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006296 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006297 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006298 }
6299 }
6300 }
6301
6302 /**
6303 * Called after virtual display Id is updated by
6304 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6305 * {@param vrVr2dDisplayId}.
6306 */
6307 @Override
6308 public void setVr2dDisplayId(int vr2dDisplayId) {
6309 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6310 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006311 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006312 }
6313 }
6314
6315 @Override
6316 public void setFocusedActivity(IBinder token) {
6317 synchronized (mGlobalLock) {
6318 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6319 if (r == null) {
6320 throw new IllegalArgumentException(
6321 "setFocusedActivity: No activity record matching token=" + token);
6322 }
Louis Chang19443452018-10-09 12:10:21 +08006323 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006324 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006325 }
6326 }
6327 }
6328
6329 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006330 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006331 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006332 }
6333
6334 @Override
6335 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006336 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006337 }
6338
6339 @Override
6340 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006341 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006342 }
6343
6344 @Override
6345 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6346 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6347 }
6348
6349 @Override
6350 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006351 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006352 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006353
6354 @Override
6355 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6356 synchronized (mGlobalLock) {
6357 mActiveVoiceInteractionServiceComponent = component;
6358 }
6359 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006360
6361 @Override
Galia Peycheva480275a2020-03-18 17:33:42 +01006362 public void notifyDreamStateChanged(boolean dreaming) {
6363 synchronized (mGlobalLock) {
6364 mDreaming = dreaming;
6365 }
6366 }
6367
6368 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006369 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6370 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6371 return;
6372 }
6373 synchronized (mGlobalLock) {
6374 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6375 if (types == null) {
6376 if (uid < 0) {
6377 return;
6378 }
6379 types = new ArrayMap<>();
6380 mAllowAppSwitchUids.put(userId, types);
6381 }
6382 if (uid < 0) {
6383 types.remove(type);
6384 } else {
6385 types.put(type, uid);
6386 }
6387 }
6388 }
6389
6390 @Override
6391 public void onUserStopped(int userId) {
6392 synchronized (mGlobalLock) {
6393 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6394 mAllowAppSwitchUids.remove(userId);
6395 }
6396 }
6397
6398 @Override
6399 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6400 synchronized (mGlobalLock) {
6401 return ActivityTaskManagerService.this.isGetTasksAllowed(
6402 caller, callingPid, callingUid);
6403 }
6404 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006405
Riddle Hsua0536432019-02-16 00:38:59 +08006406 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006407 @Override
6408 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006409 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006410 mProcessNames.put(proc.mName, proc.mUid, proc);
6411 }
6412 }
6413
Riddle Hsua0536432019-02-16 00:38:59 +08006414 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006415 @Override
6416 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006417 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006418 mProcessNames.remove(name, uid);
6419 }
6420 }
6421
Riddle Hsua0536432019-02-16 00:38:59 +08006422 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006423 @Override
6424 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006425 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006426 if (proc == mHomeProcess) {
6427 mHomeProcess = null;
6428 }
6429 if (proc == mPreviousProcess) {
6430 mPreviousProcess = null;
6431 }
6432 }
6433 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006434
Riddle Hsua0536432019-02-16 00:38:59 +08006435 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006436 @Override
6437 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006438 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006439 return mTopProcessState;
6440 }
6441 }
6442
Riddle Hsua0536432019-02-16 00:38:59 +08006443 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006444 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006445 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006446 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006447 return proc == mHeavyWeightProcess;
6448 }
6449 }
6450
Riddle Hsua0536432019-02-16 00:38:59 +08006451 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006452 @Override
6453 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006454 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006455 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6456 }
6457 }
6458
6459 @Override
6460 public void finishHeavyWeightApp() {
6461 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006462 if (mHeavyWeightProcess != null) {
6463 mHeavyWeightProcess.finishActivities();
6464 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006465 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6466 mHeavyWeightProcess);
6467 }
6468 }
6469
Galia Peycheva480275a2020-03-18 17:33:42 +01006470 @Override
6471 public boolean isDreaming() {
6472 synchronized (mGlobalLock) {
6473 return mDreaming;
6474 }
6475 }
6476
Riddle Hsua0536432019-02-16 00:38:59 +08006477 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006478 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006479 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006480 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006481 return isSleepingLocked();
6482 }
6483 }
6484
6485 @Override
6486 public boolean isShuttingDown() {
6487 synchronized (mGlobalLock) {
6488 return mShuttingDown;
6489 }
6490 }
6491
6492 @Override
6493 public boolean shuttingDown(boolean booted, int timeout) {
6494 synchronized (mGlobalLock) {
6495 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006496 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006497 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006498 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006499 return mStackSupervisor.shutdownLocked(timeout);
6500 }
6501 }
6502
6503 @Override
6504 public void enableScreenAfterBoot(boolean booted) {
6505 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006506 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006507 mWindowManager.enableScreenAfterBoot();
6508 updateEventDispatchingLocked(booted);
6509 }
6510 }
6511
6512 @Override
6513 public boolean showStrictModeViolationDialog() {
6514 synchronized (mGlobalLock) {
6515 return mShowDialogs && !mSleeping && !mShuttingDown;
6516 }
6517 }
6518
6519 @Override
6520 public void showSystemReadyErrorDialogsIfNeeded() {
6521 synchronized (mGlobalLock) {
6522 try {
6523 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6524 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6525 + " data partition or your device will be unstable.");
6526 mUiHandler.post(() -> {
6527 if (mShowDialogs) {
6528 AlertDialog d = new BaseErrorDialog(mUiContext);
6529 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6530 d.setCancelable(false);
6531 d.setTitle(mUiContext.getText(R.string.android_system_label));
6532 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6533 d.setButton(DialogInterface.BUTTON_POSITIVE,
6534 mUiContext.getText(R.string.ok),
6535 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6536 d.show();
6537 }
6538 });
6539 }
6540 } catch (RemoteException e) {
6541 }
6542
6543 if (!Build.isBuildConsistent()) {
6544 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6545 mUiHandler.post(() -> {
6546 if (mShowDialogs) {
6547 AlertDialog d = new BaseErrorDialog(mUiContext);
6548 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6549 d.setCancelable(false);
6550 d.setTitle(mUiContext.getText(R.string.android_system_label));
6551 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6552 d.setButton(DialogInterface.BUTTON_POSITIVE,
6553 mUiContext.getText(R.string.ok),
6554 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6555 d.show();
6556 }
6557 });
6558 }
6559 }
6560 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006561
6562 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006563 public void onProcessMapped(int pid, WindowProcessController proc) {
6564 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006565 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006566 }
6567 }
6568
6569 @Override
6570 public void onProcessUnMapped(int pid) {
6571 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006572 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006573 }
6574 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006575
6576 @Override
6577 public void onPackageDataCleared(String name) {
6578 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006579 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006580 mAppWarnings.onPackageDataCleared(name);
6581 }
6582 }
6583
6584 @Override
6585 public void onPackageUninstalled(String name) {
6586 synchronized (mGlobalLock) {
6587 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006588 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006589 }
6590 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006591
6592 @Override
6593 public void onPackageAdded(String name, boolean replacing) {
6594 synchronized (mGlobalLock) {
6595 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6596 }
6597 }
6598
6599 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006600 public void onPackageReplaced(ApplicationInfo aInfo) {
6601 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006602 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006603 }
6604 }
6605
6606 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006607 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6608 synchronized (mGlobalLock) {
6609 return compatibilityInfoForPackageLocked(ai);
6610 }
6611 }
6612
Yunfan Chen75157d72018-07-27 14:47:21 +09006613 /**
6614 * Set the corresponding display information for the process global configuration. To be
6615 * called when we need to show IME on a different display.
6616 *
6617 * @param pid The process id associated with the IME window.
6618 * @param displayId The ID of the display showing the IME.
6619 */
6620 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006621 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006622 // Don't update process-level configuration for Multi-Client IME process since other
6623 // IMEs on other displays will also receive this configuration change due to IME
6624 // services use the same application config/context.
6625 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006626
Yunfan Chen75157d72018-07-27 14:47:21 +09006627 if (pid == MY_PID || pid < 0) {
6628 if (DEBUG_CONFIGURATION) {
6629 Slog.w(TAG,
6630 "Trying to update display configuration for system/invalid process.");
6631 }
6632 return;
6633 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006634 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006635 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006636 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006637 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006638 // Call might come when display is not yet added or has been removed.
6639 if (DEBUG_CONFIGURATION) {
6640 Slog.w(TAG, "Trying to update display configuration for non-existing "
6641 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006642 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006643 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006644 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006645 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006646 if (process == null) {
6647 if (DEBUG_CONFIGURATION) {
6648 Slog.w(TAG, "Trying to update display configuration for invalid "
6649 + "process, pid=" + pid);
6650 }
6651 return;
6652 }
lumarkddc77fb2019-06-27 22:22:23 +08006653 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006654 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006655 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006656 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006657
6658 @Override
6659 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006660 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006661 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006662 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006663 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006664 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006665 }
6666 }
6667 }
6668
6669 @Override
6670 public void clearPendingResultForActivity(IBinder activityToken,
6671 WeakReference<PendingIntentRecord> pir) {
6672 synchronized (mGlobalLock) {
6673 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6674 if (r != null && r.pendingResults != null) {
6675 r.pendingResults.remove(pir);
6676 }
6677 }
6678 }
6679
6680 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006681 public ActivityTokens getTopActivityForTask(int taskId) {
6682 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006683 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006684 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006685 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6686 + " Requested task not found");
6687 return null;
6688 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006689 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006690 if (activity == null) {
6691 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6692 + " Requested activity not found");
6693 return null;
6694 }
6695 if (!activity.attachedToProcess()) {
6696 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6697 + activity);
6698 return null;
6699 }
6700 return new ActivityTokens(activity.appToken, activity.assistToken,
6701 activity.app.getThread());
6702 }
6703 }
6704
6705 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006706 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006707 @Nullable String featureId, int callingUid, int userId, IBinder token,
6708 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6709 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006710 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006711 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6712 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006713 }
6714 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006715
6716 @Override
6717 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6718 synchronized (mGlobalLock) {
6719 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6720 if (r == null) {
6721 return null;
6722 }
6723 if (r.mServiceConnectionsHolder == null) {
6724 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6725 ActivityTaskManagerService.this, r);
6726 }
6727
6728 return r.mServiceConnectionsHolder;
6729 }
6730 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006731
6732 @Override
6733 public Intent getHomeIntent() {
6734 synchronized (mGlobalLock) {
6735 return ActivityTaskManagerService.this.getHomeIntent();
6736 }
6737 }
6738
6739 @Override
6740 public boolean startHomeActivity(int userId, String reason) {
6741 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006742 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006743 }
6744 }
6745
6746 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006747 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006748 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006749 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006750 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006751 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006752 }
Chilun8b1f1be2019-03-13 17:14:36 +08006753 }
6754
6755 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006756 public boolean startHomeOnAllDisplays(int userId, String reason) {
6757 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006758 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006759 }
6760 }
6761
Riddle Hsua0536432019-02-16 00:38:59 +08006762 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006763 @Override
6764 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006765 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006766 if (mFactoryTest == FACTORY_TEST_OFF) {
6767 return false;
6768 }
6769 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6770 && wpc.mName.equals(mTopComponent.getPackageName())) {
6771 return true;
6772 }
6773 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6774 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6775 }
6776 }
6777
6778 @Override
6779 public void updateTopComponentForFactoryTest() {
6780 synchronized (mGlobalLock) {
6781 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6782 return;
6783 }
6784 final ResolveInfo ri = mContext.getPackageManager()
6785 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6786 final CharSequence errorMsg;
6787 if (ri != null) {
6788 final ActivityInfo ai = ri.activityInfo;
6789 final ApplicationInfo app = ai.applicationInfo;
6790 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6791 mTopAction = Intent.ACTION_FACTORY_TEST;
6792 mTopData = null;
6793 mTopComponent = new ComponentName(app.packageName, ai.name);
6794 errorMsg = null;
6795 } else {
6796 errorMsg = mContext.getResources().getText(
6797 com.android.internal.R.string.factorytest_not_system);
6798 }
6799 } else {
6800 errorMsg = mContext.getResources().getText(
6801 com.android.internal.R.string.factorytest_no_action);
6802 }
6803 if (errorMsg == null) {
6804 return;
6805 }
6806
6807 mTopAction = null;
6808 mTopData = null;
6809 mTopComponent = null;
6810 mUiHandler.post(() -> {
6811 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6812 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006813 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006814 });
6815 }
6816 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006817
Riddle Hsua0536432019-02-16 00:38:59 +08006818 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006819 @Override
6820 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6821 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006822 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006823 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006824 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006825
6826 wpc.clearRecentTasks();
6827 wpc.clearActivities();
6828
6829 if (wpc.isInstrumenting()) {
6830 finishInstrumentationCallback.run();
6831 }
6832
Jorim Jaggid0752812018-10-16 16:07:20 +02006833 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006834 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006835 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006836 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006837 // If there was nothing to resume, and we are not already restarting
6838 // this process, but there is a visible activity that is hosted by the
6839 // process...then make sure all visible activities are running, taking
6840 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006841 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006842 !PRESERVE_WINDOWS);
6843 }
6844 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006845 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006846 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006847 }
6848 }
6849 }
6850
6851 @Override
6852 public void closeSystemDialogs(String reason) {
6853 enforceNotIsolatedCaller("closeSystemDialogs");
6854
6855 final int pid = Binder.getCallingPid();
6856 final int uid = Binder.getCallingUid();
6857 final long origId = Binder.clearCallingIdentity();
6858 try {
6859 synchronized (mGlobalLock) {
6860 // Only allow this from foreground processes, so that background
6861 // applications can't abuse it to prevent system UI from being shown.
6862 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006863 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006864 if (!proc.isPerceptible()) {
6865 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6866 + " from background process " + proc);
6867 return;
6868 }
6869 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006870 mWindowManager.closeSystemDialogs(reason);
6871
Louis Chang149d5c82019-12-30 09:47:39 +08006872 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006873 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006874 // Call into AM outside the synchronized block.
6875 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006876 } finally {
6877 Binder.restoreCallingIdentity(origId);
6878 }
6879 }
6880
6881 @Override
6882 public void cleanupDisabledPackageComponents(
6883 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6884 synchronized (mGlobalLock) {
6885 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006886 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006887 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006888 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006889 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006890 }
6891
6892 // Clean-up disabled tasks
6893 getRecentTasks().cleanupDisabledPackageTasksLocked(
6894 packageName, disabledClasses, userId);
6895 }
6896 }
6897
6898 @Override
6899 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6900 int userId) {
6901 synchronized (mGlobalLock) {
6902
6903 boolean didSomething =
6904 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006905 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006906 null, doit, evenPersistent, userId);
6907 return didSomething;
6908 }
6909 }
6910
6911 @Override
6912 public void resumeTopActivities(boolean scheduleIdle) {
6913 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006914 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006915 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006916 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006917 }
6918 }
6919 }
6920
Riddle Hsua0536432019-02-16 00:38:59 +08006921 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006922 @Override
6923 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006924 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006925 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6926 }
6927 }
6928
Riddle Hsua0536432019-02-16 00:38:59 +08006929 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006930 @Override
6931 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006932 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006933 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6934 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6935 }
6936 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006937 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006938 } finally {
6939 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6940 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006941 }
6942 }
6943
6944 @Override
6945 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6946 try {
6947 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6948 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6949 }
6950 } catch (RemoteException ex) {
6951 throw new SecurityException("Fail to check is caller a privileged app", ex);
6952 }
6953
6954 synchronized (mGlobalLock) {
6955 final long ident = Binder.clearCallingIdentity();
6956 try {
6957 if (mAmInternal.shouldConfirmCredentials(userId)) {
6958 if (mKeyguardController.isKeyguardLocked()) {
6959 // Showing launcher to avoid user entering credential twice.
6960 startHomeActivity(currentUserId, "notifyLockedProfile");
6961 }
Louis Chang149d5c82019-12-30 09:47:39 +08006962 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006963 }
6964 } finally {
6965 Binder.restoreCallingIdentity(ident);
6966 }
6967 }
6968 }
6969
6970 @Override
6971 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6972 mAmInternal.enforceCallingPermission(
6973 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6974
6975 synchronized (mGlobalLock) {
6976 final long ident = Binder.clearCallingIdentity();
6977 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006978 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6979 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006980 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006981 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6982 UserHandle.CURRENT);
6983 } finally {
6984 Binder.restoreCallingIdentity(ident);
6985 }
6986 }
6987 }
6988
6989 @Override
6990 public void writeActivitiesToProto(ProtoOutputStream proto) {
6991 synchronized (mGlobalLock) {
6992 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006993 mRootWindowContainer.dumpDebug(
6994 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006995 }
6996 }
6997
6998 @Override
6999 public void saveANRState(String reason) {
7000 synchronized (mGlobalLock) {
7001 final StringWriter sw = new StringWriter();
7002 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
7003 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
7004 if (reason != null) {
7005 pw.println(" Reason: " + reason);
7006 }
7007 pw.println();
7008 getActivityStartController().dump(pw, " ", null);
7009 pw.println();
7010 pw.println("-------------------------------------------------------------------------------");
7011 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7012 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7013 "" /* header */);
7014 pw.println();
7015 pw.close();
7016
7017 mLastANRState = sw.toString();
7018 }
7019 }
7020
7021 @Override
7022 public void clearSavedANRState() {
7023 synchronized (mGlobalLock) {
7024 mLastANRState = null;
7025 }
7026 }
7027
7028 @Override
7029 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7030 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7031 synchronized (mGlobalLock) {
7032 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7033 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7034 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7035 dumpLastANRLocked(pw);
7036 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7037 dumpLastANRTracesLocked(pw);
7038 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7039 dumpActivityStarterLocked(pw, dumpPackage);
7040 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7041 dumpActivityContainersLocked(pw);
7042 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7043 if (getRecentTasks() != null) {
7044 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7045 }
7046 }
7047 }
7048 }
7049
7050 @Override
7051 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7052 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7053 int wakefulness) {
7054 synchronized (mGlobalLock) {
7055 if (mHomeProcess != null && (dumpPackage == null
7056 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7057 if (needSep) {
7058 pw.println();
7059 needSep = false;
7060 }
7061 pw.println(" mHomeProcess: " + mHomeProcess);
7062 }
7063 if (mPreviousProcess != null && (dumpPackage == null
7064 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7065 if (needSep) {
7066 pw.println();
7067 needSep = false;
7068 }
7069 pw.println(" mPreviousProcess: " + mPreviousProcess);
7070 }
7071 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7072 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7073 StringBuilder sb = new StringBuilder(128);
7074 sb.append(" mPreviousProcessVisibleTime: ");
7075 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7076 pw.println(sb);
7077 }
7078 if (mHeavyWeightProcess != null && (dumpPackage == null
7079 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7080 if (needSep) {
7081 pw.println();
7082 needSep = false;
7083 }
7084 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7085 }
7086 if (dumpPackage == null) {
7087 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007088 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007089 }
7090 if (dumpAll) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007091 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7092 if (dumpPackage == null && topFocusedStack != null) {
7093 pw.println(" mConfigWillChange: " + topFocusedStack.mConfigWillChange);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007094 }
7095 if (mCompatModePackages.getPackages().size() > 0) {
7096 boolean printed = false;
7097 for (Map.Entry<String, Integer> entry
7098 : mCompatModePackages.getPackages().entrySet()) {
7099 String pkg = entry.getKey();
7100 int mode = entry.getValue();
7101 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7102 continue;
7103 }
7104 if (!printed) {
7105 pw.println(" mScreenCompatPackages:");
7106 printed = true;
7107 }
7108 pw.println(" " + pkg + ": " + mode);
7109 }
7110 }
7111 }
7112
7113 if (dumpPackage == null) {
7114 pw.println(" mWakefulness="
7115 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007116 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007117 if (mRunningVoice != null) {
7118 pw.println(" mRunningVoice=" + mRunningVoice);
7119 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7120 }
7121 pw.println(" mSleeping=" + mSleeping);
7122 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7123 pw.println(" mVrController=" + mVrController);
7124 }
7125 if (mCurAppTimeTracker != null) {
7126 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7127 }
7128 if (mAllowAppSwitchUids.size() > 0) {
7129 boolean printed = false;
7130 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7131 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7132 for (int j = 0; j < types.size(); j++) {
7133 if (dumpPackage == null ||
7134 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7135 if (needSep) {
7136 pw.println();
7137 needSep = false;
7138 }
7139 if (!printed) {
7140 pw.println(" mAllowAppSwitchUids:");
7141 printed = true;
7142 }
7143 pw.print(" User ");
7144 pw.print(mAllowAppSwitchUids.keyAt(i));
7145 pw.print(": Type ");
7146 pw.print(types.keyAt(j));
7147 pw.print(" = ");
7148 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7149 pw.println();
7150 }
7151 }
7152 }
7153 }
7154 if (dumpPackage == null) {
7155 if (mController != null) {
7156 pw.println(" mController=" + mController
7157 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7158 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007159 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7160 pw.println(" mLaunchingActivityWakeLock="
7161 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007162 }
7163
7164 return needSep;
7165 }
7166 }
7167
7168 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007169 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7170 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007171 synchronized (mGlobalLock) {
7172 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007173 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007174 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7175 if (topFocusedStack != null) {
7176 proto.write(CONFIG_WILL_CHANGE, topFocusedStack.mConfigWillChange);
7177 }
sanryhuang498e77e2018-12-06 14:57:01 +08007178 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7179 if (mRunningVoice != null) {
7180 final long vrToken = proto.start(
7181 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7182 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7183 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007184 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007185 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7186 proto.end(vrToken);
7187 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007188 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007189 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007190 if (mController != null) {
7191 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007192 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7193 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007194 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7195 proto.end(token);
7196 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007197 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7198 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007199 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007200 }
7201
7202 if (mHomeProcess != null && (dumpPackage == null
7203 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007204 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007205 }
7206
7207 if (mPreviousProcess != null && (dumpPackage == null
7208 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007209 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007210 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7211 }
7212
7213 if (mHeavyWeightProcess != null && (dumpPackage == null
7214 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007215 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007216 }
7217
7218 for (Map.Entry<String, Integer> entry
7219 : mCompatModePackages.getPackages().entrySet()) {
7220 String pkg = entry.getKey();
7221 int mode = entry.getValue();
7222 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7223 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7224 proto.write(PACKAGE, pkg);
7225 proto.write(MODE, mode);
7226 proto.end(compatToken);
7227 }
7228 }
7229
7230 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007231 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007232 }
7233
7234 }
7235 }
7236
7237 @Override
7238 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7239 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7240 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007241 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7242 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007243 }
7244
7245 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007246 public void dumpForOom(PrintWriter pw) {
7247 synchronized (mGlobalLock) {
7248 pw.println(" mHomeProcess: " + mHomeProcess);
7249 pw.println(" mPreviousProcess: " + mPreviousProcess);
7250 if (mHeavyWeightProcess != null) {
7251 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7252 }
7253 }
7254 }
7255
7256 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007257 public boolean canGcNow() {
7258 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007259 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007260 }
7261 }
7262
Riddle Hsua0536432019-02-16 00:38:59 +08007263 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007264 @Override
7265 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007266 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007267 if (mRootWindowContainer == null) {
7268 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007269 // oomadj after AMS created.
7270 return null;
7271 }
Louis Chang149d5c82019-12-30 09:47:39 +08007272 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007273 return top != null ? top.app : null;
7274 }
7275 }
7276
Riddle Hsua0536432019-02-16 00:38:59 +08007277 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007278 @Override
7279 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007280 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007281 if (mRootWindowContainer != null) {
7282 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007283 }
7284 }
7285 }
7286
7287 @Override
7288 public void scheduleDestroyAllActivities(String reason) {
7289 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007290 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007291 }
7292 }
7293
7294 @Override
7295 public void removeUser(int userId) {
7296 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007297 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007298 }
7299 }
7300
7301 @Override
7302 public boolean switchUser(int userId, UserState userState) {
7303 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007304 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007305 }
7306 }
7307
7308 @Override
7309 public void onHandleAppCrash(WindowProcessController wpc) {
7310 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007311 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007312 }
7313 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007314
7315 @Override
7316 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7317 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007318 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007319 }
7320 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007321
Riddle Hsua0536432019-02-16 00:38:59 +08007322 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007323 @Override
7324 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007325 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007326 }
7327
Riddle Hsua0536432019-02-16 00:38:59 +08007328 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007329 @Override
7330 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007331 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007332 }
7333
Riddle Hsua0536432019-02-16 00:38:59 +08007334 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007335 @Override
7336 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007337 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007338 }
7339
Riddle Hsua0536432019-02-16 00:38:59 +08007340 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007341 @Override
7342 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007343 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007344 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007345
7346 @Override
7347 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007348 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007349 mPendingTempWhitelist.put(uid, tag);
7350 }
7351 }
7352
7353 @Override
7354 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007355 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007356 mPendingTempWhitelist.remove(uid);
7357 }
7358 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007359
7360 @Override
7361 public boolean handleAppCrashInActivityController(String processName, int pid,
7362 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7363 Runnable killCrashingAppCallback) {
7364 synchronized (mGlobalLock) {
7365 if (mController == null) {
7366 return false;
7367 }
7368
7369 try {
7370 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7371 stackTrace)) {
7372 killCrashingAppCallback.run();
7373 return true;
7374 }
7375 } catch (RemoteException e) {
7376 mController = null;
7377 Watchdog.getInstance().setActivityController(null);
7378 }
7379 return false;
7380 }
7381 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007382
7383 @Override
7384 public void removeRecentTasksByPackageName(String packageName, int userId) {
7385 synchronized (mGlobalLock) {
7386 mRecentTasks.removeTasksByPackageName(packageName, userId);
7387 }
7388 }
7389
7390 @Override
7391 public void cleanupRecentTasksForUser(int userId) {
7392 synchronized (mGlobalLock) {
7393 mRecentTasks.cleanupLocked(userId);
7394 }
7395 }
7396
7397 @Override
7398 public void loadRecentTasksForUser(int userId) {
7399 synchronized (mGlobalLock) {
7400 mRecentTasks.loadUserRecentsLocked(userId);
7401 }
7402 }
7403
7404 @Override
7405 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7406 synchronized (mGlobalLock) {
7407 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7408 }
7409 }
7410
7411 @Override
7412 public void flushRecentTasks() {
7413 mRecentTasks.flush();
7414 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007415
7416 @Override
7417 public WindowProcessController getHomeProcess() {
7418 synchronized (mGlobalLock) {
7419 return mHomeProcess;
7420 }
7421 }
7422
7423 @Override
7424 public WindowProcessController getPreviousProcess() {
7425 synchronized (mGlobalLock) {
7426 return mPreviousProcess;
7427 }
7428 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007429
7430 @Override
7431 public void clearLockedTasks(String reason) {
7432 synchronized (mGlobalLock) {
7433 getLockTaskController().clearLockedTasks(reason);
7434 }
7435 }
7436
7437 @Override
7438 public void updateUserConfiguration() {
7439 synchronized (mGlobalLock) {
7440 final Configuration configuration = new Configuration(getGlobalConfiguration());
7441 final int currentUserId = mAmInternal.getCurrentUserId();
7442 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7443 configuration, currentUserId, Settings.System.canWrite(mContext));
7444 updateConfigurationLocked(configuration, null /* starting */,
7445 false /* initLocale */, false /* persistent */, currentUserId,
7446 false /* deferResume */);
7447 }
7448 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007449
7450 @Override
7451 public boolean canShowErrorDialogs() {
7452 synchronized (mGlobalLock) {
7453 return mShowDialogs && !mSleeping && !mShuttingDown
7454 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7455 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7456 mAmInternal.getCurrentUserId())
7457 && !(UserManager.isDeviceInDemoMode(mContext)
7458 && mAmInternal.getCurrentUser().isDemo());
7459 }
7460 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007461
7462 @Override
7463 public void setProfileApp(String profileApp) {
7464 synchronized (mGlobalLock) {
7465 mProfileApp = profileApp;
7466 }
7467 }
7468
7469 @Override
7470 public void setProfileProc(WindowProcessController wpc) {
7471 synchronized (mGlobalLock) {
7472 mProfileProc = wpc;
7473 }
7474 }
7475
7476 @Override
7477 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7478 synchronized (mGlobalLock) {
7479 mProfilerInfo = profilerInfo;
7480 }
7481 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007482
7483 @Override
7484 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7485 synchronized (mGlobalLock) {
7486 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7487 }
7488 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007489
7490 @Override
Zak Cohen84b43182020-03-09 14:36:01 -07007491 public ActivityManager.TaskSnapshot getTaskSnapshotBlocking(
7492 int taskId, boolean isLowResolution) {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08007493 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution,
Zak Cohen84b43182020-03-09 14:36:01 -07007494 true /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007495 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007496
7497 @Override
7498 public boolean isUidForeground(int uid) {
7499 synchronized (mGlobalLock) {
7500 return ActivityTaskManagerService.this.isUidForeground(uid);
7501 }
7502 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007503
7504 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007505 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007506 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007507 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007508 }
7509 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007510
7511 @Override
7512 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007513 // Translate package names into UIDs
7514 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007515 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007516 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7517 if (uid >= 0) {
7518 result.add(uid);
7519 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007520 }
7521 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007522 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007523 }
7524 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007525 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007526}