blob: 5992ff74dfa20b719281158eacda181e35d04b08 [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;
Sergey Nikolaienkov30c947d2020-04-15 19:55:48 +020045import static android.content.pm.PackageManager.FEATURE_CANT_SAVE_STATE;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Sergey Nikolaienkov30c947d2020-04-15 19:55:48 +020047import static android.content.pm.PackageManager.FEATURE_LEANBACK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080055import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070067
Yunfan Chen79b96062018-10-17 12:45:23 -070068import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
69import static com.android.server.am.ActivityManagerService.MY_PID;
70import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
71import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwalef342f062020-01-27 07:34:13 -080072import static com.android.server.am.ActivityManagerServiceDumpActivitiesProto.ROOT_WINDOW_CONTAINER;
Wale Ogunwale31913b52018-10-13 08:29:31 -070073import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
86import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Jeff Changd136e772019-11-05 20:33:52 +080087import static com.android.server.am.EventLogTags.writeBootProgressEnableScreen;
88import static com.android.server.am.EventLogTags.writeConfigurationChanged;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070089import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
90import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070092import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
93import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
94import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
112import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
116import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800117import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
118import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700119import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
120import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Louis Chang149d5c82019-12-30 09:47:39 +0800121import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_ONLY;
122import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
Louis Changcdec0802019-11-11 11:45:07 +0800123import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK;
124import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT;
125import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
Louis Changa009c762020-02-26 11:21:31 +0800126import static com.android.server.wm.WindowContainer.POSITION_TOP;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700127
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700128import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800129import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700130import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700131import android.annotation.Nullable;
132import android.annotation.UserIdInt;
133import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700134import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700135import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.ActivityOptions;
137import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700138import android.app.ActivityThread;
139import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100141import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700142import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700143import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700144import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700145import android.app.IApplicationThread;
146import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700147import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400148import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700149import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700150import android.app.Notification;
151import android.app.NotificationManager;
152import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.PictureInPictureParams;
154import android.app.ProfilerInfo;
155import android.app.RemoteAction;
156import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700157import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700158import android.app.admin.DevicePolicyCache;
159import android.app.assist.AssistContent;
160import android.app.assist.AssistStructure;
jorgegil@google.com06bc3232019-10-31 14:51:22 -0700161import android.app.servertransaction.ClientTransaction;
162import android.app.servertransaction.EnterPipRequestedItem;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700163import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700164import android.content.ActivityNotFoundException;
165import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700166import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700167import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700168import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700169import android.content.IIntentSender;
170import android.content.Intent;
171import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700172import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900173import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700174import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700176import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700177import android.content.pm.ParceledListSlice;
178import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700179import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700180import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700181import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700182import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700183import android.graphics.Bitmap;
184import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700185import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700187import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700189import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700190import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700191import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700192import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700193import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700194import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700195import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800196import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700197import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700200import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100201import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700204import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700205import android.os.SystemClock;
206import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700207import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700208import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700210import android.os.UserManager;
211import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700212import android.os.storage.IStorageManager;
213import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700214import android.provider.Settings;
Galia Peycheva6861e912019-08-21 10:20:23 +0200215import android.service.dreams.DreamActivity;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700216import android.service.voice.IVoiceInteractionSession;
217import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900218import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700219import android.telecom.TelecomManager;
220import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100221import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700223import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700224import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700225import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700226import android.util.SparseArray;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700227import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700228import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700229import android.view.IRecentsAnimationRunner;
230import android.view.RemoteAnimationAdapter;
231import android.view.RemoteAnimationDefinition;
Louis Changa009c762020-02-26 11:21:31 +0800232import android.view.WindowManager;
Wale Ogunwale568f9f412020-03-21 22:27:35 -0700233import android.window.IWindowOrganizerController;
Wale Ogunwale57946582020-03-21 14:29:07 -0700234import android.window.WindowContainerTransaction;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700235
Evan Rosky4505b352018-09-06 11:20:40 -0700236import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700237import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.app.AssistUtils;
239import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700240import com.android.internal.app.ProcessMap;
Wale Ogunwale53783742018-09-16 10:21:51 -0700241import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
242import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.os.TransferPipe;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700244import com.android.internal.policy.IKeyguardDismissCallback;
245import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700246import com.android.internal.util.ArrayUtils;
247import com.android.internal.util.FastPrintWriter;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800248import com.android.internal.util.FrameworkStatsLog;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800249import com.android.internal.util.function.pooled.PooledConsumer;
250import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700251import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700252import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700253import com.android.server.LocalServices;
254import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700255import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800256import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700257import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700258import com.android.server.am.ActivityManagerService;
Wale Ogunwale59507092018-10-29 09:00:30 -0700259import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
260import com.android.server.am.AppTimeTracker;
261import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700262import com.android.server.am.PendingIntentController;
263import com.android.server.am.PendingIntentRecord;
264import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700265import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700266import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700267import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800268import com.android.server.policy.PermissionPolicyInternal;
Jeff Sharkey307ea7a2020-04-13 10:24:49 -0600269import com.android.server.uri.NeededUriGrants;
Evan Rosky4505b352018-09-06 11:20:40 -0700270import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700278import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700279import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700280import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800281import java.lang.annotation.ElementType;
282import java.lang.annotation.Retention;
283import java.lang.annotation.RetentionPolicy;
284import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700285import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700287import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700288import java.util.Arrays;
Jeff Sharkey8b0cff72020-03-09 15:49:01 -0600289import java.util.Collection;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700290import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400291import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700292import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700293import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700294import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700295import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000296import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700297import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700298
299/**
300 * System service for managing activities and their containers (task, stacks, displays,... ).
301 *
302 * {@hide}
303 */
304public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700305 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800306 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000307 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700308 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
309 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
310 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
311 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700312 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700313
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700314 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700315 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700316 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700317 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100318 // How long we permit background activity starts after an activity in the process
319 // started or finished.
320 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700321
Wale Ogunwale98875612018-10-12 07:53:02 -0700322 /** Used to indicate that an app transition should be animated. */
323 static final boolean ANIMATE = true;
324
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700325 /** Hardware-reported OpenGLES version. */
326 final int GL_ES_VERSION;
327
Wale Ogunwale31913b52018-10-13 08:29:31 -0700328 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
329 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
330 public static final String DUMP_LASTANR_CMD = "lastanr" ;
331 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
332 public static final String DUMP_STARTER_CMD = "starter" ;
333 public static final String DUMP_CONTAINERS_CMD = "containers" ;
334 public static final String DUMP_RECENTS_CMD = "recents" ;
335 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
336
Wale Ogunwale64258362018-10-16 15:13:37 -0700337 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
338 public static final int RELAUNCH_REASON_NONE = 0;
339 /** This activity is being relaunched due to windowing mode change. */
340 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
341 /** This activity is being relaunched due to a free-resize operation. */
342 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
343
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700344 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700345
Wale Ogunwalef6733932018-06-27 05:14:34 -0700346 /**
347 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
348 * change at runtime. Use mContext for non-UI purposes.
349 */
350 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700351 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700352 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700353 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700354 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700355 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700356 private PackageManagerInternal mPmInternal;
Darryl L Johnsona0982222020-02-18 18:21:51 -0800357 /** The cached sys ui service component name from package manager. */
358 private ComponentName mSysUiServiceComponent;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800359 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800360 @VisibleForTesting
361 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700362 PowerManagerInternal mPowerManagerInternal;
363 private UsageStatsManagerInternal mUsageStatsInternal;
364
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700365 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700366 IntentFirewall mIntentFirewall;
367
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700368 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800369 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800370 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700371 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800372 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
373 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
374 *
375 * @see WindowManagerThreadPriorityBooster
376 */
377 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700378 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800379 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700380 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700381 private UserManagerService mUserManager;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800382 private AppOpsManager mAppOpsManager;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700383 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800384 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700385 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700386 /** All processes currently running that might have a window organized by name. */
387 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100388 /** All processes we currently have running mapped by pid and uid */
389 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700390 /** This is the process holding what we currently consider to be the "home" activity. */
391 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700392 /** The currently running heavy-weight process, if any. */
393 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700394 boolean mHasHeavyWeightFeature;
Sergey Nikolaienkov30c947d2020-04-15 19:55:48 +0200395 boolean mHasLeanbackFeature;
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) {
Sergey Nikolaienkov30c947d2020-04-15 19:55:48 +0200737 final PackageManager pm = mContext.getPackageManager();
738 mHasHeavyWeightFeature = pm.hasSystemFeature(FEATURE_CANT_SAVE_STATE);
739 mHasLeanbackFeature = pm.hasSystemFeature(FEATURE_LEANBACK);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700740 mAssistUtils = new AssistUtils(mContext);
741 mVrController.onSystemReady();
742 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700743 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700744 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700745 }
746
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700747 public void onInitPowerManagement() {
748 synchronized (mGlobalLock) {
749 mStackSupervisor.initPowerManagement();
750 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
751 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
752 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
753 mVoiceWakeLock.setReferenceCounted(false);
754 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700755 }
756
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700757 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700758 mFontScaleSettingObserver = new FontScaleSettingObserver();
759 }
760
Wale Ogunwale59507092018-10-29 09:00:30 -0700761 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700762 final boolean freeformWindowManagement =
763 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
764 || Settings.Global.getInt(
765 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
766
767 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
768 final boolean supportsPictureInPicture = supportsMultiWindow &&
769 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
770 final boolean supportsSplitScreenMultiWindow =
771 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
772 final boolean supportsMultiDisplay = mContext.getPackageManager()
773 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700774 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
775 final boolean forceResizable = Settings.Global.getInt(
776 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700777 final boolean sizeCompatFreeform = Settings.Global.getInt(
778 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700779
780 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900781 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700782
783 final Configuration configuration = new Configuration();
784 Settings.System.getConfiguration(resolver, configuration);
785 if (forceRtl) {
786 // This will take care of setting the correct layout direction flags
787 configuration.setLayoutDirection(configuration.locale);
788 }
789
790 synchronized (mGlobalLock) {
791 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700792 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700793 final boolean multiWindowFormEnabled = freeformWindowManagement
794 || supportsSplitScreenMultiWindow
795 || supportsPictureInPicture
796 || supportsMultiDisplay;
797 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
798 mSupportsMultiWindow = true;
799 mSupportsFreeformWindowManagement = freeformWindowManagement;
800 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
801 mSupportsPictureInPicture = supportsPictureInPicture;
802 mSupportsMultiDisplay = supportsMultiDisplay;
803 } else {
804 mSupportsMultiWindow = false;
805 mSupportsFreeformWindowManagement = false;
806 mSupportsSplitScreenMultiWindow = false;
807 mSupportsPictureInPicture = false;
808 mSupportsMultiDisplay = false;
809 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700810 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700811 // This happens before any activities are started, so we can change global configuration
812 // in-place.
813 updateConfigurationLocked(configuration, null, true);
814 final Configuration globalConfig = getGlobalConfiguration();
815 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
816
817 // Load resources only after the current configuration has been set.
818 final Resources res = mContext.getResources();
819 mThumbnailWidth = res.getDimensionPixelSize(
820 com.android.internal.R.dimen.thumbnail_width);
821 mThumbnailHeight = res.getDimensionPixelSize(
822 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700823 }
824 }
825
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800826 public WindowManagerGlobalLock getGlobalLock() {
827 return mGlobalLock;
828 }
829
Yunfan Chen585f2932019-01-29 16:04:45 +0900830 /** For test purpose only. */
831 @VisibleForTesting
832 public ActivityTaskManagerInternal getAtmInternal() {
833 return mInternal;
834 }
835
Riddle Hsud93a6c42018-11-29 21:50:06 +0800836 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
837 Looper looper) {
838 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700839 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700840 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700841 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800842 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700843 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700844 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700845 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700846
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700847 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700848 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700849 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700850 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700851 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700852 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700853 mKeyguardController = mStackSupervisor.getKeyguardController();
854 }
855
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700856 public void onActivityManagerInternalAdded() {
857 synchronized (mGlobalLock) {
858 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
859 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
860 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700861 }
862
Yunfan Chen75157d72018-07-27 14:47:21 +0900863 int increaseConfigurationSeqLocked() {
864 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
865 return mConfigurationSeq;
866 }
867
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700868 protected ActivityStackSupervisor createStackSupervisor() {
869 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
870 supervisor.initialize();
871 return supervisor;
872 }
873
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800874 protected AppWarnings createAppWarnings(
875 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
876 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
877 }
878
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700879 public void setWindowManager(WindowManagerService wm) {
880 synchronized (mGlobalLock) {
881 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800882 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800883 mTempConfig.setToDefaults();
884 mTempConfig.setLocales(LocaleList.getDefault());
885 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800886 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700887 mLockTaskController.setWindowManager(wm);
888 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800889 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700890 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700891 }
892
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700893 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
894 synchronized (mGlobalLock) {
895 mUsageStatsInternal = usageStatsManager;
896 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700897 }
898
Wale Ogunwalef6733932018-06-27 05:14:34 -0700899 UserManagerService getUserManager() {
900 if (mUserManager == null) {
901 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
902 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
903 }
904 return mUserManager;
905 }
906
Philip P. Moltmannee295092020-02-10 08:46:26 -0800907 AppOpsManager getAppOpsManager() {
908 if (mAppOpsManager == null) {
909 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Wale Ogunwalef6733932018-06-27 05:14:34 -0700910 }
Philip P. Moltmannee295092020-02-10 08:46:26 -0800911 return mAppOpsManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700912 }
913
914 boolean hasUserRestriction(String restriction, int userId) {
915 return getUserManager().hasUserRestriction(restriction, userId);
916 }
917
Michal Karpinski15486842019-04-25 17:33:42 +0100918 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
Philip P. Moltmannee295092020-02-10 08:46:26 -0800919 final int mode = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
920 callingUid, callingPackage, /* featureId */ null, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100921 if (mode == AppOpsManager.MODE_DEFAULT) {
922 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
923 == PERMISSION_GRANTED;
924 }
925 return mode == AppOpsManager.MODE_ALLOWED;
926 }
927
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700928 @VisibleForTesting
929 protected void setRecentTasks(RecentTasks recentTasks) {
930 mRecentTasks = recentTasks;
931 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700932 }
933
934 RecentTasks getRecentTasks() {
935 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700936 }
937
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700938 ClientLifecycleManager getLifecycleManager() {
939 return mLifecycleManager;
940 }
941
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700942 ActivityStartController getActivityStartController() {
943 return mActivityStartController;
944 }
945
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700946 TaskChangeNotificationController getTaskChangeNotificationController() {
947 return mTaskChangeNotificationController;
948 }
949
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700950 LockTaskController getLockTaskController() {
951 return mLockTaskController;
952 }
953
Yunfan Chen75157d72018-07-27 14:47:21 +0900954 /**
955 * Return the global configuration used by the process corresponding to the input pid. This is
956 * usually the global configuration with some overrides specific to that process.
957 */
958 Configuration getGlobalConfigurationForCallingPid() {
959 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800960 return getGlobalConfigurationForPid(pid);
961 }
962
963 /**
964 * Return the global configuration used by the process corresponding to the given pid.
965 */
966 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900967 if (pid == MY_PID || pid < 0) {
968 return getGlobalConfiguration();
969 }
970 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100971 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900972 return app != null ? app.getConfiguration() : getGlobalConfiguration();
973 }
974 }
975
976 /**
977 * Return the device configuration info used by the process corresponding to the input pid.
978 * The value is consistent with the global configuration for the process.
979 */
980 @Override
981 public ConfigurationInfo getDeviceConfigurationInfo() {
982 ConfigurationInfo config = new ConfigurationInfo();
983 synchronized (mGlobalLock) {
984 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
985 config.reqTouchScreen = globalConfig.touchscreen;
986 config.reqKeyboardType = globalConfig.keyboard;
987 config.reqNavigation = globalConfig.navigation;
988 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
989 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
990 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
991 }
992 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
993 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
994 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
995 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700996 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900997 }
998 return config;
999 }
1000
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001001 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -07001002 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001003 }
1004
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001005 public static final class Lifecycle extends SystemService {
1006 private final ActivityTaskManagerService mService;
1007
1008 public Lifecycle(Context context) {
1009 super(context);
1010 mService = new ActivityTaskManagerService(context);
1011 }
1012
1013 @Override
1014 public void onStart() {
1015 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001016 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001017 }
1018
Garfield Tan891146c2018-10-09 12:14:00 -07001019 @Override
1020 public void onUnlockUser(int userId) {
1021 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001022 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001023 }
1024 }
1025
1026 @Override
1027 public void onCleanupUser(int userId) {
1028 synchronized (mService.getGlobalLock()) {
1029 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1030 }
1031 }
1032
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001033 public ActivityTaskManagerService getService() {
1034 return mService;
1035 }
1036 }
1037
1038 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001039 public final int startActivity(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001040 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1041 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1042 Bundle bOptions) {
1043 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1044 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001045 UserHandle.getCallingUserId());
1046 }
1047
1048 @Override
1049 public final int startActivities(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001050 String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
1051 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001052 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001053 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001054 enforceNotIsolatedCaller(reason);
1055 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001056 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001057 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001058 callingFeatureId, intents, resolvedTypes, resultTo,
1059 SafeActivityOptions.fromBundle(bOptions), userId, reason,
1060 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001061 }
1062
1063 @Override
1064 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001065 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1066 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1067 Bundle bOptions, int userId) {
1068 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1069 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001070 true /*validateIncomingUser*/);
1071 }
1072
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001073 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001074 @Nullable String callingFeatureId, Intent intent, String resolvedType,
1075 IBinder resultTo, String resultWho, int requestCode, int startFlags,
1076 ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001077 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001078 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001079
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001080 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001081 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1082
1083 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001084 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001085 .setCaller(caller)
1086 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001087 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001088 .setResolvedType(resolvedType)
1089 .setResultTo(resultTo)
1090 .setResultWho(resultWho)
1091 .setRequestCode(requestCode)
1092 .setStartFlags(startFlags)
1093 .setProfilerInfo(profilerInfo)
1094 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001095 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001096 .execute();
1097
1098 }
1099
1100 @Override
1101 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1102 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001103 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1104 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001105 // Refuse possible leaked file descriptors
1106 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1107 throw new IllegalArgumentException("File descriptors passed in Intent");
1108 }
1109
1110 if (!(target instanceof PendingIntentRecord)) {
1111 throw new IllegalArgumentException("Bad PendingIntent object");
1112 }
1113
1114 PendingIntentRecord pir = (PendingIntentRecord)target;
1115
1116 synchronized (mGlobalLock) {
1117 // If this is coming from the currently resumed activity, it is
1118 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001119 final ActivityStack stack = getTopDisplayFocusedStack();
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001120 if (stack != null && stack.mResumedActivity != null
1121 && stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001122 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001123 }
1124 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001125 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001126 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001127 }
1128
1129 @Override
1130 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1131 Bundle bOptions) {
1132 // Refuse possible leaked file descriptors
1133 if (intent != null && intent.hasFileDescriptors()) {
1134 throw new IllegalArgumentException("File descriptors passed in Intent");
1135 }
1136 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1137
1138 synchronized (mGlobalLock) {
1139 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1140 if (r == null) {
1141 SafeActivityOptions.abort(options);
1142 return false;
1143 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001144 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001145 // The caller is not running... d'oh!
1146 SafeActivityOptions.abort(options);
1147 return false;
1148 }
1149 intent = new Intent(intent);
1150 // The caller is not allowed to change the data.
1151 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1152 // And we are resetting to find the next component...
1153 intent.setComponent(null);
1154
1155 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1156
1157 ActivityInfo aInfo = null;
1158 try {
1159 List<ResolveInfo> resolves =
1160 AppGlobals.getPackageManager().queryIntentActivities(
1161 intent, r.resolvedType,
1162 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1163 UserHandle.getCallingUserId()).getList();
1164
1165 // Look for the original activity in the list...
1166 final int N = resolves != null ? resolves.size() : 0;
1167 for (int i=0; i<N; i++) {
1168 ResolveInfo rInfo = resolves.get(i);
1169 if (rInfo.activityInfo.packageName.equals(r.packageName)
1170 && rInfo.activityInfo.name.equals(r.info.name)) {
1171 // We found the current one... the next matching is
1172 // after it.
1173 i++;
1174 if (i<N) {
1175 aInfo = resolves.get(i).activityInfo;
1176 }
1177 if (debug) {
1178 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1179 + "/" + r.info.name);
1180 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1181 ? "null" : aInfo.packageName + "/" + aInfo.name));
1182 }
1183 break;
1184 }
1185 }
1186 } catch (RemoteException e) {
1187 }
1188
1189 if (aInfo == null) {
1190 // Nobody who is next!
1191 SafeActivityOptions.abort(options);
1192 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1193 return false;
1194 }
1195
1196 intent.setComponent(new ComponentName(
1197 aInfo.applicationInfo.packageName, aInfo.name));
1198 intent.setFlags(intent.getFlags()&~(
1199 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1200 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1201 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1202 FLAG_ACTIVITY_NEW_TASK));
1203
1204 // Okay now we need to start the new activity, replacing the currently running activity.
1205 // This is a little tricky because we want to start the new one as if the current one is
1206 // finished, but not finish the current one first so that there is no flicker.
1207 // And thus...
1208 final boolean wasFinishing = r.finishing;
1209 r.finishing = true;
1210
1211 // Propagate reply information over to the new activity.
1212 final ActivityRecord resultTo = r.resultTo;
1213 final String resultWho = r.resultWho;
1214 final int requestCode = r.requestCode;
1215 r.resultTo = null;
1216 if (resultTo != null) {
1217 resultTo.removeResultsLocked(r, resultWho, requestCode);
1218 }
1219
1220 final long origId = Binder.clearCallingIdentity();
1221 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001222 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001223 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001224 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001225 .setResolvedType(r.resolvedType)
1226 .setActivityInfo(aInfo)
1227 .setResultTo(resultTo != null ? resultTo.appToken : null)
1228 .setResultWho(resultWho)
1229 .setRequestCode(requestCode)
1230 .setCallingPid(-1)
1231 .setCallingUid(r.launchedFromUid)
1232 .setCallingPackage(r.launchedFromPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001233 .setCallingFeatureId(r.launchedFromFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001234 .setRealCallingPid(-1)
1235 .setRealCallingUid(r.launchedFromUid)
1236 .setActivityOptions(options)
1237 .execute();
1238 Binder.restoreCallingIdentity(origId);
1239
1240 r.finishing = wasFinishing;
1241 if (res != ActivityManager.START_SUCCESS) {
1242 return false;
1243 }
1244 return true;
1245 }
1246 }
1247
Galia Peychevaed401cc2020-03-19 20:28:09 +01001248 private void enforceCallerIsDream(String callerPackageName) {
Galia Peycheva52e89222020-02-18 23:41:43 +01001249 final long origId = Binder.clearCallingIdentity();
Galia Peychevaed401cc2020-03-19 20:28:09 +01001250 try {
1251 if (!ActivityRecord.canLaunchDreamActivity(callerPackageName)) {
1252 throw new SecurityException("The dream activity can be started only when the device"
1253 + " is dreaming and only by the active dream package.");
1254 }
1255 } finally {
1256 Binder.restoreCallingIdentity(origId);
Galia Peycheva52e89222020-02-18 23:41:43 +01001257 }
Galia Peychevaed401cc2020-03-19 20:28:09 +01001258 }
1259
1260 @Override
1261 public boolean startDreamActivity(@NonNull Intent intent) {
1262 assertPackageMatchesCallingUid(intent.getPackage());
1263 enforceCallerIsDream(intent.getPackage());
Galia Peycheva52e89222020-02-18 23:41:43 +01001264
Galia Peycheva6861e912019-08-21 10:20:23 +02001265 final ActivityInfo a = new ActivityInfo();
1266 a.theme = com.android.internal.R.style.Theme_Dream;
1267 a.exported = true;
1268 a.name = DreamActivity.class.getName();
Galia Peycheva6861e912019-08-21 10:20:23 +02001269 a.enabled = true;
1270 a.launchMode = ActivityInfo.LAUNCH_SINGLE_INSTANCE;
Galia Peycheva6861e912019-08-21 10:20:23 +02001271 a.persistableMode = ActivityInfo.PERSIST_NEVER;
1272 a.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1273 a.colorMode = ActivityInfo.COLOR_MODE_DEFAULT;
1274 a.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1275
Galia Peycheva45f48d32020-02-20 15:39:10 +01001276 final ActivityOptions options = ActivityOptions.makeBasic();
1277 options.setLaunchActivityType(ACTIVITY_TYPE_DREAM);
1278
Galia Peychevaed401cc2020-03-19 20:28:09 +01001279 synchronized (mGlobalLock) {
1280 final WindowProcessController process = mProcessMap.getProcess(Binder.getCallingPid());
1281
1282 a.packageName = process.mInfo.packageName;
1283 a.applicationInfo = process.mInfo;
1284 a.processName = process.mInfo.processName;
1285 a.uiOptions = process.mInfo.uiOptions;
1286 a.taskAffinity = "android:" + a.packageName + "/dream";
1287
1288 final int callingUid = Binder.getCallingUid();
1289 final int callingPid = Binder.getCallingPid();
1290
1291 final long origId = Binder.clearCallingIdentity();
1292 try {
1293 getActivityStartController().obtainStarter(intent, "dream")
1294 .setCallingUid(callingUid)
1295 .setCallingPid(callingPid)
1296 .setActivityInfo(a)
1297 .setActivityOptions(options.toBundle())
1298 // To start the dream from background, we need to start it from a persistent
1299 // system process. Here we set the real calling uid to the system server uid
1300 .setRealCallingUid(Binder.getCallingUid())
1301 .setAllowBackgroundActivityStart(true)
1302 .execute();
1303 return true;
1304 } finally {
1305 Binder.restoreCallingIdentity(origId);
1306 }
Galia Peycheva6861e912019-08-21 10:20:23 +02001307 }
1308 }
1309
1310 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001311 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001312 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1313 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1314 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001315 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001316 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001317 enforceNotIsolatedCaller("startActivityAndWait");
1318 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1319 userId, "startActivityAndWait");
1320 // TODO: Switch to user app stacks here.
1321 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1322 .setCaller(caller)
1323 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001324 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001325 .setResolvedType(resolvedType)
1326 .setResultTo(resultTo)
1327 .setResultWho(resultWho)
1328 .setRequestCode(requestCode)
1329 .setStartFlags(startFlags)
1330 .setActivityOptions(bOptions)
1331 .setUserId(userId)
1332 .setProfilerInfo(profilerInfo)
1333 .setWaitResult(res)
1334 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001335 return res;
1336 }
1337
1338 @Override
1339 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001340 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1341 String resultWho, int requestCode, int startFlags, Configuration config,
1342 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001343 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001344 enforceNotIsolatedCaller("startActivityWithConfig");
1345 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1346 "startActivityWithConfig");
1347 // TODO: Switch to user app stacks here.
1348 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1349 .setCaller(caller)
1350 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001351 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001352 .setResolvedType(resolvedType)
1353 .setResultTo(resultTo)
1354 .setResultWho(resultWho)
1355 .setRequestCode(requestCode)
1356 .setStartFlags(startFlags)
1357 .setGlobalConfiguration(config)
1358 .setActivityOptions(bOptions)
1359 .setUserId(userId)
1360 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001361 }
1362
Robert Carr8a2f9132019-11-11 15:03:15 -08001363 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001364 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1365 int callingUid = Binder.getCallingUid();
1366 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1367 throw new SecurityException("Only the system process can request a permission token, "
1368 + "received request from uid: " + callingUid);
1369 }
1370 IBinder permissionToken = new Binder();
1371 synchronized (mGlobalLock) {
1372 mStartActivitySources.put(permissionToken, delegatorToken);
1373 }
1374
1375 Message expireMsg = PooledLambda.obtainMessage(
1376 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1377 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1378
1379 Message forgetMsg = PooledLambda.obtainMessage(
1380 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1381 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1382
1383 return permissionToken;
1384 }
1385
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001386 @Override
1387 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1388 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001389 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1390 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001391 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001392 // permission grants) as any app that may launch one of your own activities. So we only
1393 // allow this in two cases:
1394 // 1) The caller is an activity that is part of the core framework, and then only when it
1395 // is running as the system.
1396 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1397 // can only be requested by a system activity, which may then delegate this call to
1398 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001399 final ActivityRecord sourceRecord;
1400 final int targetUid;
1401 final String targetPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001402 final String targetFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001403 final boolean isResolver;
1404 synchronized (mGlobalLock) {
1405 if (resultTo == null) {
1406 throw new SecurityException("Must be called from an activity");
1407 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001408 final IBinder sourceToken;
1409 if (permissionToken != null) {
1410 // To even attempt to use a permissionToken, an app must also have this signature
1411 // permission.
1412 mAmInternal.enforceCallingPermission(
1413 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1414 "startActivityAsCaller");
1415 // If called with a permissionToken, we want the sourceRecord from the delegator
1416 // activity that requested this token.
1417 sourceToken = mStartActivitySources.remove(permissionToken);
1418 if (sourceToken == null) {
1419 // Invalid permissionToken, check if it recently expired.
1420 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1421 throw new SecurityException("Called with expired permission token: "
1422 + permissionToken);
1423 } else {
1424 throw new SecurityException("Called with invalid permission token: "
1425 + permissionToken);
1426 }
1427 }
1428 } else {
1429 // This method was called directly by the source.
1430 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001431 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001432
Louis Chang149d5c82019-12-30 09:47:39 +08001433 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001434 if (sourceRecord == null) {
1435 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001436 }
1437 if (sourceRecord.app == null) {
1438 throw new SecurityException("Called without a process attached to activity");
1439 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001440
1441 // Whether called directly or from a delegate, the source activity must be from the
1442 // android package.
1443 if (!sourceRecord.info.packageName.equals("android")) {
1444 throw new SecurityException("Must be called from an activity that is "
1445 + "declared in the android package");
1446 }
1447
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001448 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001449 // This is still okay, as long as this activity is running under the
1450 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001451 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001453 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001454 + " must be system uid or original calling uid "
1455 + sourceRecord.launchedFromUid);
1456 }
1457 }
1458 if (ignoreTargetSecurity) {
1459 if (intent.getComponent() == null) {
1460 throw new SecurityException(
1461 "Component must be specified with ignoreTargetSecurity");
1462 }
1463 if (intent.getSelector() != null) {
1464 throw new SecurityException(
1465 "Selector not allowed with ignoreTargetSecurity");
1466 }
1467 }
1468 targetUid = sourceRecord.launchedFromUid;
1469 targetPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001470 targetFeatureId = sourceRecord.launchedFromFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001471 isResolver = sourceRecord.isResolverOrChildActivity();
1472 }
1473
1474 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001475 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001476 }
1477
1478 // TODO: Switch to user app stacks here.
1479 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001480 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001481 .setCallingUid(targetUid)
1482 .setCallingPackage(targetPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001483 .setCallingFeatureId(targetFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001484 .setResolvedType(resolvedType)
1485 .setResultTo(resultTo)
1486 .setResultWho(resultWho)
1487 .setRequestCode(requestCode)
1488 .setStartFlags(startFlags)
1489 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001490 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001491 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1492 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001493 // The target may well be in the background, which would normally prevent it
1494 // from starting an activity. Here we definitely want the start to succeed.
1495 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001496 .execute();
1497 } catch (SecurityException e) {
1498 // XXX need to figure out how to propagate to original app.
1499 // A SecurityException here is generally actually a fault of the original
1500 // calling activity (such as a fairly granting permissions), so propagate it
1501 // back to them.
1502 /*
1503 StringBuilder msg = new StringBuilder();
1504 msg.append("While launching");
1505 msg.append(intent.toString());
1506 msg.append(": ");
1507 msg.append(e.getMessage());
1508 */
1509 throw e;
1510 }
1511 }
1512
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001513 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1514 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001515 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001516 }
1517
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001518 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001519 public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1520 int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001521 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1522 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001523 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001524 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001525 if (session == null || interactor == null) {
1526 throw new NullPointerException("null session or interactor");
1527 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001528 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001529 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001530 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001531 .setCallingUid(callingUid)
1532 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001533 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001534 .setResolvedType(resolvedType)
1535 .setVoiceSession(session)
1536 .setVoiceInteractor(interactor)
1537 .setStartFlags(startFlags)
1538 .setProfilerInfo(profilerInfo)
1539 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001540 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001541 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001542 .execute();
1543 }
1544
1545 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001546 public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1547 int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1548 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001549 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001550 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1551 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001552
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001553 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001554 .setCallingUid(callingUid)
1555 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001556 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001557 .setResolvedType(resolvedType)
1558 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001559 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001560 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001561 .execute();
1562 }
1563
Riddle Hsu609a8e22019-06-27 16:46:29 -06001564 /**
1565 * Start the recents activity to perform the recents animation.
1566 *
1567 * @param intent The intent to start the recents activity.
1568 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1569 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001570 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001571 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1572 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001573 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001574 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001575 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001576 final long origId = Binder.clearCallingIdentity();
1577 try {
1578 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001579 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
Philip P. Moltmannee295092020-02-10 08:46:26 -08001580 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001581 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001582 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583
1584 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001585 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001586 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001587 recentsFeatureId, recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001588 if (recentsAnimationRunner == null) {
1589 anim.preloadRecentsActivity();
1590 } else {
1591 anim.startRecentsActivity(recentsAnimationRunner);
1592 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001593 }
1594 } finally {
1595 Binder.restoreCallingIdentity(origId);
1596 }
1597 }
1598
1599 @Override
1600 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001601 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001602 "startActivityFromRecents()");
1603
1604 final int callingPid = Binder.getCallingPid();
1605 final int callingUid = Binder.getCallingUid();
1606 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1607 final long origId = Binder.clearCallingIdentity();
1608 try {
1609 synchronized (mGlobalLock) {
1610 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1611 safeOptions);
1612 }
1613 } finally {
1614 Binder.restoreCallingIdentity(origId);
1615 }
1616 }
1617
1618 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001619 * Public API to check if the client is allowed to start an activity on specified display.
1620 *
1621 * If the target display is private or virtual, some restrictions will apply.
1622 *
1623 * @param displayId Target display id.
1624 * @param intent Intent used to launch the activity.
1625 * @param resolvedType The MIME type of the intent.
1626 * @param userId The id of the user for whom the call is made.
1627 * @return {@code true} if a call to start an activity on the target display should succeed and
1628 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1629 */
1630 @Override
1631 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1632 String resolvedType, int userId) {
1633 final int callingUid = Binder.getCallingUid();
1634 final int callingPid = Binder.getCallingPid();
1635 final long origId = Binder.clearCallingIdentity();
1636
1637 try {
1638 // Collect information about the target of the Intent.
1639 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1640 0 /* startFlags */, null /* profilerInfo */, userId,
1641 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1642 UserHandle.USER_NULL));
1643 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1644
1645 synchronized (mGlobalLock) {
1646 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1647 aInfo);
1648 }
1649 } finally {
1650 Binder.restoreCallingIdentity(origId);
1651 }
1652 }
1653
1654 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001655 * This is the internal entry point for handling Activity.finish().
1656 *
1657 * @param token The Binder token referencing the Activity we want to finish.
1658 * @param resultCode Result code, if any, from this Activity.
1659 * @param resultData Result data (Intent), if any, from this Activity.
1660 * @param finishTask Whether to finish the task associated with this Activity.
1661 *
1662 * @return Returns true if the activity successfully finished, or false if it is still running.
1663 */
1664 @Override
1665 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1666 int finishTask) {
1667 // Refuse possible leaked file descriptors
1668 if (resultData != null && resultData.hasFileDescriptors()) {
1669 throw new IllegalArgumentException("File descriptors passed in Intent");
1670 }
1671
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06001672 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001673 synchronized (mGlobalLock) {
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06001674 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001675 if (r == null) {
1676 return true;
1677 }
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06001678 }
1679
1680 // Carefully collect grants without holding lock
1681 final NeededUriGrants resultGrants = collectGrants(resultData, r.resultTo);
1682
1683 synchronized (mGlobalLock) {
Louis Chang73269792020-06-09 16:02:42 +08001684 // Sanity check in case activity was removed before entering global lock.
1685 if (!r.isInHistory()) {
1686 return true;
1687 }
1688
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001689 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001690 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001691 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001692 if (rootR == null) {
1693 Slog.w(TAG, "Finishing task with all activities already finished");
1694 }
1695 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1696 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001697 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001698 return false;
1699 }
1700
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001701 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1702 // We should consolidate.
1703 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001704 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001705 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001706 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001707 if (next != null) {
1708 // ask watcher if this is allowed
1709 boolean resumeOK = true;
1710 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001711 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001712 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001713 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001714 Watchdog.getInstance().setActivityController(null);
1715 }
1716
1717 if (!resumeOK) {
1718 Slog.i(TAG, "Not finishing activity because controller resumed");
1719 return false;
1720 }
1721 }
1722 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001723
1724 // note down that the process has finished an activity and is in background activity
1725 // starts grace period
1726 if (r.app != null) {
1727 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1728 }
1729
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001730 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001731 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001732 try {
1733 boolean res;
1734 final boolean finishWithRootActivity =
1735 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1736 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1737 || (finishWithRootActivity && r == rootR)) {
1738 // If requested, remove the task that is associated to this activity only if it
1739 // was the root activity in the task. The result code and data is ignored
1740 // because we don't support returning them across task boundaries. Also, to
1741 // keep backwards compatibility we remove the task from recents when finishing
1742 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001743 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001744 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001745 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001746 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001747 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001748 } else {
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06001749 r.finishIfPossible(resultCode, resultData, resultGrants,
1750 "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001751 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001752 if (!res) {
1753 Slog.i(TAG, "Failed to finish by app-request");
1754 }
1755 }
1756 return res;
1757 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001758 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001759 Binder.restoreCallingIdentity(origId);
1760 }
1761 }
1762 }
1763
1764 @Override
1765 public boolean finishActivityAffinity(IBinder token) {
1766 synchronized (mGlobalLock) {
1767 final long origId = Binder.clearCallingIdentity();
1768 try {
1769 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1770 if (r == null) {
1771 return false;
1772 }
1773
1774 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1775 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001776 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001777 return false;
1778 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001779
1780 final PooledFunction p = PooledLambda.obtainFunction(
1781 ActivityRecord::finishIfSameAffinity, r,
1782 PooledLambda.__(ActivityRecord.class));
1783 r.getTask().forAllActivities(
1784 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1785 p.recycle();
1786
Andrii Kuliande93eff2019-07-12 12:21:27 -07001787 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001788 } finally {
1789 Binder.restoreCallingIdentity(origId);
1790 }
1791 }
1792 }
1793
1794 @Override
1795 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1796 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001797 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001798 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001799 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001800 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1801 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001802 return;
1803 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001804 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1805 false /* processPausingActivities */, config);
1806 if (stopProfiling && r.hasProcess()) {
1807 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001808 }
1809 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001810 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001811 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001812 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001813 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001814 }
1815
1816 @Override
1817 public final void activityResumed(IBinder token) {
1818 final long origId = Binder.clearCallingIdentity();
1819 synchronized (mGlobalLock) {
1820 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001821 }
1822 Binder.restoreCallingIdentity(origId);
1823 }
1824
1825 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001826 public final void activityTopResumedStateLost() {
1827 final long origId = Binder.clearCallingIdentity();
1828 synchronized (mGlobalLock) {
1829 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1830 }
1831 Binder.restoreCallingIdentity(origId);
1832 }
1833
1834 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001835 public final void activityPaused(IBinder token) {
1836 final long origId = Binder.clearCallingIdentity();
1837 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001838 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001839 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1840 if (r != null) {
1841 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001842 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001843 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001844 }
1845 Binder.restoreCallingIdentity(origId);
1846 }
1847
1848 @Override
1849 public final void activityStopped(IBinder token, Bundle icicle,
1850 PersistableBundle persistentState, CharSequence description) {
1851 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1852
1853 // Refuse possible leaked file descriptors
1854 if (icicle != null && icicle.hasFileDescriptors()) {
1855 throw new IllegalArgumentException("File descriptors passed in Bundle");
1856 }
1857
1858 final long origId = Binder.clearCallingIdentity();
1859
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001860 String restartingName = null;
1861 int restartingUid = 0;
1862 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001863 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001864 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001865 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001866 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001867 if (r.attachedToProcess()
1868 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1869 // The activity was requested to restart from
1870 // {@link #restartActivityProcessIfVisible}.
1871 restartingName = r.app.mName;
1872 restartingUid = r.app.mUid;
1873 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001874 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001875 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001876 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001877 }
1878
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001879 if (restartingName != null) {
1880 // In order to let the foreground activity can be restarted with its saved state from
1881 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1882 // until the activity reports stopped with the state. And the activity record will be
1883 // kept because the record state is restarting, then the activity will be restarted
1884 // immediately if it is still the top one.
1885 mStackSupervisor.removeRestartTimeouts(r);
1886 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1887 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001888 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001889
1890 Binder.restoreCallingIdentity(origId);
1891 }
1892
1893 @Override
1894 public final void activityDestroyed(IBinder token) {
1895 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1896 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001897 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001898 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001899 try {
1900 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1901 if (activity != null) {
1902 activity.destroyed("activityDestroyed");
1903 }
1904 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001905 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001906 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001907 }
1908 }
1909 }
1910
1911 @Override
1912 public final void activityRelaunched(IBinder token) {
1913 final long origId = Binder.clearCallingIdentity();
1914 synchronized (mGlobalLock) {
1915 mStackSupervisor.activityRelaunchedLocked(token);
1916 }
1917 Binder.restoreCallingIdentity(origId);
1918 }
1919
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001920 @Override
1921 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1922 synchronized (mGlobalLock) {
1923 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1924 if (r == null) {
1925 return;
1926 }
1927 final long origId = Binder.clearCallingIdentity();
1928 try {
1929 r.setRequestedOrientation(requestedOrientation);
1930 } finally {
1931 Binder.restoreCallingIdentity(origId);
1932 }
1933 }
1934 }
1935
1936 @Override
1937 public int getRequestedOrientation(IBinder token) {
1938 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001939 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1940 return (r != null)
1941 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001942 }
1943 }
1944
1945 @Override
1946 public void setImmersive(IBinder token, boolean immersive) {
1947 synchronized (mGlobalLock) {
1948 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1949 if (r == null) {
1950 throw new IllegalArgumentException();
1951 }
1952 r.immersive = immersive;
1953
1954 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001955 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001956 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001957 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001958 }
1959 }
1960 }
1961
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001962 void applyUpdateLockStateLocked(ActivityRecord r) {
1963 // Modifications to the UpdateLock state are done on our handler, outside
1964 // the activity manager's locks. The new state is determined based on the
1965 // state *now* of the relevant activity record. The object is passed to
1966 // the handler solely for logging detail, not to be consulted/modified.
1967 final boolean nextState = r != null && r.immersive;
1968 mH.post(() -> {
1969 if (mUpdateLock.isHeld() != nextState) {
1970 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1971 "Applying new update lock state '" + nextState + "' for " + r);
1972 if (nextState) {
1973 mUpdateLock.acquire();
1974 } else {
1975 mUpdateLock.release();
1976 }
1977 }
1978 });
1979 }
1980
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001981 @Override
1982 public boolean isImmersive(IBinder token) {
1983 synchronized (mGlobalLock) {
1984 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1985 if (r == null) {
1986 throw new IllegalArgumentException();
1987 }
1988 return r.immersive;
1989 }
1990 }
1991
1992 @Override
1993 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001994 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001995 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001996 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
1997 if (topFocusedStack == null) {
1998 return false;
1999 }
2000
2001 final ActivityRecord r = topFocusedStack.topRunningActivity();
2002 return r != null && r.immersive;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002003 }
2004 }
2005
2006 @Override
2007 public void overridePendingTransition(IBinder token, String packageName,
2008 int enterAnim, int exitAnim) {
2009 synchronized (mGlobalLock) {
2010 ActivityRecord self = ActivityRecord.isInStackLocked(token);
2011 if (self == null) {
2012 return;
2013 }
2014
2015 final long origId = Binder.clearCallingIdentity();
2016
2017 if (self.isState(
2018 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08002019 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
Ming-Shin Lub6d70022020-03-27 23:51:56 +08002020 packageName, enterAnim, exitAnim, null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002021 }
2022
2023 Binder.restoreCallingIdentity(origId);
2024 }
2025 }
2026
2027 @Override
2028 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002029 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002030 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002031 final ActivityStack stack = getTopDisplayFocusedStack();
2032 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002033 if (r == null) {
2034 return ActivityManager.COMPAT_MODE_UNKNOWN;
2035 }
Wale Ogunwale53783742018-09-16 10:21:51 -07002036 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002037 }
2038 }
2039
2040 @Override
2041 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002042 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002043 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002044 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002045 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002046 final ActivityStack stack = getTopDisplayFocusedStack();
2047 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002048 if (r == null) {
2049 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
2050 return;
2051 }
2052 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07002053 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002054 }
2055 }
2056
2057 @Override
2058 public int getLaunchedFromUid(IBinder activityToken) {
2059 ActivityRecord srec;
2060 synchronized (mGlobalLock) {
2061 srec = ActivityRecord.forTokenLocked(activityToken);
2062 }
2063 if (srec == null) {
2064 return -1;
2065 }
2066 return srec.launchedFromUid;
2067 }
2068
2069 @Override
2070 public String getLaunchedFromPackage(IBinder activityToken) {
2071 ActivityRecord srec;
2072 synchronized (mGlobalLock) {
2073 srec = ActivityRecord.forTokenLocked(activityToken);
2074 }
2075 if (srec == null) {
2076 return null;
2077 }
2078 return srec.launchedFromPackage;
2079 }
2080
2081 @Override
2082 public boolean convertFromTranslucent(IBinder token) {
2083 final long origId = Binder.clearCallingIdentity();
2084 try {
2085 synchronized (mGlobalLock) {
2086 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2087 if (r == null) {
2088 return false;
2089 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002090 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002091 }
2092 } finally {
2093 Binder.restoreCallingIdentity(origId);
2094 }
2095 }
2096
2097 @Override
2098 public boolean convertToTranslucent(IBinder token, Bundle options) {
2099 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2100 final long origId = Binder.clearCallingIdentity();
2101 try {
2102 synchronized (mGlobalLock) {
2103 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2104 if (r == null) {
2105 return false;
2106 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002107 final ActivityRecord under = r.getTask().getActivityBelow(r);
2108 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002109 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2110 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002111 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002112 }
2113 } finally {
2114 Binder.restoreCallingIdentity(origId);
2115 }
2116 }
2117
2118 @Override
2119 public void notifyActivityDrawn(IBinder token) {
2120 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2121 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002122 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002123 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002124 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002125 }
2126 }
2127 }
2128
2129 @Override
2130 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2131 synchronized (mGlobalLock) {
2132 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2133 if (r == null) {
2134 return;
2135 }
2136 r.reportFullyDrawnLocked(restoredFromBundle);
2137 }
2138 }
2139
2140 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002141 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002142 synchronized (mGlobalLock) {
2143 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002144 if (stack != null) {
2145 final int displayId = stack.getDisplayId();
2146 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002147 }
2148 return DEFAULT_DISPLAY;
2149 }
2150 }
2151
2152 @Override
2153 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002154 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002155 long ident = Binder.clearCallingIdentity();
2156 try {
2157 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002158 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002159 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002160 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002161 }
2162 return null;
2163 }
2164 } finally {
2165 Binder.restoreCallingIdentity(ident);
2166 }
2167 }
2168
2169 @Override
2170 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002171 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002172 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2173 final long callingId = Binder.clearCallingIdentity();
2174 try {
2175 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002176 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002177 if (stack == null) {
2178 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2179 return;
2180 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002181 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002182 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002183 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002184 }
2185 }
2186 } finally {
2187 Binder.restoreCallingIdentity(callingId);
2188 }
2189 }
2190
2191 @Override
2192 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002193 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002194 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2195 final long callingId = Binder.clearCallingIdentity();
2196 try {
2197 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002198 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002199 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002200 if (task == null) {
2201 return;
2202 }
2203 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002204 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002205 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002206 }
2207 }
2208 } finally {
2209 Binder.restoreCallingIdentity(callingId);
2210 }
2211 }
2212
2213 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002214 public void restartActivityProcessIfVisible(IBinder activityToken) {
2215 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2216 final long callingId = Binder.clearCallingIdentity();
2217 try {
2218 synchronized (mGlobalLock) {
2219 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2220 if (r == null) {
2221 return;
2222 }
2223 r.restartProcessIfVisible();
2224 }
2225 } finally {
2226 Binder.restoreCallingIdentity(callingId);
2227 }
2228 }
2229
2230 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002231 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002232 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002233 synchronized (mGlobalLock) {
2234 final long ident = Binder.clearCallingIdentity();
2235 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002236 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002237 "remove-task");
2238 } finally {
2239 Binder.restoreCallingIdentity(ident);
2240 }
2241 }
2242 }
2243
2244 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002245 public void removeAllVisibleRecentTasks() {
2246 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2247 synchronized (mGlobalLock) {
2248 final long ident = Binder.clearCallingIdentity();
2249 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002250 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002251 } finally {
2252 Binder.restoreCallingIdentity(ident);
2253 }
2254 }
2255 }
2256
2257 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002258 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2259 synchronized (mGlobalLock) {
2260 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2261 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002262 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002263 }
2264 }
2265 return false;
2266 }
2267
2268 @Override
2269 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2270 Intent resultData) {
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06002271 final ActivityRecord r;
2272 synchronized (mGlobalLock) {
2273 r = ActivityRecord.isInStackLocked(token);
2274 if (r == null) {
2275 return false;
2276 }
2277 }
2278
2279 // Carefully collect grants without holding lock
2280 final NeededUriGrants destGrants = collectGrants(destIntent, r);
2281 final NeededUriGrants resultGrants = collectGrants(resultData, r.resultTo);
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002282
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002283 synchronized (mGlobalLock) {
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06002284 return r.getRootTask().navigateUpTo(
2285 r, destIntent, destGrants, resultCode, resultData, resultGrants);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002286 }
2287 }
2288
2289 /**
2290 * Attempts to move a task backwards in z-order (the order of activities within the task is
2291 * unchanged).
2292 *
2293 * There are several possible results of this call:
2294 * - if the task is locked, then we will show the lock toast
2295 * - if there is a task behind the provided task, then that task is made visible and resumed as
2296 * this task is moved to the back
2297 * - otherwise, if there are no other tasks in the stack:
2298 * - if this task is in the pinned stack, then we remove the stack completely, which will
2299 * have the effect of moving the task to the top or bottom of the fullscreen stack
2300 * (depending on whether it is visible)
2301 * - otherwise, we simply return home and hide this task
2302 *
2303 * @param token A reference to the activity we wish to move
2304 * @param nonRoot If false then this only works if the activity is the root
2305 * of a task; if true it will work for any activity in a task.
2306 * @return Returns true if the move completed, false if not.
2307 */
2308 @Override
2309 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002310 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002311 synchronized (mGlobalLock) {
2312 final long origId = Binder.clearCallingIdentity();
2313 try {
2314 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002315 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002316 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002317 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002318 }
2319 } finally {
2320 Binder.restoreCallingIdentity(origId);
2321 }
2322 }
2323 return false;
2324 }
2325
2326 @Override
2327 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002328 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002329 long ident = Binder.clearCallingIdentity();
2330 Rect rect = new Rect();
2331 try {
2332 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002333 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002334 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2335 if (task == null) {
2336 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2337 return rect;
2338 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002339 if (task.getParent() != null) {
2340 rect.set(task.getBounds());
2341 } else if (task.mLastNonFullscreenBounds != null) {
2342 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002343 }
2344 }
2345 } finally {
2346 Binder.restoreCallingIdentity(ident);
2347 }
2348 return rect;
2349 }
2350
2351 @Override
2352 public ActivityManager.TaskDescription getTaskDescription(int id) {
2353 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002354 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002355 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002356 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002357 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2358 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002359 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002360 }
2361 }
2362 return null;
2363 }
2364
2365 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002366 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002367 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08002368 return setTaskWindowingModeSplitScreenPrimary(taskId, toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002369 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002370 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002371 synchronized (mGlobalLock) {
2372 final long ident = Binder.clearCallingIdentity();
2373 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002374 if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2375 return setTaskWindowingModeSplitScreen(taskId, windowingMode, toTop);
2376 }
Louis Chang149d5c82019-12-30 09:47:39 +08002377 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002378 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002379 if (task == null) {
2380 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002381 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002382 }
2383
2384 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2385 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2386
2387 if (!task.isActivityTypeStandardOrUndefined()) {
2388 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2389 + " non-standard task " + taskId + " to windowing mode="
2390 + windowingMode);
2391 }
2392
2393 final ActivityStack stack = task.getStack();
2394 if (toTop) {
2395 stack.moveToFront("setTaskWindowingMode", task);
2396 }
Louis Changa009c762020-02-26 11:21:31 +08002397 // Convert some windowing-mode changes into root-task reparents for split-screen.
2398 if (stack.inSplitScreenWindowingMode()) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07002399 stack.getDisplayArea().onSplitScreenModeDismissed();
Louis Changa009c762020-02-26 11:21:31 +08002400
2401 } else {
2402 stack.setWindowingMode(windowingMode);
2403 stack.getDisplay().ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2404 true /* notifyClients */);
2405 }
Winson Chung7ccc6812020-01-23 16:15:10 -08002406 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002407 } finally {
2408 Binder.restoreCallingIdentity(ident);
2409 }
2410 }
2411 }
2412
2413 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002414 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002415 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002416 ActivityRecord r = getCallingRecordLocked(token);
2417 return r != null ? r.info.packageName : null;
2418 }
2419 }
2420
2421 @Override
2422 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002423 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002424 ActivityRecord r = getCallingRecordLocked(token);
2425 return r != null ? r.intent.getComponent() : null;
2426 }
2427 }
2428
2429 private ActivityRecord getCallingRecordLocked(IBinder token) {
2430 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2431 if (r == null) {
2432 return null;
2433 }
2434 return r.resultTo;
2435 }
2436
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06002437 private NeededUriGrants collectGrants(Intent intent, ActivityRecord target) {
2438 if (target != null) {
2439 return mUgmInternal.checkGrantUriPermissionFromIntent(intent,
2440 Binder.getCallingUid(), target.packageName, target.mUserId);
2441 } else {
2442 return null;
2443 }
2444 }
2445
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002446 @Override
2447 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002448 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002449
2450 synchronized (mGlobalLock) {
2451 final long origId = Binder.clearCallingIdentity();
2452 try {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002453 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
2454 if (topFocusedStack != null) {
2455 topFocusedStack.unhandledBackLocked();
2456 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002457 } finally {
2458 Binder.restoreCallingIdentity(origId);
2459 }
2460 }
2461 }
2462
Mark Renouf446251d2019-04-26 10:22:41 -04002463 @Override
2464 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2465 synchronized (mGlobalLock) {
2466 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2467 if (r == null) {
2468 return;
2469 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002470 ActivityStack stack = r.getRootTask();
Winson Chunga1f869d2020-03-21 23:02:48 -07002471 final TaskOrganizerController taskOrgController =
2472 mWindowOrganizerController.mTaskOrganizerController;
2473 if (taskOrgController.handleInterceptBackPressedOnTaskRoot(stack)) {
2474 // This task is handled by a task organizer that has requested the back pressed
2475 // callback
2476 } else if (stack != null && (stack.isSingleTaskInstance())) {
Mark Renouf446251d2019-04-26 10:22:41 -04002477 // Single-task stacks are used for activities which are presented in floating
2478 // windows above full screen activities. Instead of directly finishing the
2479 // task, a task change listener is used to notify SystemUI so the action can be
2480 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002481 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002482 mTaskChangeNotificationController
2483 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2484 } else {
2485 try {
2486 callback.requestFinish();
2487 } catch (RemoteException e) {
2488 Slog.e(TAG, "Failed to invoke request finish callback", e);
2489 }
2490 }
2491 }
2492 }
2493
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002494 /**
2495 * TODO: Add mController hook
2496 */
2497 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002498 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2499 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002500 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002501
2502 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2503 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002504 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
Riddle Hsueae6ef3e2020-05-13 01:07:33 +08002505 SafeActivityOptions.fromBundle(bOptions));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002506 }
2507 }
2508
Ricky Waiaca8a772019-04-04 16:01:06 +01002509 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
Riddle Hsueae6ef3e2020-05-13 01:07:33 +08002510 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002511 final int callingPid = Binder.getCallingPid();
2512 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002513 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002514 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002515 SafeActivityOptions.abort(options);
2516 return;
2517 }
2518 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002519 WindowProcessController callerApp = null;
2520 if (appThread != null) {
2521 callerApp = getProcessController(appThread);
2522 }
2523 final ActivityStarter starter = getActivityStartController().obtainStarter(
2524 null /* intent */, "moveTaskToFront");
2525 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
Galia Peychevaed401cc2020-03-19 20:28:09 +01002526 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002527 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002528 return;
2529 }
2530 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002531 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002532 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002533 if (task == null) {
2534 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002535 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002536 return;
2537 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002538 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002539 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002540 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002541 return;
2542 }
2543 ActivityOptions realOptions = options != null
2544 ? options.getOptions(mStackSupervisor)
2545 : null;
2546 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2547 false /* forceNonResizable */);
2548
Wale Ogunwale21e06482019-11-18 05:14:15 -08002549 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002550 if (topActivity != null) {
2551
2552 // We are reshowing a task, use a starting window to hide the initial draw delay
2553 // so the transition can start earlier.
2554 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
Riddle Hsueae6ef3e2020-05-13 01:07:33 +08002555 true /* taskSwitch */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002556 }
2557 } finally {
2558 Binder.restoreCallingIdentity(origId);
2559 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002560 }
2561
Ricky Waiaca8a772019-04-04 16:01:06 +01002562 /**
2563 * Return true if callingUid is system, or packageName belongs to that callingUid.
2564 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002565 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002566 try {
2567 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2568 if (packageName == null) {
2569 return false;
2570 }
2571 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2572 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2573 UserHandle.getUserId(callingUid));
2574 return UserHandle.isSameApp(callingUid, uid);
2575 }
2576 } catch (RemoteException e) {
2577 // Should not happen
2578 }
2579 return true;
2580 }
2581
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002582 /**
2583 * Checks that the provided package name matches the current calling UID, throws a security
2584 * exception if it doesn't.
2585 */
2586 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2587 final int callingUid = Binder.getCallingUid();
2588 if (isSameApp(callingUid, packageName)) {
2589 return;
2590 }
2591 final String msg = "Permission Denial: package=" + packageName
2592 + " does not belong to uid=" + callingUid;
2593 Slog.w(TAG, msg);
2594 throw new SecurityException(msg);
2595 }
2596
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002597 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2598 int callingPid, int callingUid, String name) {
2599 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2600 return true;
2601 }
2602
2603 if (getRecentTasks().isCallerRecents(sourceUid)) {
2604 return true;
2605 }
2606
2607 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2608 if (perm == PackageManager.PERMISSION_GRANTED) {
2609 return true;
2610 }
2611 if (checkAllowAppSwitchUid(sourceUid)) {
2612 return true;
2613 }
2614
2615 // If the actual IPC caller is different from the logical source, then
2616 // also see if they are allowed to control app switches.
2617 if (callingUid != -1 && callingUid != sourceUid) {
2618 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2619 if (perm == PackageManager.PERMISSION_GRANTED) {
2620 return true;
2621 }
2622 if (checkAllowAppSwitchUid(callingUid)) {
2623 return true;
2624 }
2625 }
2626
2627 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2628 return false;
2629 }
2630
2631 private boolean checkAllowAppSwitchUid(int uid) {
2632 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2633 if (types != null) {
2634 for (int i = types.size() - 1; i >= 0; i--) {
2635 if (types.valueAt(i).intValue() == uid) {
2636 return true;
2637 }
2638 }
2639 }
2640 return false;
2641 }
2642
2643 @Override
2644 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2645 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2646 "setActivityController()");
2647 synchronized (mGlobalLock) {
2648 mController = controller;
2649 mControllerIsAMonkey = imAMonkey;
2650 Watchdog.getInstance().setActivityController(controller);
2651 }
2652 }
2653
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002654 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002655 synchronized (mGlobalLock) {
2656 return mController != null && mControllerIsAMonkey;
2657 }
2658 }
2659
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002660 @Override
2661 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2662 synchronized (mGlobalLock) {
2663 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2664 }
2665 }
2666
2667 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002668 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
Winson Chunge5ab0172020-03-21 23:00:24 -07002669 return getFilteredTasks(maxNum, false /* filterForVisibleRecents */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002670 }
2671
Winson Chunge5ab0172020-03-21 23:00:24 -07002672 /**
2673 * @param filterOnlyVisibleRecents whether to filter the tasks based on whether they would ever
2674 * be visible in the recent task list in systemui
2675 */
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002676 @Override
2677 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
Winson Chunge5ab0172020-03-21 23:00:24 -07002678 boolean filterOnlyVisibleRecents) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002679 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002680 final int callingPid = Binder.getCallingPid();
2681 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002682 final int[] profileIds = getUserManager().getProfileIds(
2683 UserHandle.getUserId(callingUid), true);
2684 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2685 for (int i = 0; i < profileIds.length; i++) {
2686 callingProfileIds.add(profileIds[i]);
2687 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002688 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2689
2690 synchronized (mGlobalLock) {
2691 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2692
Nicholas Sauer0259e532019-08-30 08:24:55 -07002693 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Winson Chunge5ab0172020-03-21 23:00:24 -07002694 mRootWindowContainer.getRunningTasks(maxNum, list, filterOnlyVisibleRecents, callingUid,
2695 allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002696 }
2697
2698 return list;
2699 }
2700
2701 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002702 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2703 synchronized (mGlobalLock) {
2704 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002705 try {
2706 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2707 if (r == null) return;
2708
2709 final PooledConsumer c = PooledLambda.obtainConsumer(
2710 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2711 r, resultWho, requestCode);
2712 // TODO: This should probably only loop over the task since you need to be in the
2713 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002714 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002715 c.recycle();
2716
2717 updateOomAdj();
2718 } finally {
2719 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002720 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002721 }
2722 }
2723
2724 @Override
2725 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002726 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002727 ActivityStack stack = ActivityRecord.getStackLocked(token);
2728 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002729 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002730 }
2731 return false;
2732 }
2733 }
2734
2735 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002736 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002737 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002738 synchronized (mGlobalLock) {
2739 final long ident = Binder.clearCallingIdentity();
2740 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002741 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002742 if (task == null) {
2743 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2744 return;
2745 }
2746
2747 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2748 + " to stackId=" + stackId + " toTop=" + toTop);
2749
Louis Chang149d5c82019-12-30 09:47:39 +08002750 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002751 if (stack == null) {
2752 throw new IllegalStateException(
2753 "moveTaskToStack: No stack for stackId=" + stackId);
2754 }
2755 if (!stack.isActivityTypeStandardOrUndefined()) {
2756 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2757 + taskId + " to stack " + stackId);
2758 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002759 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2760 "moveTaskToStack");
2761 } finally {
2762 Binder.restoreCallingIdentity(ident);
2763 }
2764 }
2765 }
2766
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002767 /**
2768 * Moves the specified task to the primary-split-screen stack.
2769 *
2770 * @param taskId Id of task to move.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002771 * @param toTop If the task and stack should be moved to the top.
Winson Chung7ccc6812020-01-23 16:15:10 -08002772 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002773 */
2774 @Override
Evan Rosky73a7fe92019-11-18 18:28:01 -08002775 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002776 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002777 "setTaskWindowingModeSplitScreenPrimary()");
2778 synchronized (mGlobalLock) {
2779 final long ident = Binder.clearCallingIdentity();
2780 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002781 return setTaskWindowingModeSplitScreen(taskId, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY,
2782 toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002783 } finally {
2784 Binder.restoreCallingIdentity(ident);
2785 }
2786 }
2787 }
2788
2789 /**
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002790 * Moves the specified task into a split-screen tile.
2791 */
2792 private boolean setTaskWindowingModeSplitScreen(int taskId, int windowingMode, boolean toTop) {
2793 if (!WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2794 throw new IllegalArgumentException("Calling setTaskWindowingModeSplitScreen with non"
2795 + "split-screen mode: " + windowingMode);
2796 }
2797 if (isInLockTaskMode()) {
2798 Slog.w(TAG, "setTaskWindowingModeSplitScreen: Is in lock task mode="
2799 + getLockTaskModeState());
2800 return false;
2801 }
2802
2803 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2804 MATCH_TASK_IN_STACKS_ONLY);
2805 if (task == null) {
2806 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2807 return false;
2808 }
2809 if (!task.isActivityTypeStandardOrUndefined()) {
2810 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2811 + " non-standard task " + taskId + " to split-screen windowing mode");
2812 }
Wale Ogunwale0d465192020-01-23 19:14:44 -08002813 if (!task.supportsSplitScreenWindowingMode()) {
2814 return false;
2815 }
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002816
2817 final int prevMode = task.getWindowingMode();
Louis Changcf3d1452020-04-16 16:36:05 +08002818 if (prevMode == windowingMode) {
2819 // The task is already in split-screen and with correct windowing mode.
2820 return true;
2821 }
2822
Louis Changa009c762020-02-26 11:21:31 +08002823 moveTaskToSplitScreenPrimaryTask(task, toTop);
Wale Ogunwale0d465192020-01-23 19:14:44 -08002824 return prevMode != task.getWindowingMode();
2825 }
2826
Louis Changa009c762020-02-26 11:21:31 +08002827 void moveTaskToSplitScreenPrimaryTask(Task task, boolean toTop) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07002828 final TaskDisplayArea taskDisplayArea = task.getDisplayArea();
2829 final ActivityStack primarySplitTask = taskDisplayArea.getRootSplitScreenPrimaryTask();
Louis Changa009c762020-02-26 11:21:31 +08002830 if (primarySplitTask == null) {
2831 throw new IllegalStateException("Can't enter split without associated organized task");
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002832 }
Louis Changa009c762020-02-26 11:21:31 +08002833
2834 if (toTop) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07002835 taskDisplayArea.positionStackAt(POSITION_TOP, primarySplitTask,
Andrii Kulian9ea12da2020-03-27 17:16:38 -07002836 false /* includingParents */);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002837 }
2838 WindowContainerTransaction wct = new WindowContainerTransaction();
Wale Ogunwale465b1e12020-03-31 12:15:51 -07002839 // Clear out current windowing mode before reparenting to split taks.
2840 wct.setWindowingMode(
2841 task.getStack().mRemoteToken.toWindowContainerToken(), WINDOWING_MODE_UNDEFINED);
Wale Ogunwaleadf116e2020-03-27 16:36:01 -07002842 wct.reparent(task.getStack().mRemoteToken.toWindowContainerToken(),
2843 primarySplitTask.mRemoteToken.toWindowContainerToken(), toTop);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07002844 mWindowOrganizerController.applyTransaction(wct);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002845 }
2846
2847 /**
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002848 * Removes stacks in the input windowing modes from the system if they are of activity type
2849 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2850 */
2851 @Override
2852 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002853 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002854 "removeStacksInWindowingModes()");
2855
2856 synchronized (mGlobalLock) {
2857 final long ident = Binder.clearCallingIdentity();
2858 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002859 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002860 } finally {
2861 Binder.restoreCallingIdentity(ident);
2862 }
2863 }
2864 }
2865
2866 @Override
2867 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002868 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002869 "removeStacksWithActivityTypes()");
2870
2871 synchronized (mGlobalLock) {
2872 final long ident = Binder.clearCallingIdentity();
2873 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002874 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002875 } finally {
2876 Binder.restoreCallingIdentity(ident);
2877 }
2878 }
2879 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880
2881 @Override
2882 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2883 int userId) {
2884 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002885 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2886 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002887 callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002888 synchronized (mGlobalLock) {
Winson Chung66b08f02020-03-03 14:32:35 -08002889 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, userId, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002890 }
2891 }
2892
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002893 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002894 @Override
2895 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002896 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002897 long ident = Binder.clearCallingIdentity();
2898 try {
2899 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002900 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002901 }
2902 } finally {
2903 Binder.restoreCallingIdentity(ident);
2904 }
2905 }
2906
2907 @Override
2908 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002909 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002910 long ident = Binder.clearCallingIdentity();
2911 try {
2912 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002913 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002914 }
2915 } finally {
2916 Binder.restoreCallingIdentity(ident);
2917 }
2918 }
2919
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002920 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002921 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002922 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2923 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2924 long ident = Binder.clearCallingIdentity();
2925 try {
2926 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002927 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002928 }
2929 } finally {
2930 Binder.restoreCallingIdentity(ident);
2931 }
2932 }
2933
2934 @Override
2935 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2936 int displayId) {
2937 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2938 long ident = Binder.clearCallingIdentity();
2939 try {
2940 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002941 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002942 }
2943 } finally {
2944 Binder.restoreCallingIdentity(ident);
2945 }
2946 }
2947
2948 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002949 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002950 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002951 final long callingUid = Binder.getCallingUid();
2952 final long origId = Binder.clearCallingIdentity();
2953 try {
2954 synchronized (mGlobalLock) {
2955 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002956 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002957 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2958 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2959 }
2960 } finally {
2961 Binder.restoreCallingIdentity(origId);
2962 }
2963 }
2964
2965 @Override
2966 public void startLockTaskModeByToken(IBinder token) {
2967 synchronized (mGlobalLock) {
2968 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2969 if (r == null) {
2970 return;
2971 }
Louis Changcdec0802019-11-11 11:45:07 +08002972 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002973 }
2974 }
2975
2976 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002977 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002978 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002979 // This makes inner call to look as if it was initiated by system.
2980 long ident = Binder.clearCallingIdentity();
2981 try {
2982 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002983 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002984 MATCH_TASK_IN_STACKS_ONLY);
2985 if (task == null) {
2986 return;
2987 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002988
2989 // When starting lock task mode the stack must be in front and focused
2990 task.getStack().moveToFront("startSystemLockTaskMode");
2991 startLockTaskModeLocked(task, true /* isSystemCaller */);
2992 }
2993 } finally {
2994 Binder.restoreCallingIdentity(ident);
2995 }
2996 }
2997
2998 @Override
2999 public void stopLockTaskModeByToken(IBinder token) {
3000 synchronized (mGlobalLock) {
3001 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3002 if (r == null) {
3003 return;
3004 }
Louis Changcdec0802019-11-11 11:45:07 +08003005 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003006 }
3007 }
3008
3009 /**
3010 * This API should be called by SystemUI only when user perform certain action to dismiss
3011 * lock task mode. We should only dismiss pinned lock task mode in this case.
3012 */
3013 @Override
3014 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003015 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003016 stopLockTaskModeInternal(null, true /* isSystemCaller */);
3017 }
3018
Louis Changcdec0802019-11-11 11:45:07 +08003019 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003020 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
3021 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
3022 return;
3023 }
3024
Louis Chang149d5c82019-12-30 09:47:39 +08003025 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09003026 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003027 throw new IllegalArgumentException("Invalid task, not in foreground");
3028 }
3029
3030 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
3031 // system or a specific app.
3032 // * System-initiated requests will only start the pinned mode (screen pinning)
3033 // * App-initiated requests
3034 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
3035 // - will start the pinned mode, otherwise
3036 final int callingUid = Binder.getCallingUid();
3037 long ident = Binder.clearCallingIdentity();
3038 try {
3039 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08003040 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003041
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003042 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003043 } finally {
3044 Binder.restoreCallingIdentity(ident);
3045 }
3046 }
3047
Louis Changcdec0802019-11-11 11:45:07 +08003048 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003049 final int callingUid = Binder.getCallingUid();
3050 long ident = Binder.clearCallingIdentity();
3051 try {
3052 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003053 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003054 }
3055 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
3056 // task and jumping straight into a call in the case of emergency call back.
3057 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
3058 if (tm != null) {
3059 tm.showInCallScreen(false);
3060 }
3061 } finally {
3062 Binder.restoreCallingIdentity(ident);
3063 }
3064 }
3065
3066 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003067 public void updateLockTaskPackages(int userId, String[] packages) {
3068 final int callingUid = Binder.getCallingUid();
3069 if (callingUid != 0 && callingUid != SYSTEM_UID) {
3070 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
3071 "updateLockTaskPackages()");
3072 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08003073 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003074 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
3075 + Arrays.toString(packages));
3076 getLockTaskController().updateLockTaskPackages(userId, packages);
3077 }
3078 }
3079
3080 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003081 public boolean isInLockTaskMode() {
3082 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3083 }
3084
3085 @Override
3086 public int getLockTaskModeState() {
3087 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003088 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003089 }
3090 }
3091
3092 @Override
3093 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3094 synchronized (mGlobalLock) {
3095 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3096 if (r != null) {
3097 r.setTaskDescription(td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003098 }
3099 }
3100 }
3101
3102 @Override
3103 public Bundle getActivityOptions(IBinder token) {
3104 final long origId = Binder.clearCallingIdentity();
3105 try {
3106 synchronized (mGlobalLock) {
3107 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3108 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003109 final ActivityOptions activityOptions = r.takeOptionsLocked(
3110 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003111 return activityOptions == null ? null : activityOptions.toBundle();
3112 }
3113 return null;
3114 }
3115 } finally {
3116 Binder.restoreCallingIdentity(origId);
3117 }
3118 }
3119
3120 @Override
3121 public List<IBinder> getAppTasks(String callingPackage) {
3122 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003123 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003124 long ident = Binder.clearCallingIdentity();
3125 try {
3126 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003127 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003128 }
3129 } finally {
3130 Binder.restoreCallingIdentity(ident);
3131 }
3132 }
3133
3134 @Override
3135 public void finishVoiceTask(IVoiceInteractionSession session) {
3136 synchronized (mGlobalLock) {
3137 final long origId = Binder.clearCallingIdentity();
3138 try {
3139 // TODO: VI Consider treating local voice interactions and voice tasks
3140 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003141 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003142 } finally {
3143 Binder.restoreCallingIdentity(origId);
3144 }
3145 }
3146
3147 }
3148
3149 @Override
3150 public boolean isTopOfTask(IBinder token) {
3151 synchronized (mGlobalLock) {
3152 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003153 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003154 }
3155 }
3156
3157 @Override
3158 public void notifyLaunchTaskBehindComplete(IBinder token) {
3159 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3160 }
3161
3162 @Override
3163 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003164 mH.post(() -> {
3165 synchronized (mGlobalLock) {
3166 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003167 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003168 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003169 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003170 } catch (RemoteException e) {
3171 }
3172 }
3173 }
3174
3175 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003176 }
3177
3178 /** Called from an app when assist data is ready. */
3179 @Override
3180 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3181 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003182 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003183 synchronized (pae) {
3184 pae.result = extras;
3185 pae.structure = structure;
3186 pae.content = content;
3187 if (referrer != null) {
3188 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3189 }
3190 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003191 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003192 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003193 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003194 structure.setHomeActivity(pae.isHome);
3195 }
3196 pae.haveResult = true;
3197 pae.notifyAll();
3198 if (pae.intent == null && pae.receiver == null) {
3199 // Caller is just waiting for the result.
3200 return;
3201 }
3202 }
3203 // We are now ready to launch the assist activity.
3204 IAssistDataReceiver sendReceiver = null;
3205 Bundle sendBundle = null;
3206 synchronized (mGlobalLock) {
3207 buildAssistBundleLocked(pae, extras);
3208 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003209 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003210 if (!exists) {
3211 // Timed out.
3212 return;
3213 }
3214
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003215 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003216 // Caller wants result sent back to them.
3217 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003218 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003219 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003220 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3221 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003222 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3223 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3224 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3225 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3226 }
3227 }
3228 if (sendReceiver != null) {
3229 try {
3230 sendReceiver.onHandleAssistData(sendBundle);
3231 } catch (RemoteException e) {
3232 }
3233 return;
3234 }
3235
3236 final long ident = Binder.clearCallingIdentity();
3237 try {
3238 if (TextUtils.equals(pae.intent.getAction(),
3239 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003240 // Start voice interaction through VoiceInteractionManagerService.
Galia Peycheva969f9952020-05-11 20:26:45 +02003241 mAssistUtils.showSessionForActiveService(pae.extras, SHOW_SOURCE_APPLICATION,
Galia Peychevabffbfc32019-06-18 10:11:35 +02003242 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003243 } else {
3244 pae.intent.replaceExtras(pae.extras);
3245 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3246 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3247 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003248 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003249
3250 try {
3251 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3252 } catch (ActivityNotFoundException e) {
3253 Slog.w(TAG, "No activity to handle assist action.", e);
3254 }
3255 }
3256 } finally {
3257 Binder.restoreCallingIdentity(ident);
3258 }
3259 }
3260
3261 @Override
3262 public int addAppTask(IBinder activityToken, Intent intent,
3263 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3264 final int callingUid = Binder.getCallingUid();
3265 final long callingIdent = Binder.clearCallingIdentity();
3266
3267 try {
3268 synchronized (mGlobalLock) {
3269 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3270 if (r == null) {
3271 throw new IllegalArgumentException("Activity does not exist; token="
3272 + activityToken);
3273 }
3274 ComponentName comp = intent.getComponent();
3275 if (comp == null) {
3276 throw new IllegalArgumentException("Intent " + intent
3277 + " must specify explicit component");
3278 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003279 if (thumbnail.getWidth() != mThumbnailWidth
3280 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003281 throw new IllegalArgumentException("Bad thumbnail size: got "
3282 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003283 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003284 }
3285 if (intent.getSelector() != null) {
3286 intent.setSelector(null);
3287 }
3288 if (intent.getSourceBounds() != null) {
3289 intent.setSourceBounds(null);
3290 }
3291 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3292 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3293 // The caller has added this as an auto-remove task... that makes no
3294 // sense, so turn off auto-remove.
3295 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3296 }
3297 }
3298 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3299 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3300 if (ainfo.applicationInfo.uid != callingUid) {
3301 throw new SecurityException(
3302 "Can't add task for another application: target uid="
3303 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3304 }
3305
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003306 final ActivityStack stack = r.getRootTask();
Andrii Kulian86d676c2020-03-27 19:34:54 -07003307 final Task task = stack.getDisplayArea().createStack(stack.getWindowingMode(),
3308 stack.getActivityType(), !ON_TOP, ainfo, intent,
Louis Changa009c762020-02-26 11:21:31 +08003309 false /* createdByOrganizer */);
Wale Ogunwale0d465192020-01-23 19:14:44 -08003310
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003311 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003312 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003313 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003314 return INVALID_TASK_ID;
3315 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003316 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003317
3318 // TODO: Send the thumbnail to WM to store it.
3319
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003320 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003321 }
3322 } finally {
3323 Binder.restoreCallingIdentity(callingIdent);
3324 }
3325 }
3326
3327 @Override
3328 public Point getAppTaskThumbnailSize() {
3329 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003330 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003331 }
3332 }
3333
3334 @Override
3335 public void setTaskResizeable(int taskId, int resizeableMode) {
3336 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003337 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003338 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3339 if (task == null) {
3340 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3341 return;
3342 }
3343 task.setResizeMode(resizeableMode);
3344 }
3345 }
3346
3347 @Override
Daichi Hironofa23f602020-05-14 06:15:59 +00003348 public boolean resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003349 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003350 long ident = Binder.clearCallingIdentity();
3351 try {
3352 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003353 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003354 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003355 if (task == null) {
3356 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
Daichi Hironofa23f602020-05-14 06:15:59 +00003357 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003358 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003359 if (!task.getWindowConfiguration().canResizeTask()) {
Daichi Hironofa23f602020-05-14 06:15:59 +00003360 Slog.w(TAG, "resizeTask not allowed on task=" + task);
3361 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003362 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003363
3364 // Reparent the task to the right stack if necessary
3365 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003366
3367 // After reparenting (which only resizes the task to the stack bounds), resize the
3368 // task to the actual bounds provided
Daichi Hironofa23f602020-05-14 06:15:59 +00003369 return task.resize(bounds, resizeMode, preserveWindow);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 }
3371 } finally {
3372 Binder.restoreCallingIdentity(ident);
3373 }
3374 }
3375
3376 @Override
3377 public boolean releaseActivityInstance(IBinder token) {
3378 synchronized (mGlobalLock) {
3379 final long origId = Binder.clearCallingIdentity();
3380 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003381 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3382 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383 return false;
3384 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003385 r.destroyImmediately(true /* removeFromApp */, "app-req");
3386 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003387 } finally {
3388 Binder.restoreCallingIdentity(origId);
3389 }
3390 }
3391 }
3392
3393 @Override
3394 public void releaseSomeActivities(IApplicationThread appInt) {
3395 synchronized (mGlobalLock) {
3396 final long origId = Binder.clearCallingIdentity();
3397 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003398 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003399 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003400 } finally {
3401 Binder.restoreCallingIdentity(origId);
3402 }
3403 }
3404 }
3405
3406 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003407 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003408 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003409 != PackageManager.PERMISSION_GRANTED) {
3410 throw new SecurityException("Requires permission "
3411 + android.Manifest.permission.DEVICE_POWER);
3412 }
3413
3414 synchronized (mGlobalLock) {
3415 long ident = Binder.clearCallingIdentity();
3416 if (mKeyguardShown != keyguardShowing) {
3417 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003418 final Message msg = PooledLambda.obtainMessage(
3419 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3420 keyguardShowing);
3421 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422 }
3423 try {
wilsonshih177261f2019-02-22 12:02:18 +08003424 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003425 } finally {
3426 Binder.restoreCallingIdentity(ident);
3427 }
3428 }
3429
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003430 mH.post(() -> {
3431 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3432 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3433 }
3434 });
3435 }
3436
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003437 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003438 mH.post(() -> {
3439 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3440 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3441 }
3442 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003443 }
3444
3445 @Override
3446 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003447 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3448 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003449
3450 final File passedIconFile = new File(filePath);
3451 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3452 passedIconFile.getName());
3453 if (!legitIconFile.getPath().equals(filePath)
3454 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3455 throw new IllegalArgumentException("Bad file path: " + filePath
3456 + " passed for userId " + userId);
3457 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003458 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003459 }
3460
3461 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003462 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003463 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003464 synchronized (mGlobalLock) {
3465 final long ident = Binder.clearCallingIdentity();
3466 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003467 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003468 if (stack == null) {
3469 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3470 return;
3471 }
3472 if (!stack.isActivityTypeStandardOrUndefined()) {
3473 throw new IllegalArgumentException(
3474 "Removing non-standard stack is not allowed.");
3475 }
3476 mStackSupervisor.removeStack(stack);
3477 } finally {
3478 Binder.restoreCallingIdentity(ident);
3479 }
3480 }
3481 }
3482
3483 @Override
3484 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003485 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003486
3487 synchronized (mGlobalLock) {
3488 final long ident = Binder.clearCallingIdentity();
3489 try {
3490 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3491 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003492 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003493 } finally {
3494 Binder.restoreCallingIdentity(ident);
3495 }
3496 }
3497 }
3498
3499 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003500 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003501 synchronized (mGlobalLock) {
3502 long ident = Binder.clearCallingIdentity();
3503 try {
3504 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3505 if (r == null) {
3506 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003507 "toggleFreeformWindowingMode: No activity record matching token="
3508 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003509 }
3510
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003511 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003512 if (stack == null) {
3513 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3514 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003515 }
3516
Yunfan Chend967af82019-01-17 18:30:18 +09003517 if (!stack.inFreeformWindowingMode()
3518 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3519 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3520 + "toggle between fullscreen and freeform.");
3521 }
3522
3523 if (stack.inFreeformWindowingMode()) {
3524 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003525 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003526 throw new IllegalStateException("Size-compat windows are currently not"
3527 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003528 } else if (stack.getParent().inFreeformWindowingMode()) {
3529 // If the window is on a freeform display, set it to undefined. It will be
3530 // resolved to freeform and it can adjust windowing mode when the display mode
3531 // changes in runtime.
3532 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003533 } else {
3534 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3535 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003536 } finally {
3537 Binder.restoreCallingIdentity(ident);
3538 }
3539 }
3540 }
3541
3542 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3543 @Override
3544 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003545 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003546 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003547 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003548 }
3549
3550 /** Unregister a task stack listener so that it stops receiving callbacks. */
3551 @Override
3552 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003553 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003554 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003555 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003556 }
3557
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003558 @Override
3559 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3560 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3561 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3562 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3563 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3564 }
3565
3566 @Override
3567 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3568 IBinder activityToken, int flags) {
3569 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3570 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3571 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3572 }
3573
3574 @Override
3575 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3576 Bundle args) {
3577 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3578 true /* focused */, true /* newSessionId */, userHandle, args,
3579 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3580 }
3581
3582 @Override
3583 public Bundle getAssistContextExtras(int requestType) {
3584 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3585 null, null, true /* focused */, true /* newSessionId */,
3586 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3587 if (pae == null) {
3588 return null;
3589 }
3590 synchronized (pae) {
3591 while (!pae.haveResult) {
3592 try {
3593 pae.wait();
3594 } catch (InterruptedException e) {
3595 }
3596 }
3597 }
3598 synchronized (mGlobalLock) {
3599 buildAssistBundleLocked(pae, pae.result);
3600 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003601 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003602 }
3603 return pae.extras;
3604 }
3605
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003606 /**
3607 * Binder IPC calls go through the public entry point.
3608 * This can be called with or without the global lock held.
3609 */
3610 private static int checkCallingPermission(String permission) {
3611 return checkPermission(
3612 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3613 }
3614
3615 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003616 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003617 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3618 mAmInternal.enforceCallingPermission(permission, func);
3619 }
3620 }
3621
3622 @VisibleForTesting
3623 int checkGetTasksPermission(String permission, int pid, int uid) {
3624 return checkPermission(permission, pid, uid);
3625 }
3626
3627 static int checkPermission(String permission, int pid, int uid) {
3628 if (permission == null) {
3629 return PackageManager.PERMISSION_DENIED;
3630 }
3631 return checkComponentPermission(permission, pid, uid, -1, true);
3632 }
3633
Wale Ogunwale214f3482018-10-04 11:00:47 -07003634 public static int checkComponentPermission(String permission, int pid, int uid,
3635 int owningUid, boolean exported) {
3636 return ActivityManagerService.checkComponentPermission(
3637 permission, pid, uid, owningUid, exported);
3638 }
3639
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003640 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3641 if (getRecentTasks().isCallerRecents(callingUid)) {
3642 // Always allow the recents component to get tasks
3643 return true;
3644 }
3645
3646 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3647 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3648 if (!allowed) {
3649 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3650 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3651 // Temporary compatibility: some existing apps on the system image may
3652 // still be requesting the old permission and not switched to the new
3653 // one; if so, we'll still allow them full access. This means we need
3654 // to see if they are holding the old permission and are a system app.
3655 try {
3656 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3657 allowed = true;
3658 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3659 + " is using old GET_TASKS but privileged; allowing");
3660 }
3661 } catch (RemoteException e) {
3662 }
3663 }
3664 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3665 + " does not hold REAL_GET_TASKS; limiting output");
3666 }
3667 return allowed;
3668 }
3669
Nicholas Sauer0259e532019-08-30 08:24:55 -07003670 boolean isCrossUserAllowed(int pid, int uid) {
3671 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3672 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3673 }
3674
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003675 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3676 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3677 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3678 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003679 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003680 "enqueueAssistContext()");
3681
3682 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08003683 final ActivityStack stack = getTopDisplayFocusedStack();
3684 ActivityRecord activity = stack != null ? stack.getTopNonFinishingActivity() : null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003685 if (activity == null) {
3686 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3687 return null;
3688 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003689 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003690 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3691 return null;
3692 }
3693 if (focused) {
3694 if (activityToken != null) {
3695 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3696 if (activity != caller) {
3697 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3698 + " is not current top " + activity);
3699 return null;
3700 }
3701 }
3702 } else {
3703 activity = ActivityRecord.forTokenLocked(activityToken);
3704 if (activity == null) {
3705 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3706 + " couldn't be found");
3707 return null;
3708 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003709 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003710 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3711 return null;
3712 }
3713 }
3714
3715 PendingAssistExtras pae;
3716 Bundle extras = new Bundle();
3717 if (args != null) {
3718 extras.putAll(args);
3719 }
3720 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003721 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003722
3723 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3724 userHandle);
3725 pae.isHome = activity.isActivityTypeHome();
3726
3727 // Increment the sessionId if necessary
3728 if (newSessionId) {
3729 mViSessionId++;
3730 }
3731 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003732 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3733 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003734 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003735 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003736 } catch (RemoteException e) {
3737 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3738 return null;
3739 }
3740 return pae;
3741 }
3742 }
3743
3744 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3745 if (result != null) {
3746 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3747 }
3748 if (pae.hint != null) {
3749 pae.extras.putBoolean(pae.hint, true);
3750 }
3751 }
3752
3753 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3754 IAssistDataReceiver receiver;
3755 synchronized (mGlobalLock) {
3756 mPendingAssistExtras.remove(pae);
3757 receiver = pae.receiver;
3758 }
3759 if (receiver != null) {
3760 // Caller wants result sent back to them.
3761 Bundle sendBundle = new Bundle();
3762 // At least return the receiver extras
3763 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3764 try {
3765 pae.receiver.onHandleAssistData(sendBundle);
3766 } catch (RemoteException e) {
3767 }
3768 }
3769 }
3770
3771 public class PendingAssistExtras extends Binder implements Runnable {
3772 public final ActivityRecord activity;
3773 public boolean isHome;
3774 public final Bundle extras;
3775 public final Intent intent;
3776 public final String hint;
3777 public final IAssistDataReceiver receiver;
3778 public final int userHandle;
3779 public boolean haveResult = false;
3780 public Bundle result = null;
3781 public AssistStructure structure = null;
3782 public AssistContent content = null;
3783 public Bundle receiverExtras;
3784
3785 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3786 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3787 int _userHandle) {
3788 activity = _activity;
3789 extras = _extras;
3790 intent = _intent;
3791 hint = _hint;
3792 receiver = _receiver;
3793 receiverExtras = _receiverExtras;
3794 userHandle = _userHandle;
3795 }
3796
3797 @Override
3798 public void run() {
3799 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3800 synchronized (this) {
3801 haveResult = true;
3802 notifyAll();
3803 }
3804 pendingAssistExtrasTimedOut(this);
3805 }
3806 }
3807
3808 @Override
3809 public boolean isAssistDataAllowedOnCurrentActivity() {
3810 int userId;
3811 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003812 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003813 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3814 return false;
3815 }
3816
Wale Ogunwale21e06482019-11-18 05:14:15 -08003817 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003818 if (activity == null) {
3819 return false;
3820 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003821 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003822 }
Alex Johnston302c1fe2020-06-18 20:00:51 +01003823 return DevicePolicyCache.getInstance().isScreenCaptureAllowed(userId, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003824 }
3825
3826 @Override
3827 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3828 long ident = Binder.clearCallingIdentity();
3829 try {
3830 synchronized (mGlobalLock) {
3831 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003832 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003833 if (top != caller) {
3834 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3835 + " is not current top " + top);
3836 return false;
3837 }
3838 if (!top.nowVisible) {
3839 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3840 + " is not visible");
3841 return false;
3842 }
3843 }
3844 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3845 token);
3846 } finally {
3847 Binder.restoreCallingIdentity(ident);
3848 }
3849 }
3850
3851 @Override
3852 public boolean isRootVoiceInteraction(IBinder token) {
3853 synchronized (mGlobalLock) {
3854 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3855 if (r == null) {
3856 return false;
3857 }
3858 return r.rootVoiceInteraction;
3859 }
3860 }
3861
Wale Ogunwalef6733932018-06-27 05:14:34 -07003862 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3863 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3864 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3865 if (activityToCallback == null) return;
3866 activityToCallback.setVoiceSessionLocked(voiceSession);
3867
3868 // Inform the activity
3869 try {
3870 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3871 voiceInteractor);
3872 long token = Binder.clearCallingIdentity();
3873 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003874 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003875 } finally {
3876 Binder.restoreCallingIdentity(token);
3877 }
3878 // TODO: VI Should we cache the activity so that it's easier to find later
3879 // rather than scan through all the stacks and activities?
3880 } catch (RemoteException re) {
3881 activityToCallback.clearVoiceSessionLocked();
3882 // TODO: VI Should this terminate the voice session?
3883 }
3884 }
3885
3886 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3887 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3888 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3889 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3890 boolean wasRunningVoice = mRunningVoice != null;
3891 mRunningVoice = session;
3892 if (!wasRunningVoice) {
3893 mVoiceWakeLock.acquire();
3894 updateSleepIfNeededLocked();
3895 }
3896 }
3897 }
3898
3899 void finishRunningVoiceLocked() {
3900 if (mRunningVoice != null) {
3901 mRunningVoice = null;
3902 mVoiceWakeLock.release();
3903 updateSleepIfNeededLocked();
3904 }
3905 }
3906
3907 @Override
3908 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3909 synchronized (mGlobalLock) {
3910 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3911 if (keepAwake) {
3912 mVoiceWakeLock.acquire();
3913 } else {
3914 mVoiceWakeLock.release();
3915 }
3916 }
3917 }
3918 }
3919
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003920 @Override
3921 public ComponentName getActivityClassForToken(IBinder token) {
3922 synchronized (mGlobalLock) {
3923 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3924 if (r == null) {
3925 return null;
3926 }
3927 return r.intent.getComponent();
3928 }
3929 }
3930
3931 @Override
3932 public String getPackageForToken(IBinder token) {
3933 synchronized (mGlobalLock) {
3934 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3935 if (r == null) {
3936 return null;
3937 }
3938 return r.packageName;
3939 }
3940 }
3941
3942 @Override
3943 public void showLockTaskEscapeMessage(IBinder token) {
3944 synchronized (mGlobalLock) {
3945 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3946 if (r == null) {
3947 return;
3948 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003949 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003950 }
3951 }
3952
3953 @Override
3954 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003955 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003956 final long token = Binder.clearCallingIdentity();
3957 try {
3958 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003959 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003960 }
3961 } finally {
3962 Binder.restoreCallingIdentity(token);
3963 }
3964 }
3965
3966 /**
3967 * Try to place task to provided position. The final position might be different depending on
3968 * current user and stacks state. The task will be moved to target stack if it's currently in
3969 * different stack.
3970 */
3971 @Override
3972 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003973 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003974 synchronized (mGlobalLock) {
3975 long ident = Binder.clearCallingIdentity();
3976 try {
3977 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3978 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003979 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003980 if (task == null) {
3981 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3982 + taskId);
3983 }
3984
Louis Chang149d5c82019-12-30 09:47:39 +08003985 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003986
3987 if (stack == null) {
3988 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3989 + stackId);
3990 }
3991 if (!stack.isActivityTypeStandardOrUndefined()) {
3992 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3993 + " the position of task " + taskId + " in/to non-standard stack");
3994 }
3995
3996 // TODO: Have the callers of this API call a separate reparent method if that is
3997 // what they intended to do vs. having this method also do reparenting.
3998 if (task.getStack() == stack) {
3999 // Change position in current stack.
4000 stack.positionChildAt(task, position);
4001 } else {
4002 // Reparent to new stack.
4003 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
4004 !DEFER_RESUME, "positionTaskInStack");
4005 }
4006 } finally {
4007 Binder.restoreCallingIdentity(ident);
4008 }
4009 }
4010 }
4011
4012 @Override
4013 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
4014 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
4015 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09004016 + Arrays.toString(horizontalSizeConfiguration) + " "
4017 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004018 synchronized (mGlobalLock) {
4019 ActivityRecord record = ActivityRecord.isInStackLocked(token);
4020 if (record == null) {
4021 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
4022 + "found for: " + token);
4023 }
4024 record.setSizeConfigurations(horizontalSizeConfiguration,
4025 verticalSizeConfigurations, smallestSizeConfigurations);
4026 }
4027 }
4028
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004029 @Override
4030 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004031 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004032 synchronized (mGlobalLock) {
4033 mSuppressResizeConfigChanges = suppress;
4034 }
4035 }
4036
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004037 /**
4038 * Moves the top activity in the input stackId to the pinned stack.
4039 *
4040 * @param stackId Id of stack to move the top activity to pinned stack.
4041 * @param bounds Bounds to use for pinned stack.
4042 *
4043 * @return True if the top activity of the input stack was successfully moved to the pinned
4044 * stack.
4045 */
4046 @Override
4047 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004048 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004049 "moveTopActivityToPinnedStack()");
4050 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004051 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004052 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4053 + "Device doesn't support picture-in-picture mode");
4054 }
4055
4056 long ident = Binder.clearCallingIdentity();
4057 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004058 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004059 } finally {
4060 Binder.restoreCallingIdentity(ident);
4061 }
4062 }
4063 }
4064
Hongwei Wang5711b8f2019-11-15 15:44:12 -08004065 @VisibleForTesting
4066 boolean isInPictureInPictureMode(ActivityRecord r) {
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004067 return r != null
4068 && r.getRootTask() != null
4069 && r.inPinnedWindowingMode()
Wale Ogunwale0db64ac2020-04-11 10:00:42 -07004070 && r.getRootTask().isInTask(r) != null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004071 }
4072
4073 @Override
4074 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4075 final long origId = Binder.clearCallingIdentity();
4076 try {
4077 synchronized (mGlobalLock) {
4078 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4079 "enterPictureInPictureMode", token, params);
4080
4081 // If the activity is already in picture in picture mode, then just return early
4082 if (isInPictureInPictureMode(r)) {
4083 return true;
4084 }
4085
4086 // Activity supports picture-in-picture, now check that we can enter PiP at this
4087 // point, if it is
4088 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4089 false /* beforeStopping */)) {
4090 return false;
4091 }
4092
4093 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004094 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004095 if (r.getParent() == null) {
4096 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4097 return;
4098 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004099 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004100 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004101 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4102 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
Louis Chang149d5c82019-12-30 09:47:39 +08004103 mRootWindowContainer.moveActivityToPinnedStack(
Hongwei Wange8e32862020-04-08 13:23:45 -07004104 r, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004105 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004106 stack.setPictureInPictureAspectRatio(aspectRatio);
4107 stack.setPictureInPictureActions(actions);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004108 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004109 };
4110
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004111 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004112 // If the keyguard is showing or occluded, then try and dismiss it before
4113 // entering picture-in-picture (this will prompt the user to authenticate if the
4114 // device is currently locked).
4115 dismissKeyguard(token, new KeyguardDismissCallback() {
4116 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004117 public void onDismissSucceeded() {
4118 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004119 }
4120 }, null /* message */);
4121 } else {
4122 // Enter picture in picture immediately otherwise
4123 enterPipRunnable.run();
4124 }
4125 return true;
4126 }
4127 } finally {
4128 Binder.restoreCallingIdentity(origId);
4129 }
4130 }
4131
4132 @Override
4133 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4134 final long origId = Binder.clearCallingIdentity();
4135 try {
4136 synchronized (mGlobalLock) {
4137 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4138 "setPictureInPictureParams", token, params);
4139
4140 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004141 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004142 if (r.inPinnedWindowingMode()) {
4143 // If the activity is already in picture-in-picture, update the pinned stack now
4144 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4145 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004146 final ActivityStack stack = r.getRootTask();
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004147 stack.setPictureInPictureAspectRatio(
4148 r.pictureInPictureArgs.getAspectRatio());
4149 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004150 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004151 }
4152 } finally {
4153 Binder.restoreCallingIdentity(origId);
4154 }
4155 }
4156
4157 @Override
4158 public int getMaxNumPictureInPictureActions(IBinder token) {
4159 // Currently, this is a static constant, but later, we may change this to be dependent on
4160 // the context of the activity
4161 return 3;
4162 }
4163
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004164 /**
4165 * Checks the state of the system and the activity associated with the given {@param token} to
4166 * verify that picture-in-picture is supported for that activity.
4167 *
4168 * @return the activity record for the given {@param token} if all the checks pass.
4169 */
4170 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4171 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004172 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004173 throw new IllegalStateException(caller
4174 + ": Device doesn't support picture-in-picture mode.");
4175 }
4176
4177 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4178 if (r == null) {
4179 throw new IllegalStateException(caller
4180 + ": Can't find activity for token=" + token);
4181 }
4182
4183 if (!r.supportsPictureInPicture()) {
4184 throw new IllegalStateException(caller
4185 + ": Current activity does not support picture-in-picture.");
4186 }
4187
4188 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004189 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004190 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004191 final float minAspectRatio = mContext.getResources().getFloat(
4192 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4193 final float maxAspectRatio = mContext.getResources().getFloat(
4194 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4195 throw new IllegalArgumentException(String.format(caller
4196 + ": Aspect ratio is too extreme (must be between %f and %f).",
4197 minAspectRatio, maxAspectRatio));
4198 }
4199
4200 // Truncate the number of actions if necessary
4201 params.truncateActions(getMaxNumPictureInPictureActions(token));
4202
4203 return r;
4204 }
4205
4206 @Override
4207 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004208 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004209 synchronized (mGlobalLock) {
4210 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4211 if (r == null) {
4212 throw new IllegalArgumentException("Activity does not exist; token="
4213 + activityToken);
4214 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004215 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004216 }
4217 }
4218
Evan Rosky73a7fe92019-11-18 18:28:01 -08004219 // TODO(b/149338177): remove when CTS no-longer requires it
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004220 @Override
4221 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4222 Rect tempDockedTaskInsetBounds,
4223 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004224 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004225 long ident = Binder.clearCallingIdentity();
4226 try {
4227 synchronized (mGlobalLock) {
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -07004228 final TaskDisplayArea tc = mRootWindowContainer.getDefaultTaskDisplayArea();
4229 final Task primary = tc.getRootSplitScreenPrimaryTask();
4230 final Task secondary = tc.getTask(t -> t.mCreatedByOrganizer && t.isRootTask()
Louis Changa009c762020-02-26 11:21:31 +08004231 && t.inSplitScreenSecondaryWindowingMode());
Evan Rosky73a7fe92019-11-18 18:28:01 -08004232 if (primary == null || secondary == null) {
4233 return;
4234 }
4235 final WindowContainerTransaction wct = new WindowContainerTransaction();
4236 final Rect primaryRect =
4237 tempDockedTaskInsetBounds != null ? tempDockedTaskInsetBounds
4238 : (tempDockedTaskBounds != null ? tempDockedTaskBounds
4239 : dockedBounds);
Wale Ogunwaleadf116e2020-03-27 16:36:01 -07004240 wct.setBounds(primary.mRemoteToken.toWindowContainerToken(), primaryRect);
Evan Rosky73a7fe92019-11-18 18:28:01 -08004241 Rect otherRect = tempOtherTaskInsetBounds != null ? tempOtherTaskInsetBounds
4242 : tempOtherTaskBounds;
4243 if (otherRect == null) {
4244 // Temporary estimation... again this is just for tests.
4245 otherRect = new Rect(secondary.getBounds());
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -07004246 if (tc.getBounds().width() > tc.getBounds().height()) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08004247 otherRect.left = primaryRect.right + 6;
4248 } else {
4249 otherRect.top = primaryRect.bottom + 6;
4250 }
4251 }
Wale Ogunwaleadf116e2020-03-27 16:36:01 -07004252 wct.setBounds(secondary.mRemoteToken.toWindowContainerToken(), otherRect);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004253 mWindowOrganizerController.applyTransaction(wct);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004254 }
4255 } finally {
4256 Binder.restoreCallingIdentity(ident);
4257 }
4258 }
4259
4260 @Override
4261 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004262 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004263 final long ident = Binder.clearCallingIdentity();
4264 try {
4265 synchronized (mGlobalLock) {
4266 mStackSupervisor.setSplitScreenResizing(resizing);
4267 }
4268 } finally {
4269 Binder.restoreCallingIdentity(ident);
4270 }
4271 }
4272
Evan Rosky0037e5f2019-11-05 10:26:24 -08004273 @Override
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004274 public IWindowOrganizerController getWindowOrganizerController() {
Evan Rosky0037e5f2019-11-05 10:26:24 -08004275 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004276 "getWindowOrganizerController()");
4277 return mWindowOrganizerController;
Evan Rosky0037e5f2019-11-05 10:26:24 -08004278 }
4279
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004280 /**
4281 * Check that we have the features required for VR-related API calls, and throw an exception if
4282 * not.
4283 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004284 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004285 if (!mContext.getPackageManager().hasSystemFeature(
4286 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4287 throw new UnsupportedOperationException("VR mode not supported on this device!");
4288 }
4289 }
4290
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004291 @Override
4292 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004293 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004294
4295 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4296
4297 ActivityRecord r;
4298 synchronized (mGlobalLock) {
4299 r = ActivityRecord.isInStackLocked(token);
4300 }
4301
4302 if (r == null) {
4303 throw new IllegalArgumentException();
4304 }
4305
4306 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004307 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004308 VrManagerInternal.NO_ERROR) {
4309 return err;
4310 }
4311
4312 // Clear the binder calling uid since this path may call moveToTask().
4313 final long callingId = Binder.clearCallingIdentity();
4314 try {
4315 synchronized (mGlobalLock) {
4316 r.requestedVrComponent = (enabled) ? packageName : null;
4317
4318 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004319 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004320 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004321 }
4322 return 0;
4323 }
4324 } finally {
4325 Binder.restoreCallingIdentity(callingId);
4326 }
4327 }
4328
4329 @Override
4330 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4331 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4332 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004333 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004334 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4335 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4336 }
Louis Changcdec0802019-11-11 11:45:07 +08004337 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004338 || activity.voiceSession != null) {
4339 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4340 return;
4341 }
4342 if (activity.pendingVoiceInteractionStart) {
4343 Slog.w(TAG, "Pending start of voice interaction already.");
4344 return;
4345 }
4346 activity.pendingVoiceInteractionStart = true;
4347 }
4348 LocalServices.getService(VoiceInteractionManagerInternal.class)
4349 .startLocalVoiceInteraction(callingActivity, options);
4350 }
4351
4352 @Override
4353 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4354 LocalServices.getService(VoiceInteractionManagerInternal.class)
4355 .stopLocalVoiceInteraction(callingActivity);
4356 }
4357
4358 @Override
4359 public boolean supportsLocalVoiceInteraction() {
4360 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4361 .supportsLocalVoiceInteraction();
4362 }
4363
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004364 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004365 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004366 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367
4368 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004369 if (mWindowManager == null) {
4370 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4371 return false;
4372 }
4373
4374 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004375 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004376 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004377 }
4378
Riddle Hsua0022cd2019-09-09 21:12:41 +08004379 mH.sendMessage(PooledLambda.obtainMessage(
4380 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4381 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004382
4383 final long origId = Binder.clearCallingIdentity();
4384 try {
4385 if (values != null) {
4386 Settings.System.clearConfiguration(values);
4387 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004388 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004389 UserHandle.USER_NULL, false /* deferResume */,
4390 mTmpUpdateConfigurationResult);
4391 return mTmpUpdateConfigurationResult.changes != 0;
4392 } finally {
4393 Binder.restoreCallingIdentity(origId);
4394 }
4395 }
4396 }
4397
4398 @Override
4399 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4400 CharSequence message) {
4401 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004402 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004403 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4404 }
4405 final long callingId = Binder.clearCallingIdentity();
4406 try {
4407 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004408 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004409 }
4410 } finally {
4411 Binder.restoreCallingIdentity(callingId);
4412 }
4413 }
4414
4415 @Override
4416 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004417 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004418 "cancelTaskWindowTransition()");
4419 final long ident = Binder.clearCallingIdentity();
4420 try {
4421 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004422 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004423 MATCH_TASK_IN_STACKS_ONLY);
4424 if (task == null) {
4425 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4426 return;
4427 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004428 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004429 }
4430 } finally {
4431 Binder.restoreCallingIdentity(ident);
4432 }
4433 }
4434
4435 @Override
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004436 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004437 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004438 final long ident = Binder.clearCallingIdentity();
4439 try {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004440 return getTaskSnapshot(taskId, isLowResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004441 } finally {
4442 Binder.restoreCallingIdentity(ident);
4443 }
4444 }
4445
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004446 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004447 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004448 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004449 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004450 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004451 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4452 if (task == null) {
4453 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4454 return null;
4455 }
4456 }
4457 // Don't call this while holding the lock as this operation might hit the disk.
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004458 return task.getSnapshot(isLowResolution, restoreFromDisk);
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004459 }
4460
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004461 @Override
4462 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4463 synchronized (mGlobalLock) {
4464 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4465 if (r == null) {
4466 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4467 + token);
4468 return;
4469 }
4470 final long origId = Binder.clearCallingIdentity();
4471 try {
4472 r.setDisablePreviewScreenshots(disable);
4473 } finally {
4474 Binder.restoreCallingIdentity(origId);
4475 }
4476 }
4477 }
4478
Riddle Hsu440f88b2019-11-06 22:17:35 +08004479 @Override
4480 public void invalidateHomeTaskSnapshot(IBinder token) {
4481 synchronized (mGlobalLock) {
4482 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4483 if (r == null || !r.isActivityTypeHome()) {
4484 return;
4485 }
4486 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4487 }
4488 }
4489
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004490 /** Return the user id of the last resumed activity. */
4491 @Override
4492 public @UserIdInt
4493 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004494 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004495 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4496 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004497 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004498 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004499 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004500 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004501 }
4502 }
4503
4504 @Override
4505 public void updateLockTaskFeatures(int userId, int flags) {
4506 final int callingUid = Binder.getCallingUid();
4507 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004508 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004509 "updateLockTaskFeatures()");
4510 }
4511 synchronized (mGlobalLock) {
4512 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4513 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004514 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004515 }
4516 }
4517
4518 @Override
4519 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4520 synchronized (mGlobalLock) {
4521 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4522 if (r == null) {
4523 return;
4524 }
4525 final long origId = Binder.clearCallingIdentity();
4526 try {
4527 r.setShowWhenLocked(showWhenLocked);
4528 } finally {
4529 Binder.restoreCallingIdentity(origId);
4530 }
4531 }
4532 }
4533
4534 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004535 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4536 synchronized (mGlobalLock) {
4537 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4538 if (r == null) {
4539 return;
4540 }
4541 final long origId = Binder.clearCallingIdentity();
4542 try {
4543 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4544 } finally {
4545 Binder.restoreCallingIdentity(origId);
4546 }
4547 }
4548 }
4549
4550 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004551 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4552 synchronized (mGlobalLock) {
4553 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4554 if (r == null) {
4555 return;
4556 }
4557 final long origId = Binder.clearCallingIdentity();
4558 try {
4559 r.setTurnScreenOn(turnScreenOn);
4560 } finally {
4561 Binder.restoreCallingIdentity(origId);
4562 }
4563 }
4564 }
4565
4566 @Override
4567 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004568 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004569 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004570 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004571 synchronized (mGlobalLock) {
4572 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4573 if (r == null) {
4574 return;
4575 }
4576 final long origId = Binder.clearCallingIdentity();
4577 try {
4578 r.registerRemoteAnimations(definition);
4579 } finally {
4580 Binder.restoreCallingIdentity(origId);
4581 }
4582 }
4583 }
4584
4585 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004586 public void unregisterRemoteAnimations(IBinder token) {
4587 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4588 "unregisterRemoteAnimations");
4589 synchronized (mGlobalLock) {
4590 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4591 if (r == null) {
4592 return;
4593 }
4594 final long origId = Binder.clearCallingIdentity();
4595 try {
4596 r.unregisterRemoteAnimations();
4597 } finally {
4598 Binder.restoreCallingIdentity(origId);
4599 }
4600 }
4601 }
4602
4603 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004604 public void registerRemoteAnimationForNextActivityStart(String packageName,
4605 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004606 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004607 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004608 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004609 synchronized (mGlobalLock) {
4610 final long origId = Binder.clearCallingIdentity();
4611 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004612 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004613 packageName, adapter);
4614 } finally {
4615 Binder.restoreCallingIdentity(origId);
4616 }
4617 }
4618 }
4619
Evan Rosky966759f2019-01-15 10:33:58 -08004620 @Override
4621 public void registerRemoteAnimationsForDisplay(int displayId,
4622 RemoteAnimationDefinition definition) {
4623 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4624 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004625 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004626 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004627 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004628 if (display == null) {
4629 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4630 return;
4631 }
4632 final long origId = Binder.clearCallingIdentity();
4633 try {
4634 display.mDisplayContent.registerRemoteAnimations(definition);
4635 } finally {
4636 Binder.restoreCallingIdentity(origId);
4637 }
4638 }
4639 }
4640
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004641 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4642 @Override
4643 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4644 synchronized (mGlobalLock) {
4645 final long origId = Binder.clearCallingIdentity();
4646 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004647 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004648 } finally {
4649 Binder.restoreCallingIdentity(origId);
4650 }
4651 }
4652 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004653
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004654 @Override
4655 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004656 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004657 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004658 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004659 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004660 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004661 }
4662 }
4663
4664 @Override
4665 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004666 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004667 != PERMISSION_GRANTED) {
4668 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4669 + Binder.getCallingPid()
4670 + ", uid=" + Binder.getCallingUid()
4671 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4672 Slog.w(TAG, msg);
4673 throw new SecurityException(msg);
4674 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004675 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004676 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004677 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004678 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004679 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004680 }
4681 }
4682
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004683 @Override
4684 public void stopAppSwitches() {
4685 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4686 synchronized (mGlobalLock) {
4687 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004688 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004689 mDidAppSwitch = false;
4690 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4691 }
4692 }
4693
4694 @Override
4695 public void resumeAppSwitches() {
4696 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4697 synchronized (mGlobalLock) {
4698 // Note that we don't execute any pending app switches... we will
4699 // let those wait until either the timeout, or the next start
4700 // activity request.
4701 mAppSwitchesAllowedTime = 0;
4702 }
4703 }
4704
Ricky Wai906af482019-06-03 17:25:28 +01004705 long getLastStopAppSwitchesTime() {
4706 return mLastStopAppSwitchesTime;
4707 }
4708
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004709 void onStartActivitySetDidAppSwitch() {
4710 if (mDidAppSwitch) {
4711 // This is the second allowed switch since we stopped switches, so now just generally
4712 // allow switches. Use case:
4713 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4714 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4715 // anyone to switch again).
4716 mAppSwitchesAllowedTime = 0;
4717 } else {
4718 mDidAppSwitch = true;
4719 }
4720 }
4721
4722 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004723 boolean shouldDisableNonVrUiLocked() {
4724 return mVrController.shouldDisableNonVrUiLocked();
4725 }
4726
Wale Ogunwale53783742018-09-16 10:21:51 -07004727 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004728 // 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 +00004729 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004730 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004731 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4732 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004733 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004734 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004735 }
4736 mH.post(() -> {
4737 if (!mVrController.onVrModeChanged(r)) {
4738 return;
4739 }
4740 synchronized (mGlobalLock) {
4741 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4742 mWindowManager.disableNonVrUi(disableNonVrUi);
4743 if (disableNonVrUi) {
4744 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4745 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004746 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004747 }
4748 }
4749 });
4750 }
4751
Wale Ogunwale53783742018-09-16 10:21:51 -07004752 @Override
4753 public int getPackageScreenCompatMode(String packageName) {
4754 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4755 synchronized (mGlobalLock) {
4756 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4757 }
4758 }
4759
4760 @Override
4761 public void setPackageScreenCompatMode(String packageName, int mode) {
4762 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4763 "setPackageScreenCompatMode");
4764 synchronized (mGlobalLock) {
4765 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4766 }
4767 }
4768
4769 @Override
4770 public boolean getPackageAskScreenCompat(String packageName) {
4771 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4772 synchronized (mGlobalLock) {
4773 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4774 }
4775 }
4776
4777 @Override
4778 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4779 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4780 "setPackageAskScreenCompat");
4781 synchronized (mGlobalLock) {
4782 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4783 }
4784 }
4785
Wale Ogunwale64258362018-10-16 15:13:37 -07004786 public static String relaunchReasonToString(int relaunchReason) {
4787 switch (relaunchReason) {
4788 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4789 return "window_resize";
4790 case RELAUNCH_REASON_FREE_RESIZE:
4791 return "free_resize";
4792 default:
4793 return null;
4794 }
4795 }
4796
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004797 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004798 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004799 }
4800
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004801 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004802 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004803 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4804 }
4805
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004806 boolean isKeyguardLocked() {
4807 return mKeyguardController.isKeyguardLocked();
4808 }
4809
Garfield Tan01548632018-11-27 10:15:48 -08004810 /**
4811 * Clears launch params for the given package.
4812 * @param packageNames the names of the packages of which the launch params are to be cleared
4813 */
4814 @Override
4815 public void clearLaunchParamsForPackages(List<String> packageNames) {
4816 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4817 "clearLaunchParamsForPackages");
4818 synchronized (mGlobalLock) {
4819 for (int i = 0; i < packageNames.size(); ++i) {
4820 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4821 }
4822 }
4823 }
4824
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004825 /**
4826 * Makes the display with the given id a single task instance display. I.e the display can only
4827 * contain one task.
4828 */
4829 @Override
4830 public void setDisplayToSingleTaskInstance(int displayId) {
4831 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4832 "setDisplayToSingleTaskInstance");
4833 final long origId = Binder.clearCallingIdentity();
4834 try {
Louis Chang677921f2019-12-06 16:44:24 +08004835 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004836 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004837 if (display != null) {
4838 display.setDisplayToSingleTaskInstance();
4839 }
4840 } finally {
4841 Binder.restoreCallingIdentity(origId);
4842 }
4843 }
4844
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004845 /**
4846 * Requests that an activity should enter picture-in-picture mode if possible.
4847 */
4848 @Override
4849 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4850 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4851 "requestPictureInPictureMode");
4852 final long origId = Binder.clearCallingIdentity();
4853 try {
4854 synchronized (mGlobalLock) {
4855 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4856 if (activity == null) {
4857 return;
4858 }
4859
jorgegil@google.com2e9cf022020-06-04 14:58:24 -07004860 if (isInPictureInPictureMode(activity)) {
4861 throw new IllegalStateException("Activity is already in PIP mode");
4862 }
4863
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004864 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4865 "requestPictureInPictureMode", /* beforeStopping */ false);
4866 if (!canEnterPictureInPicture) {
4867 throw new IllegalStateException(
4868 "Requested PIP on an activity that doesn't support it");
4869 }
4870
4871 try {
4872 final ClientTransaction transaction = ClientTransaction.obtain(
4873 activity.app.getThread(),
4874 activity.token);
4875 transaction.addCallback(EnterPipRequestedItem.obtain());
4876 getLifecycleManager().scheduleTransaction(transaction);
4877 } catch (Exception e) {
4878 Slog.w(TAG, "Failed to send enter pip requested item: "
4879 + activity.intent.getComponent(), e);
4880 }
4881 }
4882 } finally {
4883 Binder.restoreCallingIdentity(origId);
4884 }
4885 }
4886
Wale Ogunwale31913b52018-10-13 08:29:31 -07004887 void dumpLastANRLocked(PrintWriter pw) {
4888 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4889 if (mLastANRState == null) {
4890 pw.println(" <no ANR has occurred since boot>");
4891 } else {
4892 pw.println(mLastANRState);
4893 }
4894 }
4895
4896 void dumpLastANRTracesLocked(PrintWriter pw) {
4897 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4898
4899 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4900 if (ArrayUtils.isEmpty(files)) {
4901 pw.println(" <no ANR has occurred since boot>");
4902 return;
4903 }
4904 // Find the latest file.
4905 File latest = null;
4906 for (File f : files) {
4907 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4908 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004909 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004910 }
4911 pw.print("File: ");
4912 pw.print(latest.getName());
4913 pw.println();
4914 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4915 String line;
4916 while ((line = in.readLine()) != null) {
4917 pw.println(line);
4918 }
4919 } catch (IOException e) {
4920 pw.print("Unable to read: ");
4921 pw.print(e);
4922 pw.println();
4923 }
4924 }
4925
4926 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4927 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4928 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4929 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4930 }
4931
4932 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4933 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4934 pw.println(header);
4935
Louis Chang149d5c82019-12-30 09:47:39 +08004936 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004937 dumpPackage);
4938 boolean needSep = printedAnything;
4939
4940 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08004941 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Dianne Hackborn9106f2a2020-04-30 16:23:20 -07004942 " ResumedActivity: ", null);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004943 if (printed) {
4944 printedAnything = true;
4945 needSep = false;
4946 }
4947
4948 if (dumpPackage == null) {
4949 if (needSep) {
4950 pw.println();
4951 }
4952 printedAnything = true;
4953 mStackSupervisor.dump(pw, " ");
Winson Chung268eccb2020-03-26 13:43:44 -07004954 mTaskOrganizerController.dump(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004955 }
4956
4957 if (!printedAnything) {
4958 pw.println(" (nothing)");
4959 }
4960 }
4961
4962 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004963 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08004964 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004965 pw.println(" ");
4966 }
4967
4968 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4969 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4970 getActivityStartController().dump(pw, "", dumpPackage);
4971 }
4972
4973 /**
4974 * There are three things that cmd can be:
4975 * - a flattened component name that matches an existing activity
4976 * - the cmd arg isn't the flattened component name of an existing activity:
4977 * dump all activity whose component contains the cmd as a substring
4978 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004979 * <p>
4980 * The caller should not hold lock when calling this method because it will wait for the
4981 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004982 *
4983 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4984 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4985 */
4986 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4987 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4988 ArrayList<ActivityRecord> activities;
4989
4990 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004991 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004992 dumpFocusedStackOnly);
4993 }
4994
4995 if (activities.size() <= 0) {
4996 return false;
4997 }
4998
4999 String[] newArgs = new String[args.length - opti];
5000 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5001
Louis Changcdec0802019-11-11 11:45:07 +08005002 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005003 boolean needSep = false;
5004 for (int i = activities.size() - 1; i >= 0; i--) {
5005 ActivityRecord r = activities.get(i);
5006 if (needSep) {
5007 pw.println();
5008 }
5009 needSep = true;
5010 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005011 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005012 if (lastTask != task) {
5013 lastTask = task;
5014 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005015 pw.print(" id="); pw.print(lastTask.mTaskId);
5016 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005017 if (dumpAll) {
5018 lastTask.dump(pw, " ");
5019 }
5020 }
5021 }
5022 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5023 }
5024 return true;
5025 }
5026
5027 /**
5028 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5029 * there is a thread associated with the activity.
5030 */
5031 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5032 final ActivityRecord r, String[] args, boolean dumpAll) {
5033 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005034 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005035 synchronized (mGlobalLock) {
5036 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5037 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5038 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005039 if (r.hasProcess()) {
5040 pw.println(r.app.getPid());
5041 appThread = r.app.getThread();
5042 } else {
5043 pw.println("(not running)");
5044 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005045 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005046 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005047 }
5048 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005049 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005050 // flush anything that is already in the PrintWriter since the thread is going
5051 // to write to the file descriptor directly
5052 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005053 try (TransferPipe tp = new TransferPipe()) {
5054 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5055 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005056 } catch (IOException e) {
5057 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5058 } catch (RemoteException e) {
5059 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5060 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005061 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005062 }
5063
sanryhuang498e77e2018-12-06 14:57:01 +08005064 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5065 boolean testPssMode) {
5066 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5067 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5068 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
wilsonshih66071962020-07-10 10:45:23 +08005069 final int tokenSize = mRootWindowContainer.mSleepTokens.size();
5070 for (int i = 0; i < tokenSize; i++) {
5071 final RootWindowContainer.SleepToken st =
5072 mRootWindowContainer.mSleepTokens.valueAt(i);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005073 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5074 st.toString());
5075 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005076 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5077 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5078 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005079 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5080 testPssMode);
5081 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005082 }
5083
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005084 int getCurrentUserId() {
5085 return mAmInternal.getCurrentUserId();
5086 }
5087
5088 private void enforceNotIsolatedCaller(String caller) {
5089 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5090 throw new SecurityException("Isolated process not allowed to call " + caller);
5091 }
5092 }
5093
Wale Ogunwalef6733932018-06-27 05:14:34 -07005094 public Configuration getConfiguration() {
5095 Configuration ci;
5096 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005097 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005098 ci.userSetLocale = false;
5099 }
5100 return ci;
5101 }
5102
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005103 /**
5104 * Current global configuration information. Contains general settings for the entire system,
5105 * also corresponds to the merged configuration of the default display.
5106 */
5107 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005108 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005109 // while initializing process record for system, see {@link
5110 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005111 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005112 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005113 }
5114
5115 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5116 boolean initLocale) {
5117 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5118 }
5119
5120 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5121 boolean initLocale, boolean deferResume) {
5122 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5123 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5124 UserHandle.USER_NULL, deferResume);
5125 }
5126
Wale Ogunwale59507092018-10-29 09:00:30 -07005127 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005128 final long origId = Binder.clearCallingIdentity();
5129 try {
5130 synchronized (mGlobalLock) {
5131 updateConfigurationLocked(values, null, false, true, userId,
5132 false /* deferResume */);
5133 }
5134 } finally {
5135 Binder.restoreCallingIdentity(origId);
5136 }
5137 }
5138
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005139 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5140 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5141 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5142 deferResume, null /* result */);
5143 }
5144
5145 /**
5146 * Do either or both things: (1) change the current configuration, and (2)
5147 * make sure the given activity is running with the (now) current
5148 * configuration. Returns true if the activity has been left running, or
5149 * false if <var>starting</var> is being destroyed to match the new
5150 * configuration.
5151 *
5152 * @param userId is only used when persistent parameter is set to true to persist configuration
5153 * for that particular user
5154 */
5155 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5156 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5157 ActivityTaskManagerService.UpdateConfigurationResult result) {
5158 int changes = 0;
5159 boolean kept = true;
5160
Riddle Hsua0022cd2019-09-09 21:12:41 +08005161 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005162 try {
5163 if (values != null) {
5164 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5165 deferResume);
5166 }
5167
5168 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5169 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005170 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005171 }
5172
5173 if (result != null) {
5174 result.changes = changes;
5175 result.activityRelaunched = !kept;
5176 }
5177 return kept;
5178 }
5179
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005180 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005181 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005182 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005183
Louis Chang677921f2019-12-06 16:44:24 +08005184 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005185 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005186
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005187 mTempConfig.setTo(getGlobalConfiguration());
5188 final int changes = mTempConfig.updateFrom(values);
5189 if (changes == 0) {
5190 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5191 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5192 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5193 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005194 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005195 return 0;
5196 }
5197
5198 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5199 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005200 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005201 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005202 values.colorMode,
5203 values.densityDpi,
5204 values.fontScale,
5205 values.hardKeyboardHidden,
5206 values.keyboard,
5207 values.keyboardHidden,
5208 values.mcc,
5209 values.mnc,
5210 values.navigation,
5211 values.navigationHidden,
5212 values.orientation,
5213 values.screenHeightDp,
5214 values.screenLayout,
5215 values.screenWidthDp,
5216 values.smallestScreenWidthDp,
5217 values.touchscreen,
5218 values.uiMode);
5219
5220
5221 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5222 final LocaleList locales = values.getLocales();
5223 int bestLocaleIndex = 0;
5224 if (locales.size() > 1) {
5225 if (mSupportedSystemLocales == null) {
5226 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5227 }
5228 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5229 }
5230 SystemProperties.set("persist.sys.locale",
5231 locales.get(bestLocaleIndex).toLanguageTag());
5232 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005233
5234 final Message m = PooledLambda.obtainMessage(
5235 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5236 locales.get(bestLocaleIndex));
5237 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005238 }
5239
Yunfan Chen75157d72018-07-27 14:47:21 +09005240 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005241
5242 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005243 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005244
5245 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5246 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005247 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005248
5249 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005250 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005251
5252 AttributeCache ac = AttributeCache.instance();
5253 if (ac != null) {
5254 ac.updateConfiguration(mTempConfig);
5255 }
5256
5257 // Make sure all resources in our process are updated right now, so that anyone who is going
5258 // to retrieve resource values after we return will be sure to get the new ones. This is
5259 // especially important during boot, where the first config change needs to guarantee all
5260 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005261 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005262
5263 // We need another copy of global config because we're scheduling some calls instead of
5264 // running them in place. We need to be sure that object we send will be handled unchanged.
5265 final Configuration configCopy = new Configuration(mTempConfig);
5266 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005267 final Message msg = PooledLambda.obtainMessage(
5268 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5269 this, userId, configCopy);
5270 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005271 }
5272
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005273 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5274 for (int i = pidMap.size() - 1; i >= 0; i--) {
5275 final int pid = pidMap.keyAt(i);
5276 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005277 if (DEBUG_CONFIGURATION) {
5278 Slog.v(TAG_CONFIGURATION, "Update process config of "
5279 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005280 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005281 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005282 }
5283
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005284 final Message msg = PooledLambda.obtainMessage(
5285 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5286 mAmInternal, changes, initLocale);
5287 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005288
5289 // Override configuration of the default display duplicates global config, so we need to
5290 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005291 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005292 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005293
5294 return changes;
5295 }
5296
Riddle Hsua0022cd2019-09-09 21:12:41 +08005297 /** @see WindowSurfacePlacer#deferLayout */
5298 void deferWindowLayout() {
5299 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5300 // Reset the reasons at the first entrance because we only care about the changes in the
5301 // deferred scope.
5302 mLayoutReasons = 0;
5303 }
5304
5305 mWindowManager.mWindowPlacerLocked.deferLayout();
5306 }
5307
5308 /** @see WindowSurfacePlacer#continueLayout */
5309 void continueWindowLayout() {
5310 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5311 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5312 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5313 }
5314 }
5315
5316 /**
5317 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5318 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5319 * defer count is gone.
5320 */
5321 void addWindowLayoutReasons(@LayoutReason int reasons) {
5322 mLayoutReasons |= reasons;
5323 }
5324
Wale Ogunwalef6733932018-06-27 05:14:34 -07005325 private void updateEventDispatchingLocked(boolean booted) {
5326 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5327 }
5328
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005329 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5330 final ContentResolver resolver = mContext.getContentResolver();
5331 Settings.System.putConfigurationForUser(resolver, config, userId);
5332 }
5333
5334 private void sendLocaleToMountDaemonMsg(Locale l) {
5335 try {
5336 IBinder service = ServiceManager.getService("mount");
5337 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5338 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5339 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5340 } catch (RemoteException e) {
5341 Log.e(TAG, "Error storing locale for decryption UI", e);
5342 }
5343 }
5344
Alison Cichowlas3e340502018-08-07 17:15:01 -04005345 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5346 mStartActivitySources.remove(permissionToken);
5347 mExpiredStartAsCallerTokens.add(permissionToken);
5348 }
5349
5350 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5351 mExpiredStartAsCallerTokens.remove(permissionToken);
5352 }
5353
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005354 boolean isActivityStartsLoggingEnabled() {
5355 return mAmInternal.isActivityStartsLoggingEnabled();
5356 }
5357
Michal Karpinski8596ded2018-11-14 14:43:48 +00005358 boolean isBackgroundActivityStartsEnabled() {
5359 return mAmInternal.isBackgroundActivityStartsEnabled();
5360 }
5361
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005362 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5363 if (r == null || !r.hasProcess()) {
5364 return KEY_DISPATCHING_TIMEOUT_MS;
5365 }
5366 return getInputDispatchingTimeoutLocked(r.app);
5367 }
5368
5369 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005370 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005371 }
5372
Wale Ogunwalef6733932018-06-27 05:14:34 -07005373 /**
5374 * Decide based on the configuration whether we should show the ANR,
5375 * crash, etc dialogs. The idea is that if there is no affordance to
5376 * press the on-screen buttons, or the user experience would be more
5377 * greatly impacted than the crash itself, we shouldn't show the dialog.
5378 *
5379 * A thought: SystemUI might also want to get told about this, the Power
5380 * dialog / global actions also might want different behaviors.
5381 */
5382 private void updateShouldShowDialogsLocked(Configuration config) {
5383 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5384 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5385 && config.navigation == Configuration.NAVIGATION_NONAV);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005386 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5387 HIDE_ERROR_DIALOGS, 0) != 0;
Yuncheol Heo5d9b2712020-04-16 17:31:32 -07005388 mShowDialogs = inputMethodExists
Nikolas Havrikov7771e6e2020-06-19 11:45:34 +02005389 && ActivityTaskManager.currentUiModeSupportsErrorDialogs(config)
Yuncheol Heo5d9b2712020-04-16 17:31:32 -07005390 && !hideDialogsSet;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005391 }
5392
5393 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5394 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5395 FONT_SCALE, 1.0f, userId);
5396
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005397 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005398 if (getGlobalConfiguration().fontScale == scaleFactor) {
5399 return;
5400 }
5401
5402 final Configuration configuration
5403 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5404 configuration.fontScale = scaleFactor;
5405 updatePersistentConfiguration(configuration, userId);
5406 }
5407 }
5408
5409 // Actually is sleeping or shutting down or whatever else in the future
5410 // is an inactive state.
5411 boolean isSleepingOrShuttingDownLocked() {
5412 return isSleepingLocked() || mShuttingDown;
5413 }
5414
5415 boolean isSleepingLocked() {
5416 return mSleeping;
5417 }
5418
Riddle Hsu16567132018-08-16 21:37:47 +08005419 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005420 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005421 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005422 if (task.isActivityTypeStandard()) {
5423 if (mCurAppTimeTracker != r.appTimeTracker) {
5424 // We are switching app tracking. Complete the current one.
5425 if (mCurAppTimeTracker != null) {
5426 mCurAppTimeTracker.stop();
5427 mH.obtainMessage(
5428 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005429 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005430 mCurAppTimeTracker = null;
5431 }
5432 if (r.appTimeTracker != null) {
5433 mCurAppTimeTracker = r.appTimeTracker;
5434 startTimeTrackingFocusedActivityLocked();
5435 }
5436 } else {
5437 startTimeTrackingFocusedActivityLocked();
5438 }
5439 } else {
5440 r.appTimeTracker = null;
5441 }
5442 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5443 // TODO: Probably not, because we don't want to resume voice on switching
5444 // back to this activity
5445 if (task.voiceInteractor != null) {
5446 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5447 } else {
5448 finishRunningVoiceLocked();
5449
5450 if (mLastResumedActivity != null) {
5451 final IVoiceInteractionSession session;
5452
Louis Changcdec0802019-11-11 11:45:07 +08005453 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005454 if (lastResumedActivityTask != null
5455 && lastResumedActivityTask.voiceSession != null) {
5456 session = lastResumedActivityTask.voiceSession;
5457 } else {
5458 session = mLastResumedActivity.voiceSession;
5459 }
5460
5461 if (session != null) {
5462 // We had been in a voice interaction session, but now focused has
5463 // move to something different. Just finish the session, we can't
5464 // return to it and retain the proper state and synchronization with
5465 // the voice interaction service.
5466 finishVoiceTask(session);
5467 }
5468 }
5469 }
5470
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005471 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5472 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005473 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005474 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5475
Wale Ogunwalef6733932018-06-27 05:14:34 -07005476 updateResumedAppTrace(r);
5477 mLastResumedActivity = r;
5478
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005479 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005480
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005481 if (prevTask == null || task != prevTask) {
5482 if (prevTask != null) {
5483 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5484 }
5485 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5486 }
5487
Wale Ogunwalef6733932018-06-27 05:14:34 -07005488 applyUpdateLockStateLocked(r);
5489 applyUpdateVrModeLocked(r);
5490
Jeff Changd136e772019-11-05 20:33:52 +08005491 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005492 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005493 r == null ? "NULL" : r.shortComponentName,
5494 reason);
5495 }
5496
wilsonshih66071962020-07-10 10:45:23 +08005497 final class SleepTokenAcquirerImpl implements ActivityTaskManagerInternal.SleepTokenAcquirer {
5498 private final String mTag;
5499 private final SparseArray<RootWindowContainer.SleepToken> mSleepTokens =
5500 new SparseArray<>();
5501
5502 SleepTokenAcquirerImpl(@NonNull String tag) {
5503 mTag = tag;
5504 }
5505
5506 @Override
5507 public void acquire(int displayId) {
5508 synchronized (mGlobalLock) {
5509 if (!mSleepTokens.contains(displayId)) {
5510 mSleepTokens.append(displayId,
5511 mRootWindowContainer.createSleepToken(mTag, displayId));
5512 updateSleepIfNeededLocked();
5513 }
5514 }
5515 }
5516
5517 @Override
5518 public void release(int displayId) {
5519 synchronized (mGlobalLock) {
5520 final RootWindowContainer.SleepToken token = mSleepTokens.get(displayId);
5521 if (token != null) {
5522 mRootWindowContainer.removeSleepToken(token);
5523 mSleepTokens.remove(displayId);
5524 }
5525 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005526 }
5527 }
5528
5529 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005530 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005531 final boolean wasSleeping = mSleeping;
5532 boolean updateOomAdj = false;
5533
5534 if (!shouldSleep) {
5535 // If wasSleeping is true, we need to wake up activity manager state from when
5536 // we started sleeping. In either case, we need to apply the sleep tokens, which
5537 // will wake up stacks or put them to sleep as appropriate.
5538 if (wasSleeping) {
5539 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005540 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5541 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005542 startTimeTrackingFocusedActivityLocked();
5543 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005544 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005545 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5546 }
Louis Chang149d5c82019-12-30 09:47:39 +08005547 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005548 if (wasSleeping) {
5549 updateOomAdj = true;
5550 }
5551 } else if (!mSleeping && shouldSleep) {
5552 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005553 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5554 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005555 if (mCurAppTimeTracker != null) {
5556 mCurAppTimeTracker.stop();
5557 }
5558 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005559 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005560 mStackSupervisor.goingToSleepLocked();
5561 updateResumedAppTrace(null /* resumed */);
5562 updateOomAdj = true;
5563 }
5564 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005565 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005566 }
5567 }
5568
5569 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005570 mH.removeCallbacks(mUpdateOomAdjRunnable);
5571 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005572 }
5573
Wale Ogunwale53783742018-09-16 10:21:51 -07005574 void updateCpuStats() {
5575 mH.post(mAmInternal::updateCpuStats);
5576 }
5577
Hui Yu03d12402018-12-06 18:00:37 -08005578 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5579 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005580 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5581 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005582 mH.sendMessage(m);
5583 }
5584
Hui Yu03d12402018-12-06 18:00:37 -08005585 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005586 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005587 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005588 if (task != null) {
5589 final ActivityRecord rootActivity = task.getRootActivity();
5590 if (rootActivity != null) {
5591 taskRoot = rootActivity.mActivityComponent;
5592 }
5593 }
5594
Hui Yu03d12402018-12-06 18:00:37 -08005595 final Message m = PooledLambda.obtainMessage(
5596 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005597 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005598 mH.sendMessage(m);
5599 }
5600
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005601 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5602 String hostingType) {
5603 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005604 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5605 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005606 + activity.processName);
5607 }
5608 // Post message to start process to avoid possible deadlock of calling into AMS with the
5609 // ATMS lock held.
5610 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5611 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5612 isTop, hostingType, activity.intent.getComponent());
5613 mH.sendMessage(m);
5614 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005615 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005616 }
5617 }
5618
Wale Ogunwale53783742018-09-16 10:21:51 -07005619 void setBooting(boolean booting) {
5620 mAmInternal.setBooting(booting);
5621 }
5622
5623 boolean isBooting() {
5624 return mAmInternal.isBooting();
5625 }
5626
5627 void setBooted(boolean booted) {
5628 mAmInternal.setBooted(booted);
5629 }
5630
5631 boolean isBooted() {
5632 return mAmInternal.isBooted();
5633 }
5634
5635 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5636 mH.post(() -> {
5637 if (finishBooting) {
5638 mAmInternal.finishBooting();
5639 }
5640 if (enableScreen) {
5641 mInternal.enableScreenAfterBoot(isBooted());
5642 }
5643 });
5644 }
5645
5646 void setHeavyWeightProcess(ActivityRecord root) {
5647 mHeavyWeightProcess = root.app;
5648 final Message m = PooledLambda.obtainMessage(
5649 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005650 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005651 mH.sendMessage(m);
5652 }
5653
5654 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5655 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5656 return;
5657 }
5658
5659 mHeavyWeightProcess = null;
5660 final Message m = PooledLambda.obtainMessage(
5661 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5662 proc.mUserId);
5663 mH.sendMessage(m);
5664 }
5665
5666 private void cancelHeavyWeightProcessNotification(int userId) {
5667 final INotificationManager inm = NotificationManager.getService();
5668 if (inm == null) {
5669 return;
5670 }
5671 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005672 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005673 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5674 } catch (RuntimeException e) {
5675 Slog.w(TAG, "Error canceling notification for service", e);
5676 } catch (RemoteException e) {
5677 }
5678
5679 }
5680
5681 private void postHeavyWeightProcessNotification(
5682 WindowProcessController proc, Intent intent, int userId) {
5683 if (proc == null) {
5684 return;
5685 }
5686
5687 final INotificationManager inm = NotificationManager.getService();
5688 if (inm == null) {
5689 return;
5690 }
5691
5692 try {
5693 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5694 String text = mContext.getString(R.string.heavy_weight_notification,
5695 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5696 Notification notification =
5697 new Notification.Builder(context,
5698 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5699 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5700 .setWhen(0)
5701 .setOngoing(true)
5702 .setTicker(text)
5703 .setColor(mContext.getColor(
5704 com.android.internal.R.color.system_notification_accent_color))
5705 .setContentTitle(text)
5706 .setContentText(
5707 mContext.getText(R.string.heavy_weight_notification_detail))
5708 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5709 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5710 new UserHandle(userId)))
5711 .build();
5712 try {
5713 inm.enqueueNotificationWithTag("android", "android", null,
5714 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5715 } catch (RuntimeException e) {
5716 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5717 } catch (RemoteException e) {
5718 }
5719 } catch (PackageManager.NameNotFoundException e) {
5720 Slog.w(TAG, "Unable to create context for heavy notification", e);
5721 }
5722
5723 }
5724
Philip P. Moltmannee295092020-02-10 08:46:26 -08005725 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5726 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5727 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005728
5729 ActivityRecord activity = null;
5730 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5731 activity = ActivityRecord.isInStackLocked(token);
5732 if (activity == null) {
5733 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5734 return null;
5735 }
5736 if (activity.finishing) {
5737 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5738 return null;
5739 }
5740 }
5741
5742 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005743 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5744 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005745 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5746 if (noCreate) {
5747 return rec;
5748 }
5749 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5750 if (activity.pendingResults == null) {
5751 activity.pendingResults = new HashSet<>();
5752 }
5753 activity.pendingResults.add(rec.ref);
5754 }
5755 return rec;
5756 }
5757
Andrii Kulian52d255c2018-07-13 11:32:19 -07005758 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005759 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005760 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005761 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5762 mCurAppTimeTracker.start(resumedActivity.packageName);
5763 }
5764 }
5765
5766 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5767 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005768 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005769 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5770 }
5771 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005772 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005773 constructResumedTraceName(resumed.packageName), 0);
5774 }
5775 mTracedResumedActivity = resumed;
5776 }
5777
5778 private String constructResumedTraceName(String packageName) {
5779 return "focused app: " + packageName;
5780 }
5781
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005782 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005783 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005784 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005785 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005786 // mainStack is null during startup.
5787 if (mainStack != null) {
5788 if (changes != 0 && starting == null) {
5789 // If the configuration changed, and the caller is not already
5790 // in the process of starting an activity, then find the top
5791 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005792 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005793 }
5794
5795 if (starting != null) {
5796 kept = starting.ensureActivityConfiguration(changes,
5797 false /* preserveWindow */);
5798 // And we need to make sure at this point that all other activities
5799 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005800 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005801 !PRESERVE_WINDOWS);
5802 }
5803 }
5804
5805 return kept;
5806 }
5807
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005808 void scheduleAppGcsLocked() {
5809 mH.post(() -> mAmInternal.scheduleAppGcs());
5810 }
5811
Wale Ogunwale53783742018-09-16 10:21:51 -07005812 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5813 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5814 }
5815
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005816 /**
5817 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5818 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5819 * on demand.
5820 */
5821 IPackageManager getPackageManager() {
5822 return AppGlobals.getPackageManager();
5823 }
5824
5825 PackageManagerInternal getPackageManagerInternalLocked() {
5826 if (mPmInternal == null) {
5827 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5828 }
5829 return mPmInternal;
5830 }
5831
Darryl L Johnsona0982222020-02-18 18:21:51 -08005832 ComponentName getSysUiServiceComponentLocked() {
5833 if (mSysUiServiceComponent == null) {
5834 final PackageManagerInternal pm = getPackageManagerInternalLocked();
5835 mSysUiServiceComponent = pm.getSystemUiServiceComponent();
5836 }
5837 return mSysUiServiceComponent;
5838 }
5839
Hai Zhangf4da9be2019-05-01 13:46:06 +08005840 PermissionPolicyInternal getPermissionPolicyInternal() {
5841 if (mPermissionPolicyInternal == null) {
5842 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5843 }
5844 return mPermissionPolicyInternal;
5845 }
5846
Wale Ogunwale008163e2018-07-23 23:11:08 -07005847 AppWarnings getAppWarningsLocked() {
5848 return mAppWarnings;
5849 }
5850
Wale Ogunwale214f3482018-10-04 11:00:47 -07005851 Intent getHomeIntent() {
5852 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5853 intent.setComponent(mTopComponent);
5854 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5855 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5856 intent.addCategory(Intent.CATEGORY_HOME);
5857 }
5858 return intent;
5859 }
5860
Chilun2ef71f72018-11-16 17:57:15 +08005861 /**
5862 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5863 * activities.
5864 *
Chilun939b05c2020-02-19 14:50:59 +08005865 * @param preferredPackage Specify a preferred package name, otherwise use the package name
5866 * defined in config_secondaryHomePackage.
Chilun2ef71f72018-11-16 17:57:15 +08005867 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5868 */
5869 Intent getSecondaryHomeIntent(String preferredPackage) {
5870 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005871 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5872 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5873 if (preferredPackage == null || useSystemProvidedLauncher) {
Chilun939b05c2020-02-19 14:50:59 +08005874 // Using the package name stored in config if no preferred package name or forced.
5875 final String secondaryHomePackage = mContext.getResources().getString(
5876 com.android.internal.R.string.config_secondaryHomePackage);
5877 intent.setPackage(secondaryHomePackage);
Chilun2ef71f72018-11-16 17:57:15 +08005878 } else {
5879 intent.setPackage(preferredPackage);
5880 }
5881 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5882 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5883 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5884 }
5885 return intent;
5886 }
5887
Wale Ogunwale214f3482018-10-04 11:00:47 -07005888 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5889 if (info == null) return null;
5890 ApplicationInfo newInfo = new ApplicationInfo(info);
5891 newInfo.initForUser(userId);
5892 return newInfo;
5893 }
5894
Wale Ogunwale9c103022018-10-18 07:44:54 -07005895 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005896 if (uid == SYSTEM_UID) {
5897 // The system gets to run in any process. If there are multiple processes with the same
5898 // uid, just pick the first (this should never happen).
5899 final SparseArray<WindowProcessController> procs =
5900 mProcessNames.getMap().get(processName);
5901 if (procs == null) return null;
5902 final int procCount = procs.size();
5903 for (int i = 0; i < procCount; i++) {
5904 final int procUid = procs.keyAt(i);
5905 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5906 // Don't use an app process or different user process for system component.
5907 continue;
5908 }
5909 return procs.valueAt(i);
5910 }
5911 }
5912
5913 return mProcessNames.get(processName, uid);
5914 }
5915
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005916 WindowProcessController getProcessController(IApplicationThread thread) {
5917 if (thread == null) {
5918 return null;
5919 }
5920
5921 final IBinder threadBinder = thread.asBinder();
5922 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5923 for (int i = pmap.size()-1; i >= 0; i--) {
5924 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5925 for (int j = procs.size() - 1; j >= 0; j--) {
5926 final WindowProcessController proc = procs.valueAt(j);
5927 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5928 return proc;
5929 }
5930 }
5931 }
5932
5933 return null;
5934 }
5935
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005936 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005937 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005938 if (proc == null) return null;
5939 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5940 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005941 }
5942 return null;
5943 }
5944
Riddle Hsua0536432019-02-16 00:38:59 +08005945 int getUidState(int uid) {
5946 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005947 }
5948
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005949 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005950 // A uid is considered to be foreground if it has a visible non-toast window.
5951 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005952 }
5953
Ricky Wai96f5c352019-04-10 18:40:17 +01005954 boolean isDeviceOwner(int uid) {
5955 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005956 }
5957
Ricky Wai96f5c352019-04-10 18:40:17 +01005958 void setDeviceOwnerUid(int uid) {
5959 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005960 }
5961
Wale Ogunwale9de19442018-10-18 19:05:03 -07005962 /**
5963 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5964 * the whitelist
5965 */
5966 String getPendingTempWhitelistTagForUidLocked(int uid) {
5967 return mPendingTempWhitelist.get(uid);
5968 }
5969
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005970 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5971 if (true || Build.IS_USER) {
5972 return;
5973 }
5974
5975 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5976 StrictMode.allowThreadDiskWrites();
5977 try {
5978 File tracesDir = new File("/data/anr");
5979 File tracesFile = null;
5980 try {
5981 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5982
5983 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005984 String timeString =
5985 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5986 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005987 sb.append(": ");
5988 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5989 sb.append(" since ");
5990 sb.append(msg);
5991 FileOutputStream fos = new FileOutputStream(tracesFile);
5992 fos.write(sb.toString().getBytes());
5993 if (app == null) {
5994 fos.write("\n*** No application process!".getBytes());
5995 }
5996 fos.close();
5997 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5998 } catch (IOException e) {
5999 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6000 return;
6001 }
6002
6003 if (app != null && app.getPid() > 0) {
6004 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6005 firstPids.add(app.getPid());
6006 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6007 }
6008
6009 File lastTracesFile = null;
6010 File curTracesFile = null;
6011 for (int i=9; i>=0; i--) {
6012 String name = String.format(Locale.US, "slow%02d.txt", i);
6013 curTracesFile = new File(tracesDir, name);
6014 if (curTracesFile.exists()) {
6015 if (lastTracesFile != null) {
6016 curTracesFile.renameTo(lastTracesFile);
6017 } else {
6018 curTracesFile.delete();
6019 }
6020 }
6021 lastTracesFile = curTracesFile;
6022 }
6023 tracesFile.renameTo(curTracesFile);
6024 } finally {
6025 StrictMode.setThreadPolicy(oldPolicy);
6026 }
6027 }
6028
Michal Karpinskida34cd42019-04-02 19:46:52 +01006029 boolean isAssociatedCompanionApp(int userId, int uid) {
6030 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6031 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006032 return false;
6033 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006034 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006035 }
6036
Issei Suzuki734bc942019-06-05 13:59:52 +02006037 void notifySingleTaskDisplayEmpty(int displayId) {
6038 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6039 }
6040
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006041 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006042 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006043
6044
Wale Ogunwale98875612018-10-12 07:53:02 -07006045 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6046 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006047
Riddle Hsud93a6c42018-11-29 21:50:06 +08006048 H(Looper looper) {
6049 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006050 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006051
6052 @Override
6053 public void handleMessage(Message msg) {
6054 switch (msg.what) {
6055 case REPORT_TIME_TRACKER_MSG: {
6056 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6057 tracker.deliverResult(mContext);
6058 } break;
6059 }
6060 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006061 }
6062
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006063 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006064 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006065
6066 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006067 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006068 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006069
6070 @Override
6071 public void handleMessage(Message msg) {
6072 switch (msg.what) {
6073 case DISMISS_DIALOG_UI_MSG: {
6074 final Dialog d = (Dialog) msg.obj;
6075 d.dismiss();
6076 break;
6077 }
6078 }
6079 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006080 }
6081
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006082 final class LocalService extends ActivityTaskManagerInternal {
6083 @Override
wilsonshih66071962020-07-10 10:45:23 +08006084 public SleepTokenAcquirer createSleepTokenAcquirer(@NonNull String tag) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006085 Objects.requireNonNull(tag);
wilsonshih66071962020-07-10 10:45:23 +08006086 return new SleepTokenAcquirerImpl(tag);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006087 }
6088
6089 @Override
6090 public ComponentName getHomeActivityForUser(int userId) {
6091 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006092 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006093 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006094 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006095 }
6096 }
6097
6098 @Override
6099 public void onLocalVoiceInteractionStarted(IBinder activity,
6100 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6101 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006102 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006103 }
6104 }
6105
6106 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006107 public void notifySingleTaskDisplayDrawn(int displayId) {
6108 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6109 }
6110
6111 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006112 public List<IBinder> getTopVisibleActivities() {
6113 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006114 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006115 }
6116 }
6117
6118 @Override
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00006119 public boolean hasResumedActivity(int uid) {
6120 synchronized (mGlobalLock) {
6121 final ArraySet<WindowProcessController> processes = mProcessMap.getProcesses(uid);
6122 for (int i = 0, n = processes.size(); i < n; i++) {
6123 final WindowProcessController process = processes.valueAt(i);
6124 if (process.hasResumedActivity()) {
6125 return true;
6126 }
6127 }
6128 }
6129 return false;
6130 }
6131
6132 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006133 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6134 int userId, Intent[] intents, Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006135 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006136 final String[] resolvedTypes = new String[intents.length];
6137
6138 // UID of the package on user userId.
6139 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6140 // packageUid may not be initialized.
6141 int packageUid = 0;
6142 final long ident = Binder.clearCallingIdentity();
6143
6144 try {
6145 for (int i = 0; i < intents.length; i++) {
6146 resolvedTypes[i] =
6147 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6148 }
6149
6150 packageUid = AppGlobals.getPackageManager().getPackageUid(
6151 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6152 } catch (RemoteException e) {
6153 // Shouldn't happen.
6154 } finally {
6155 Binder.restoreCallingIdentity(ident);
6156 }
6157
Riddle Hsu591bf612019-02-14 17:55:31 +08006158 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006159 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006160 intents, resolvedTypes, null /* resultTo */,
6161 SafeActivityOptions.fromBundle(bOptions), userId,
6162 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6163 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006164 }
6165
6166 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006167 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006168 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6169 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6170 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006171 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006172 assertPackageMatchesCallingUid(callingPackage);
Jeff Sharkey1d1e7532020-06-03 13:05:01 -06006173 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6174 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6175 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
6176 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006177 }
6178
6179 @Override
6180 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006181 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6182 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6183 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6184 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006185 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006186 assertPackageMatchesCallingUid(callingPackage);
Jeff Sharkey1d1e7532020-06-03 13:05:01 -06006187 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6188 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6189 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6190 reason, validateIncomingUser, originatingPendingIntent,
6191 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006192 }
6193
6194 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006195 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006196 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6197 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006198 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006199 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006200 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006201 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006202 false /*validateIncomingUser*/);
6203 }
6204
6205 @Override
lumark588a3e82018-07-20 18:53:54 +08006206 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006207 synchronized (mGlobalLock) {
6208
6209 // We might change the visibilities here, so prepare an empty app transition which
6210 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006211 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006212 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006213 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006214 return;
6215 }
Louis Chang677921f2019-12-06 16:44:24 +08006216 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006217 final boolean wasTransitionSet =
6218 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006219 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006220 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006221 }
Louis Chang149d5c82019-12-30 09:47:39 +08006222 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006223
6224 // If there was a transition set already we don't want to interfere with it as we
6225 // might be starting it too early.
6226 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006227 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006228 }
6229 }
6230 if (callback != null) {
6231 callback.run();
6232 }
6233 }
6234
6235 @Override
6236 public void notifyKeyguardTrustedChanged() {
6237 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006238 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006239 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006240 }
6241 }
6242 }
6243
6244 /**
6245 * Called after virtual display Id is updated by
6246 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6247 * {@param vrVr2dDisplayId}.
6248 */
6249 @Override
6250 public void setVr2dDisplayId(int vr2dDisplayId) {
6251 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6252 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006253 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006254 }
6255 }
6256
6257 @Override
6258 public void setFocusedActivity(IBinder token) {
6259 synchronized (mGlobalLock) {
6260 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6261 if (r == null) {
6262 throw new IllegalArgumentException(
6263 "setFocusedActivity: No activity record matching token=" + token);
6264 }
Louis Chang19443452018-10-09 12:10:21 +08006265 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006266 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006267 }
6268 }
6269 }
6270
6271 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006272 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006273 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006274 }
6275
6276 @Override
6277 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006278 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006279 }
6280
6281 @Override
6282 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006283 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006284 }
6285
6286 @Override
6287 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6288 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6289 }
6290
6291 @Override
6292 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006293 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006294 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006295
6296 @Override
6297 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6298 synchronized (mGlobalLock) {
6299 mActiveVoiceInteractionServiceComponent = component;
6300 }
6301 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006302
6303 @Override
Galia Peycheva480275a2020-03-18 17:33:42 +01006304 public void notifyDreamStateChanged(boolean dreaming) {
6305 synchronized (mGlobalLock) {
6306 mDreaming = dreaming;
6307 }
6308 }
6309
6310 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006311 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6312 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6313 return;
6314 }
6315 synchronized (mGlobalLock) {
6316 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6317 if (types == null) {
6318 if (uid < 0) {
6319 return;
6320 }
6321 types = new ArrayMap<>();
6322 mAllowAppSwitchUids.put(userId, types);
6323 }
6324 if (uid < 0) {
6325 types.remove(type);
6326 } else {
6327 types.put(type, uid);
6328 }
6329 }
6330 }
6331
6332 @Override
6333 public void onUserStopped(int userId) {
6334 synchronized (mGlobalLock) {
6335 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6336 mAllowAppSwitchUids.remove(userId);
6337 }
6338 }
6339
6340 @Override
6341 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6342 synchronized (mGlobalLock) {
6343 return ActivityTaskManagerService.this.isGetTasksAllowed(
6344 caller, callingPid, callingUid);
6345 }
6346 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006347
Riddle Hsua0536432019-02-16 00:38:59 +08006348 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006349 @Override
6350 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006351 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006352 mProcessNames.put(proc.mName, proc.mUid, proc);
6353 }
6354 }
6355
Riddle Hsua0536432019-02-16 00:38:59 +08006356 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006357 @Override
6358 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006359 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006360 mProcessNames.remove(name, uid);
6361 }
6362 }
6363
Riddle Hsua0536432019-02-16 00:38:59 +08006364 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006365 @Override
6366 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006367 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006368 if (proc == mHomeProcess) {
6369 mHomeProcess = null;
6370 }
6371 if (proc == mPreviousProcess) {
6372 mPreviousProcess = null;
6373 }
6374 }
6375 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006376
Riddle Hsua0536432019-02-16 00:38:59 +08006377 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006378 @Override
6379 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006380 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006381 return mTopProcessState;
6382 }
6383 }
6384
Riddle Hsua0536432019-02-16 00:38:59 +08006385 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006386 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006387 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006388 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006389 return proc == mHeavyWeightProcess;
6390 }
6391 }
6392
Riddle Hsua0536432019-02-16 00:38:59 +08006393 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006394 @Override
6395 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006396 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006397 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6398 }
6399 }
6400
6401 @Override
6402 public void finishHeavyWeightApp() {
6403 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006404 if (mHeavyWeightProcess != null) {
6405 mHeavyWeightProcess.finishActivities();
6406 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006407 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6408 mHeavyWeightProcess);
6409 }
6410 }
6411
Galia Peycheva480275a2020-03-18 17:33:42 +01006412 @Override
6413 public boolean isDreaming() {
6414 synchronized (mGlobalLock) {
6415 return mDreaming;
6416 }
6417 }
6418
Riddle Hsua0536432019-02-16 00:38:59 +08006419 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006420 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006421 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006422 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006423 return isSleepingLocked();
6424 }
6425 }
6426
6427 @Override
6428 public boolean isShuttingDown() {
6429 synchronized (mGlobalLock) {
6430 return mShuttingDown;
6431 }
6432 }
6433
6434 @Override
6435 public boolean shuttingDown(boolean booted, int timeout) {
6436 synchronized (mGlobalLock) {
6437 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006438 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006439 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006440 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006441 return mStackSupervisor.shutdownLocked(timeout);
6442 }
6443 }
6444
6445 @Override
6446 public void enableScreenAfterBoot(boolean booted) {
bepheis gaoa312f812020-08-10 22:20:47 +08006447 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
6448 mWindowManager.enableScreenAfterBoot();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006449 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006450 updateEventDispatchingLocked(booted);
6451 }
6452 }
6453
6454 @Override
6455 public boolean showStrictModeViolationDialog() {
6456 synchronized (mGlobalLock) {
6457 return mShowDialogs && !mSleeping && !mShuttingDown;
6458 }
6459 }
6460
6461 @Override
6462 public void showSystemReadyErrorDialogsIfNeeded() {
6463 synchronized (mGlobalLock) {
6464 try {
6465 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6466 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6467 + " data partition or your device will be unstable.");
6468 mUiHandler.post(() -> {
6469 if (mShowDialogs) {
6470 AlertDialog d = new BaseErrorDialog(mUiContext);
6471 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6472 d.setCancelable(false);
6473 d.setTitle(mUiContext.getText(R.string.android_system_label));
6474 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6475 d.setButton(DialogInterface.BUTTON_POSITIVE,
6476 mUiContext.getText(R.string.ok),
6477 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6478 d.show();
6479 }
6480 });
6481 }
6482 } catch (RemoteException e) {
6483 }
6484
6485 if (!Build.isBuildConsistent()) {
6486 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6487 mUiHandler.post(() -> {
6488 if (mShowDialogs) {
6489 AlertDialog d = new BaseErrorDialog(mUiContext);
6490 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6491 d.setCancelable(false);
6492 d.setTitle(mUiContext.getText(R.string.android_system_label));
6493 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6494 d.setButton(DialogInterface.BUTTON_POSITIVE,
6495 mUiContext.getText(R.string.ok),
6496 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6497 d.show();
6498 }
6499 });
6500 }
6501 }
6502 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006503
6504 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006505 public void onProcessMapped(int pid, WindowProcessController proc) {
6506 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006507 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006508 }
6509 }
6510
6511 @Override
6512 public void onProcessUnMapped(int pid) {
6513 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006514 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006515 }
6516 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006517
6518 @Override
6519 public void onPackageDataCleared(String name) {
6520 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006521 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006522 mAppWarnings.onPackageDataCleared(name);
6523 }
6524 }
6525
6526 @Override
6527 public void onPackageUninstalled(String name) {
6528 synchronized (mGlobalLock) {
6529 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006530 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006531 }
6532 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006533
6534 @Override
6535 public void onPackageAdded(String name, boolean replacing) {
6536 synchronized (mGlobalLock) {
6537 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6538 }
6539 }
6540
6541 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006542 public void onPackageReplaced(ApplicationInfo aInfo) {
6543 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006544 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006545 }
6546 }
6547
6548 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006549 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6550 synchronized (mGlobalLock) {
6551 return compatibilityInfoForPackageLocked(ai);
6552 }
6553 }
6554
Yunfan Chen75157d72018-07-27 14:47:21 +09006555 /**
6556 * Set the corresponding display information for the process global configuration. To be
6557 * called when we need to show IME on a different display.
6558 *
6559 * @param pid The process id associated with the IME window.
6560 * @param displayId The ID of the display showing the IME.
6561 */
6562 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006563 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006564 // Don't update process-level configuration for Multi-Client IME process since other
6565 // IMEs on other displays will also receive this configuration change due to IME
6566 // services use the same application config/context.
6567 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006568
Yunfan Chen75157d72018-07-27 14:47:21 +09006569 if (pid == MY_PID || pid < 0) {
6570 if (DEBUG_CONFIGURATION) {
6571 Slog.w(TAG,
6572 "Trying to update display configuration for system/invalid process.");
6573 }
6574 return;
6575 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006576 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006577 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006578 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006579 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006580 // Call might come when display is not yet added or has been removed.
6581 if (DEBUG_CONFIGURATION) {
6582 Slog.w(TAG, "Trying to update display configuration for non-existing "
6583 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006584 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006585 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006586 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006587 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006588 if (process == null) {
6589 if (DEBUG_CONFIGURATION) {
6590 Slog.w(TAG, "Trying to update display configuration for invalid "
6591 + "process, pid=" + pid);
6592 }
6593 return;
6594 }
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006595 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006596 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006597 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006598
6599 @Override
6600 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006601 int requestCode, int resultCode, Intent data) {
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06006602 final ActivityRecord r;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006603 synchronized (mGlobalLock) {
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06006604 r = ActivityRecord.isInStackLocked(activityToken);
6605 if (r == null || r.getRootTask() == null) {
6606 return;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006607 }
6608 }
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06006609
6610 // Carefully collect grants without holding lock
6611 final NeededUriGrants dataGrants = collectGrants(data, r);
6612
6613 synchronized (mGlobalLock) {
6614 r.sendResult(callingUid, resultWho, requestCode, resultCode, data, dataGrants);
6615 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006616 }
6617
6618 @Override
6619 public void clearPendingResultForActivity(IBinder activityToken,
6620 WeakReference<PendingIntentRecord> pir) {
6621 synchronized (mGlobalLock) {
6622 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6623 if (r != null && r.pendingResults != null) {
6624 r.pendingResults.remove(pir);
6625 }
6626 }
6627 }
6628
6629 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006630 public ActivityTokens getTopActivityForTask(int taskId) {
6631 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006632 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006633 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006634 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6635 + " Requested task not found");
6636 return null;
6637 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006638 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006639 if (activity == null) {
6640 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6641 + " Requested activity not found");
6642 return null;
6643 }
6644 if (!activity.attachedToProcess()) {
6645 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6646 + activity);
6647 return null;
6648 }
6649 return new ActivityTokens(activity.appToken, activity.assistToken,
6650 activity.app.getThread());
6651 }
6652 }
6653
6654 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006655 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006656 @Nullable String featureId, int callingUid, int userId, IBinder token,
6657 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6658 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006659 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006660 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6661 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006662 }
6663 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006664
6665 @Override
6666 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6667 synchronized (mGlobalLock) {
6668 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6669 if (r == null) {
6670 return null;
6671 }
6672 if (r.mServiceConnectionsHolder == null) {
6673 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6674 ActivityTaskManagerService.this, r);
6675 }
6676
6677 return r.mServiceConnectionsHolder;
6678 }
6679 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006680
6681 @Override
6682 public Intent getHomeIntent() {
6683 synchronized (mGlobalLock) {
6684 return ActivityTaskManagerService.this.getHomeIntent();
6685 }
6686 }
6687
6688 @Override
6689 public boolean startHomeActivity(int userId, String reason) {
6690 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006691 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006692 }
6693 }
6694
6695 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006696 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006697 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006698 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006699 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006700 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006701 }
Chilun8b1f1be2019-03-13 17:14:36 +08006702 }
6703
6704 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006705 public boolean startHomeOnAllDisplays(int userId, String reason) {
6706 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006707 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006708 }
6709 }
6710
Riddle Hsua0536432019-02-16 00:38:59 +08006711 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006712 @Override
6713 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006714 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006715 if (mFactoryTest == FACTORY_TEST_OFF) {
6716 return false;
6717 }
6718 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6719 && wpc.mName.equals(mTopComponent.getPackageName())) {
6720 return true;
6721 }
6722 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6723 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6724 }
6725 }
6726
6727 @Override
6728 public void updateTopComponentForFactoryTest() {
6729 synchronized (mGlobalLock) {
6730 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6731 return;
6732 }
6733 final ResolveInfo ri = mContext.getPackageManager()
6734 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6735 final CharSequence errorMsg;
6736 if (ri != null) {
6737 final ActivityInfo ai = ri.activityInfo;
6738 final ApplicationInfo app = ai.applicationInfo;
6739 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6740 mTopAction = Intent.ACTION_FACTORY_TEST;
6741 mTopData = null;
6742 mTopComponent = new ComponentName(app.packageName, ai.name);
6743 errorMsg = null;
6744 } else {
6745 errorMsg = mContext.getResources().getText(
6746 com.android.internal.R.string.factorytest_not_system);
6747 }
6748 } else {
6749 errorMsg = mContext.getResources().getText(
6750 com.android.internal.R.string.factorytest_no_action);
6751 }
6752 if (errorMsg == null) {
6753 return;
6754 }
6755
6756 mTopAction = null;
6757 mTopData = null;
6758 mTopComponent = null;
6759 mUiHandler.post(() -> {
6760 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6761 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006762 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006763 });
6764 }
6765 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006766
Riddle Hsua0536432019-02-16 00:38:59 +08006767 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006768 @Override
6769 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6770 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006771 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006772 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006773 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006774
6775 wpc.clearRecentTasks();
6776 wpc.clearActivities();
6777
6778 if (wpc.isInstrumenting()) {
6779 finishInstrumentationCallback.run();
6780 }
6781
Jorim Jaggid0752812018-10-16 16:07:20 +02006782 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006783 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006784 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006785 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006786 // If there was nothing to resume, and we are not already restarting
6787 // this process, but there is a visible activity that is hosted by the
6788 // process...then make sure all visible activities are running, taking
6789 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006790 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006791 !PRESERVE_WINDOWS);
6792 }
6793 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006794 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006795 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006796 }
6797 }
6798 }
6799
6800 @Override
6801 public void closeSystemDialogs(String reason) {
6802 enforceNotIsolatedCaller("closeSystemDialogs");
6803
6804 final int pid = Binder.getCallingPid();
6805 final int uid = Binder.getCallingUid();
6806 final long origId = Binder.clearCallingIdentity();
6807 try {
6808 synchronized (mGlobalLock) {
6809 // Only allow this from foreground processes, so that background
6810 // applications can't abuse it to prevent system UI from being shown.
6811 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006812 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006813 if (!proc.isPerceptible()) {
6814 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6815 + " from background process " + proc);
6816 return;
6817 }
6818 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006819 mWindowManager.closeSystemDialogs(reason);
6820
Galia Peycheva72d581e2020-06-12 10:06:40 +02006821 mRootWindowContainer.closeSystemDialogActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006822 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006823 // Call into AM outside the synchronized block.
6824 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006825 } finally {
6826 Binder.restoreCallingIdentity(origId);
6827 }
6828 }
6829
6830 @Override
6831 public void cleanupDisabledPackageComponents(
6832 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6833 synchronized (mGlobalLock) {
6834 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006835 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006836 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006837 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006838 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006839 }
6840
6841 // Clean-up disabled tasks
6842 getRecentTasks().cleanupDisabledPackageTasksLocked(
6843 packageName, disabledClasses, userId);
6844 }
6845 }
6846
6847 @Override
6848 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6849 int userId) {
6850 synchronized (mGlobalLock) {
6851
6852 boolean didSomething =
6853 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006854 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006855 null, doit, evenPersistent, userId);
6856 return didSomething;
6857 }
6858 }
6859
6860 @Override
6861 public void resumeTopActivities(boolean scheduleIdle) {
6862 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006863 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006864 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006865 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006866 }
6867 }
6868 }
6869
Riddle Hsua0536432019-02-16 00:38:59 +08006870 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006871 @Override
6872 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006873 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006874 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6875 }
6876 }
6877
Riddle Hsua0536432019-02-16 00:38:59 +08006878 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 @Override
6880 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006881 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006882 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6883 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6884 }
6885 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006886 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006887 } finally {
6888 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6889 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006890 }
6891 }
6892
6893 @Override
6894 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6895 try {
6896 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6897 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6898 }
6899 } catch (RemoteException ex) {
6900 throw new SecurityException("Fail to check is caller a privileged app", ex);
6901 }
6902
6903 synchronized (mGlobalLock) {
6904 final long ident = Binder.clearCallingIdentity();
6905 try {
6906 if (mAmInternal.shouldConfirmCredentials(userId)) {
6907 if (mKeyguardController.isKeyguardLocked()) {
6908 // Showing launcher to avoid user entering credential twice.
6909 startHomeActivity(currentUserId, "notifyLockedProfile");
6910 }
Louis Chang149d5c82019-12-30 09:47:39 +08006911 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006912 }
6913 } finally {
6914 Binder.restoreCallingIdentity(ident);
6915 }
6916 }
6917 }
6918
6919 @Override
6920 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6921 mAmInternal.enforceCallingPermission(
6922 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6923
6924 synchronized (mGlobalLock) {
6925 final long ident = Binder.clearCallingIdentity();
6926 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006927 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6928 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006929 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006930 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6931 UserHandle.CURRENT);
6932 } finally {
6933 Binder.restoreCallingIdentity(ident);
6934 }
6935 }
6936 }
6937
6938 @Override
6939 public void writeActivitiesToProto(ProtoOutputStream proto) {
6940 synchronized (mGlobalLock) {
6941 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006942 mRootWindowContainer.dumpDebug(
6943 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006944 }
6945 }
6946
6947 @Override
6948 public void saveANRState(String reason) {
6949 synchronized (mGlobalLock) {
6950 final StringWriter sw = new StringWriter();
6951 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6952 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6953 if (reason != null) {
6954 pw.println(" Reason: " + reason);
6955 }
6956 pw.println();
6957 getActivityStartController().dump(pw, " ", null);
6958 pw.println();
6959 pw.println("-------------------------------------------------------------------------------");
6960 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6961 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6962 "" /* header */);
6963 pw.println();
6964 pw.close();
6965
6966 mLastANRState = sw.toString();
6967 }
6968 }
6969
6970 @Override
6971 public void clearSavedANRState() {
6972 synchronized (mGlobalLock) {
6973 mLastANRState = null;
6974 }
6975 }
6976
6977 @Override
6978 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6979 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6980 synchronized (mGlobalLock) {
6981 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6982 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6983 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6984 dumpLastANRLocked(pw);
6985 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6986 dumpLastANRTracesLocked(pw);
6987 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6988 dumpActivityStarterLocked(pw, dumpPackage);
6989 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6990 dumpActivityContainersLocked(pw);
6991 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6992 if (getRecentTasks() != null) {
6993 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6994 }
6995 }
6996 }
6997 }
6998
6999 @Override
7000 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7001 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7002 int wakefulness) {
7003 synchronized (mGlobalLock) {
7004 if (mHomeProcess != null && (dumpPackage == null
7005 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7006 if (needSep) {
7007 pw.println();
7008 needSep = false;
7009 }
7010 pw.println(" mHomeProcess: " + mHomeProcess);
7011 }
7012 if (mPreviousProcess != null && (dumpPackage == null
7013 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7014 if (needSep) {
7015 pw.println();
7016 needSep = false;
7017 }
7018 pw.println(" mPreviousProcess: " + mPreviousProcess);
7019 }
7020 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7021 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7022 StringBuilder sb = new StringBuilder(128);
7023 sb.append(" mPreviousProcessVisibleTime: ");
7024 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7025 pw.println(sb);
7026 }
7027 if (mHeavyWeightProcess != null && (dumpPackage == null
7028 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7029 if (needSep) {
7030 pw.println();
7031 needSep = false;
7032 }
7033 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7034 }
7035 if (dumpPackage == null) {
7036 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007037 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007038 }
7039 if (dumpAll) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007040 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7041 if (dumpPackage == null && topFocusedStack != null) {
7042 pw.println(" mConfigWillChange: " + topFocusedStack.mConfigWillChange);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007043 }
7044 if (mCompatModePackages.getPackages().size() > 0) {
7045 boolean printed = false;
7046 for (Map.Entry<String, Integer> entry
7047 : mCompatModePackages.getPackages().entrySet()) {
7048 String pkg = entry.getKey();
7049 int mode = entry.getValue();
7050 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7051 continue;
7052 }
7053 if (!printed) {
7054 pw.println(" mScreenCompatPackages:");
7055 printed = true;
7056 }
7057 pw.println(" " + pkg + ": " + mode);
7058 }
7059 }
7060 }
7061
7062 if (dumpPackage == null) {
7063 pw.println(" mWakefulness="
7064 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007065 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007066 if (mRunningVoice != null) {
7067 pw.println(" mRunningVoice=" + mRunningVoice);
7068 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7069 }
7070 pw.println(" mSleeping=" + mSleeping);
7071 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7072 pw.println(" mVrController=" + mVrController);
7073 }
7074 if (mCurAppTimeTracker != null) {
7075 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7076 }
7077 if (mAllowAppSwitchUids.size() > 0) {
7078 boolean printed = false;
7079 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7080 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7081 for (int j = 0; j < types.size(); j++) {
7082 if (dumpPackage == null ||
7083 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7084 if (needSep) {
7085 pw.println();
7086 needSep = false;
7087 }
7088 if (!printed) {
7089 pw.println(" mAllowAppSwitchUids:");
7090 printed = true;
7091 }
7092 pw.print(" User ");
7093 pw.print(mAllowAppSwitchUids.keyAt(i));
7094 pw.print(": Type ");
7095 pw.print(types.keyAt(j));
7096 pw.print(" = ");
7097 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7098 pw.println();
7099 }
7100 }
7101 }
7102 }
7103 if (dumpPackage == null) {
7104 if (mController != null) {
7105 pw.println(" mController=" + mController
7106 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7107 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007108 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7109 pw.println(" mLaunchingActivityWakeLock="
7110 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007111 }
7112
7113 return needSep;
7114 }
7115 }
7116
7117 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007118 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7119 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007120 synchronized (mGlobalLock) {
7121 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007122 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007123 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7124 if (topFocusedStack != null) {
7125 proto.write(CONFIG_WILL_CHANGE, topFocusedStack.mConfigWillChange);
7126 }
sanryhuang498e77e2018-12-06 14:57:01 +08007127 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7128 if (mRunningVoice != null) {
7129 final long vrToken = proto.start(
7130 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7131 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7132 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007133 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007134 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7135 proto.end(vrToken);
7136 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007137 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007138 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007139 if (mController != null) {
7140 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007141 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7142 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007143 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7144 proto.end(token);
7145 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007146 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7147 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007148 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007149 }
7150
7151 if (mHomeProcess != null && (dumpPackage == null
7152 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007153 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007154 }
7155
7156 if (mPreviousProcess != null && (dumpPackage == null
7157 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007158 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007159 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7160 }
7161
7162 if (mHeavyWeightProcess != null && (dumpPackage == null
7163 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007164 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007165 }
7166
7167 for (Map.Entry<String, Integer> entry
7168 : mCompatModePackages.getPackages().entrySet()) {
7169 String pkg = entry.getKey();
7170 int mode = entry.getValue();
7171 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7172 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7173 proto.write(PACKAGE, pkg);
7174 proto.write(MODE, mode);
7175 proto.end(compatToken);
7176 }
7177 }
7178
7179 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007180 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007181 }
7182
7183 }
7184 }
7185
7186 @Override
7187 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7188 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7189 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007190 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7191 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007192 }
7193
7194 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007195 public void dumpForOom(PrintWriter pw) {
7196 synchronized (mGlobalLock) {
7197 pw.println(" mHomeProcess: " + mHomeProcess);
7198 pw.println(" mPreviousProcess: " + mPreviousProcess);
7199 if (mHeavyWeightProcess != null) {
7200 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7201 }
7202 }
7203 }
7204
7205 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007206 public boolean canGcNow() {
7207 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007208 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007209 }
7210 }
7211
Riddle Hsua0536432019-02-16 00:38:59 +08007212 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007213 @Override
7214 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007215 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007216 if (mRootWindowContainer == null) {
7217 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007218 // oomadj after AMS created.
7219 return null;
7220 }
Louis Chang149d5c82019-12-30 09:47:39 +08007221 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007222 return top != null ? top.app : null;
7223 }
7224 }
7225
Riddle Hsua0536432019-02-16 00:38:59 +08007226 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007227 @Override
7228 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007229 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007230 if (mRootWindowContainer != null) {
7231 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007232 }
7233 }
7234 }
7235
7236 @Override
7237 public void scheduleDestroyAllActivities(String reason) {
7238 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007239 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007240 }
7241 }
7242
7243 @Override
7244 public void removeUser(int userId) {
7245 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007246 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007247 }
7248 }
7249
7250 @Override
7251 public boolean switchUser(int userId, UserState userState) {
7252 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007253 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007254 }
7255 }
7256
7257 @Override
7258 public void onHandleAppCrash(WindowProcessController wpc) {
7259 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007260 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007261 }
7262 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007263
7264 @Override
7265 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7266 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007267 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007268 }
7269 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007270
Riddle Hsua0536432019-02-16 00:38:59 +08007271 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007272 @Override
7273 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007274 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007275 }
7276
Riddle Hsua0536432019-02-16 00:38:59 +08007277 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007278 @Override
7279 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007280 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007281 }
7282
Riddle Hsua0536432019-02-16 00:38:59 +08007283 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007284 @Override
7285 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007286 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007287 }
7288
Riddle Hsua0536432019-02-16 00:38:59 +08007289 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007290 @Override
7291 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007292 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007293 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007294
7295 @Override
7296 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007297 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007298 mPendingTempWhitelist.put(uid, tag);
7299 }
7300 }
7301
7302 @Override
7303 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007304 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007305 mPendingTempWhitelist.remove(uid);
7306 }
7307 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007308
7309 @Override
7310 public boolean handleAppCrashInActivityController(String processName, int pid,
7311 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7312 Runnable killCrashingAppCallback) {
7313 synchronized (mGlobalLock) {
7314 if (mController == null) {
7315 return false;
7316 }
7317
7318 try {
7319 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7320 stackTrace)) {
7321 killCrashingAppCallback.run();
7322 return true;
7323 }
7324 } catch (RemoteException e) {
7325 mController = null;
7326 Watchdog.getInstance().setActivityController(null);
7327 }
7328 return false;
7329 }
7330 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007331
7332 @Override
7333 public void removeRecentTasksByPackageName(String packageName, int userId) {
7334 synchronized (mGlobalLock) {
7335 mRecentTasks.removeTasksByPackageName(packageName, userId);
7336 }
7337 }
7338
7339 @Override
7340 public void cleanupRecentTasksForUser(int userId) {
7341 synchronized (mGlobalLock) {
7342 mRecentTasks.cleanupLocked(userId);
7343 }
7344 }
7345
7346 @Override
7347 public void loadRecentTasksForUser(int userId) {
7348 synchronized (mGlobalLock) {
7349 mRecentTasks.loadUserRecentsLocked(userId);
7350 }
7351 }
7352
7353 @Override
7354 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7355 synchronized (mGlobalLock) {
7356 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7357 }
7358 }
7359
7360 @Override
7361 public void flushRecentTasks() {
7362 mRecentTasks.flush();
7363 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007364
7365 @Override
7366 public WindowProcessController getHomeProcess() {
7367 synchronized (mGlobalLock) {
7368 return mHomeProcess;
7369 }
7370 }
7371
7372 @Override
7373 public WindowProcessController getPreviousProcess() {
7374 synchronized (mGlobalLock) {
7375 return mPreviousProcess;
7376 }
7377 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007378
7379 @Override
7380 public void clearLockedTasks(String reason) {
7381 synchronized (mGlobalLock) {
7382 getLockTaskController().clearLockedTasks(reason);
7383 }
7384 }
7385
7386 @Override
7387 public void updateUserConfiguration() {
7388 synchronized (mGlobalLock) {
7389 final Configuration configuration = new Configuration(getGlobalConfiguration());
7390 final int currentUserId = mAmInternal.getCurrentUserId();
7391 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7392 configuration, currentUserId, Settings.System.canWrite(mContext));
7393 updateConfigurationLocked(configuration, null /* starting */,
7394 false /* initLocale */, false /* persistent */, currentUserId,
7395 false /* deferResume */);
7396 }
7397 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007398
7399 @Override
7400 public boolean canShowErrorDialogs() {
7401 synchronized (mGlobalLock) {
7402 return mShowDialogs && !mSleeping && !mShuttingDown
7403 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7404 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7405 mAmInternal.getCurrentUserId())
7406 && !(UserManager.isDeviceInDemoMode(mContext)
7407 && mAmInternal.getCurrentUser().isDemo());
7408 }
7409 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007410
7411 @Override
7412 public void setProfileApp(String profileApp) {
7413 synchronized (mGlobalLock) {
7414 mProfileApp = profileApp;
7415 }
7416 }
7417
7418 @Override
7419 public void setProfileProc(WindowProcessController wpc) {
7420 synchronized (mGlobalLock) {
7421 mProfileProc = wpc;
7422 }
7423 }
7424
7425 @Override
7426 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7427 synchronized (mGlobalLock) {
7428 mProfilerInfo = profilerInfo;
7429 }
7430 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007431
7432 @Override
7433 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7434 synchronized (mGlobalLock) {
7435 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7436 }
7437 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007438
7439 @Override
Zak Cohen84b43182020-03-09 14:36:01 -07007440 public ActivityManager.TaskSnapshot getTaskSnapshotBlocking(
7441 int taskId, boolean isLowResolution) {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08007442 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution,
Zak Cohen84b43182020-03-09 14:36:01 -07007443 true /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007444 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007445
7446 @Override
7447 public boolean isUidForeground(int uid) {
7448 synchronized (mGlobalLock) {
7449 return ActivityTaskManagerService.this.isUidForeground(uid);
7450 }
7451 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007452
7453 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007454 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007455 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007456 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007457 }
7458 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007459
7460 @Override
7461 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007462 // Translate package names into UIDs
7463 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007464 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007465 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7466 if (uid >= 0) {
7467 result.add(uid);
7468 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007469 }
7470 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007471 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007472 }
7473 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007474 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007475}