blob: 0542ef9b09a4078d134dafbd78c1a8d2dd029c95 [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();
Louis Changc2236422020-09-14 17:52:02 +0800385 private final SparseArray<String> mPendingTempAllowlist = 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,
Louis Changc2236422020-09-14 17:52:02 +08001102 IBinder allowlistToken, 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 }
Louis Changc2236422020-09-14 17:52:02 +08001125 return pir.sendInner(0, fillInIntent, resolvedType, allowlistToken, 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) {
Catherine Shicb4dbb82020-06-22 12:12:03 -07003000 stopLockTaskModeInternal(token, false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003001 }
3002
3003 /**
3004 * This API should be called by SystemUI only when user perform certain action to dismiss
3005 * lock task mode. We should only dismiss pinned lock task mode in this case.
3006 */
3007 @Override
3008 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003009 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003010 stopLockTaskModeInternal(null, true /* isSystemCaller */);
3011 }
3012
Louis Changcdec0802019-11-11 11:45:07 +08003013 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003014 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
3015 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
3016 return;
3017 }
3018
Louis Chang149d5c82019-12-30 09:47:39 +08003019 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09003020 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003021 throw new IllegalArgumentException("Invalid task, not in foreground");
3022 }
3023
3024 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
3025 // system or a specific app.
3026 // * System-initiated requests will only start the pinned mode (screen pinning)
3027 // * App-initiated requests
Louis Changc2236422020-09-14 17:52:02 +08003028 // - will put the device in fully locked mode (LockTask), if the app is allowlisted
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003029 // - will start the pinned mode, otherwise
3030 final int callingUid = Binder.getCallingUid();
3031 long ident = Binder.clearCallingIdentity();
3032 try {
3033 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08003034 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003035
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003036 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003037 } finally {
3038 Binder.restoreCallingIdentity(ident);
3039 }
3040 }
3041
Catherine Shicb4dbb82020-06-22 12:12:03 -07003042 private void stopLockTaskModeInternal(@Nullable IBinder token, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003043 final int callingUid = Binder.getCallingUid();
3044 long ident = Binder.clearCallingIdentity();
3045 try {
3046 synchronized (mGlobalLock) {
Catherine Shicb4dbb82020-06-22 12:12:03 -07003047 Task task = null;
3048 if (token != null) {
3049 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3050 if (r == null) {
3051 return;
3052 }
3053 task = r.getTask();
3054 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003055 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003056 }
3057 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
3058 // task and jumping straight into a call in the case of emergency call back.
3059 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
3060 if (tm != null) {
3061 tm.showInCallScreen(false);
3062 }
3063 } finally {
3064 Binder.restoreCallingIdentity(ident);
3065 }
3066 }
3067
3068 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003069 public void updateLockTaskPackages(int userId, String[] packages) {
3070 final int callingUid = Binder.getCallingUid();
3071 if (callingUid != 0 && callingUid != SYSTEM_UID) {
3072 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
3073 "updateLockTaskPackages()");
3074 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08003075 synchronized (mGlobalLock) {
Louis Changc2236422020-09-14 17:52:02 +08003076 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowlisting " + userId + ":"
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003077 + Arrays.toString(packages));
3078 getLockTaskController().updateLockTaskPackages(userId, packages);
3079 }
3080 }
3081
3082 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003083 public boolean isInLockTaskMode() {
3084 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3085 }
3086
3087 @Override
3088 public int getLockTaskModeState() {
3089 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003090 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003091 }
3092 }
3093
3094 @Override
3095 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3096 synchronized (mGlobalLock) {
3097 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3098 if (r != null) {
3099 r.setTaskDescription(td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003100 }
3101 }
3102 }
3103
3104 @Override
3105 public Bundle getActivityOptions(IBinder token) {
3106 final long origId = Binder.clearCallingIdentity();
3107 try {
3108 synchronized (mGlobalLock) {
3109 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3110 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003111 final ActivityOptions activityOptions = r.takeOptionsLocked(
3112 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003113 return activityOptions == null ? null : activityOptions.toBundle();
3114 }
3115 return null;
3116 }
3117 } finally {
3118 Binder.restoreCallingIdentity(origId);
3119 }
3120 }
3121
3122 @Override
3123 public List<IBinder> getAppTasks(String callingPackage) {
3124 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003125 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003126 long ident = Binder.clearCallingIdentity();
3127 try {
3128 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003129 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003130 }
3131 } finally {
3132 Binder.restoreCallingIdentity(ident);
3133 }
3134 }
3135
3136 @Override
3137 public void finishVoiceTask(IVoiceInteractionSession session) {
3138 synchronized (mGlobalLock) {
3139 final long origId = Binder.clearCallingIdentity();
3140 try {
3141 // TODO: VI Consider treating local voice interactions and voice tasks
3142 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003143 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003144 } finally {
3145 Binder.restoreCallingIdentity(origId);
3146 }
3147 }
3148
3149 }
3150
3151 @Override
3152 public boolean isTopOfTask(IBinder token) {
3153 synchronized (mGlobalLock) {
3154 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003155 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003156 }
3157 }
3158
3159 @Override
3160 public void notifyLaunchTaskBehindComplete(IBinder token) {
3161 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3162 }
3163
3164 @Override
3165 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003166 mH.post(() -> {
3167 synchronized (mGlobalLock) {
3168 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003169 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003170 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003171 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003172 } catch (RemoteException e) {
3173 }
3174 }
3175 }
3176
3177 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003178 }
3179
3180 /** Called from an app when assist data is ready. */
3181 @Override
3182 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3183 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003184 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003185 synchronized (pae) {
3186 pae.result = extras;
3187 pae.structure = structure;
3188 pae.content = content;
3189 if (referrer != null) {
3190 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3191 }
3192 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003193 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003194 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003195 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 structure.setHomeActivity(pae.isHome);
3197 }
3198 pae.haveResult = true;
3199 pae.notifyAll();
3200 if (pae.intent == null && pae.receiver == null) {
3201 // Caller is just waiting for the result.
3202 return;
3203 }
3204 }
3205 // We are now ready to launch the assist activity.
3206 IAssistDataReceiver sendReceiver = null;
3207 Bundle sendBundle = null;
3208 synchronized (mGlobalLock) {
3209 buildAssistBundleLocked(pae, extras);
3210 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003211 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003212 if (!exists) {
3213 // Timed out.
3214 return;
3215 }
3216
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003217 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003218 // Caller wants result sent back to them.
3219 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003220 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003221 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003222 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3223 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003224 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3225 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3226 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3227 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3228 }
3229 }
3230 if (sendReceiver != null) {
3231 try {
3232 sendReceiver.onHandleAssistData(sendBundle);
3233 } catch (RemoteException e) {
3234 }
3235 return;
3236 }
3237
3238 final long ident = Binder.clearCallingIdentity();
3239 try {
3240 if (TextUtils.equals(pae.intent.getAction(),
3241 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003242 // Start voice interaction through VoiceInteractionManagerService.
Galia Peycheva969f9952020-05-11 20:26:45 +02003243 mAssistUtils.showSessionForActiveService(pae.extras, SHOW_SOURCE_APPLICATION,
Galia Peychevabffbfc32019-06-18 10:11:35 +02003244 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003245 } else {
3246 pae.intent.replaceExtras(pae.extras);
3247 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3248 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3249 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003250 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003251
3252 try {
3253 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3254 } catch (ActivityNotFoundException e) {
3255 Slog.w(TAG, "No activity to handle assist action.", e);
3256 }
3257 }
3258 } finally {
3259 Binder.restoreCallingIdentity(ident);
3260 }
3261 }
3262
3263 @Override
3264 public int addAppTask(IBinder activityToken, Intent intent,
3265 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3266 final int callingUid = Binder.getCallingUid();
3267 final long callingIdent = Binder.clearCallingIdentity();
3268
3269 try {
3270 synchronized (mGlobalLock) {
3271 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3272 if (r == null) {
3273 throw new IllegalArgumentException("Activity does not exist; token="
3274 + activityToken);
3275 }
3276 ComponentName comp = intent.getComponent();
3277 if (comp == null) {
3278 throw new IllegalArgumentException("Intent " + intent
3279 + " must specify explicit component");
3280 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003281 if (thumbnail.getWidth() != mThumbnailWidth
3282 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003283 throw new IllegalArgumentException("Bad thumbnail size: got "
3284 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003285 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003286 }
3287 if (intent.getSelector() != null) {
3288 intent.setSelector(null);
3289 }
3290 if (intent.getSourceBounds() != null) {
3291 intent.setSourceBounds(null);
3292 }
3293 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3294 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3295 // The caller has added this as an auto-remove task... that makes no
3296 // sense, so turn off auto-remove.
3297 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3298 }
3299 }
3300 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3301 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3302 if (ainfo.applicationInfo.uid != callingUid) {
3303 throw new SecurityException(
3304 "Can't add task for another application: target uid="
3305 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3306 }
3307
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003308 final ActivityStack stack = r.getRootTask();
Andrii Kulian86d676c2020-03-27 19:34:54 -07003309 final Task task = stack.getDisplayArea().createStack(stack.getWindowingMode(),
3310 stack.getActivityType(), !ON_TOP, ainfo, intent,
Louis Changa009c762020-02-26 11:21:31 +08003311 false /* createdByOrganizer */);
Wale Ogunwale0d465192020-01-23 19:14:44 -08003312
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003313 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003314 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003315 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003316 return INVALID_TASK_ID;
3317 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003318 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003319
3320 // TODO: Send the thumbnail to WM to store it.
3321
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003322 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003323 }
3324 } finally {
3325 Binder.restoreCallingIdentity(callingIdent);
3326 }
3327 }
3328
3329 @Override
3330 public Point getAppTaskThumbnailSize() {
3331 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003332 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003333 }
3334 }
3335
3336 @Override
3337 public void setTaskResizeable(int taskId, int resizeableMode) {
3338 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003339 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003340 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3341 if (task == null) {
3342 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3343 return;
3344 }
3345 task.setResizeMode(resizeableMode);
3346 }
3347 }
3348
3349 @Override
Daichi Hironofa23f602020-05-14 06:15:59 +00003350 public boolean resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003351 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003352 long ident = Binder.clearCallingIdentity();
3353 try {
3354 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003355 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003356 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003357 if (task == null) {
3358 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
Daichi Hironofa23f602020-05-14 06:15:59 +00003359 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003360 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003361 if (!task.getWindowConfiguration().canResizeTask()) {
Daichi Hironofa23f602020-05-14 06:15:59 +00003362 Slog.w(TAG, "resizeTask not allowed on task=" + task);
3363 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003364 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003365
3366 // Reparent the task to the right stack if necessary
3367 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003368
3369 // After reparenting (which only resizes the task to the stack bounds), resize the
3370 // task to the actual bounds provided
Daichi Hironofa23f602020-05-14 06:15:59 +00003371 return task.resize(bounds, resizeMode, preserveWindow);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003372 }
3373 } finally {
3374 Binder.restoreCallingIdentity(ident);
3375 }
3376 }
3377
3378 @Override
3379 public boolean releaseActivityInstance(IBinder token) {
3380 synchronized (mGlobalLock) {
3381 final long origId = Binder.clearCallingIdentity();
3382 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003383 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3384 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003385 return false;
3386 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003387 r.destroyImmediately(true /* removeFromApp */, "app-req");
3388 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003389 } finally {
3390 Binder.restoreCallingIdentity(origId);
3391 }
3392 }
3393 }
3394
3395 @Override
3396 public void releaseSomeActivities(IApplicationThread appInt) {
3397 synchronized (mGlobalLock) {
3398 final long origId = Binder.clearCallingIdentity();
3399 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003400 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003401 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003402 } finally {
3403 Binder.restoreCallingIdentity(origId);
3404 }
3405 }
3406 }
3407
3408 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003409 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003410 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003411 != PackageManager.PERMISSION_GRANTED) {
3412 throw new SecurityException("Requires permission "
3413 + android.Manifest.permission.DEVICE_POWER);
3414 }
3415
3416 synchronized (mGlobalLock) {
3417 long ident = Binder.clearCallingIdentity();
3418 if (mKeyguardShown != keyguardShowing) {
3419 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003420 final Message msg = PooledLambda.obtainMessage(
3421 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3422 keyguardShowing);
3423 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 }
3425 try {
wilsonshih177261f2019-02-22 12:02:18 +08003426 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003427 } finally {
3428 Binder.restoreCallingIdentity(ident);
3429 }
3430 }
3431
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003432 mH.post(() -> {
3433 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3434 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3435 }
3436 });
3437 }
3438
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003439 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003440 mH.post(() -> {
3441 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3442 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3443 }
3444 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003445 }
3446
3447 @Override
3448 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003449 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3450 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003451
3452 final File passedIconFile = new File(filePath);
3453 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3454 passedIconFile.getName());
3455 if (!legitIconFile.getPath().equals(filePath)
3456 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3457 throw new IllegalArgumentException("Bad file path: " + filePath
3458 + " passed for userId " + userId);
3459 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003460 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003461 }
3462
3463 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003464 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003465 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003466 synchronized (mGlobalLock) {
3467 final long ident = Binder.clearCallingIdentity();
3468 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003469 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003470 if (stack == null) {
3471 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3472 return;
3473 }
3474 if (!stack.isActivityTypeStandardOrUndefined()) {
3475 throw new IllegalArgumentException(
3476 "Removing non-standard stack is not allowed.");
3477 }
3478 mStackSupervisor.removeStack(stack);
3479 } finally {
3480 Binder.restoreCallingIdentity(ident);
3481 }
3482 }
3483 }
3484
3485 @Override
3486 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003487 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003488
3489 synchronized (mGlobalLock) {
3490 final long ident = Binder.clearCallingIdentity();
3491 try {
3492 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3493 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003494 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003495 } finally {
3496 Binder.restoreCallingIdentity(ident);
3497 }
3498 }
3499 }
3500
3501 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003502 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003503 synchronized (mGlobalLock) {
3504 long ident = Binder.clearCallingIdentity();
3505 try {
3506 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3507 if (r == null) {
3508 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003509 "toggleFreeformWindowingMode: No activity record matching token="
3510 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003511 }
3512
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003513 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003514 if (stack == null) {
3515 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3516 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003517 }
3518
Yunfan Chend967af82019-01-17 18:30:18 +09003519 if (!stack.inFreeformWindowingMode()
3520 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3521 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3522 + "toggle between fullscreen and freeform.");
3523 }
3524
3525 if (stack.inFreeformWindowingMode()) {
3526 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003527 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003528 throw new IllegalStateException("Size-compat windows are currently not"
3529 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003530 } else if (stack.getParent().inFreeformWindowingMode()) {
3531 // If the window is on a freeform display, set it to undefined. It will be
3532 // resolved to freeform and it can adjust windowing mode when the display mode
3533 // changes in runtime.
3534 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003535 } else {
3536 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3537 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003538 } finally {
3539 Binder.restoreCallingIdentity(ident);
3540 }
3541 }
3542 }
3543
3544 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3545 @Override
3546 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003547 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003548 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003549 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003550 }
3551
3552 /** Unregister a task stack listener so that it stops receiving callbacks. */
3553 @Override
3554 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003555 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003556 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003557 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003558 }
3559
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003560 @Override
3561 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3562 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3563 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3564 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3565 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3566 }
3567
3568 @Override
3569 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3570 IBinder activityToken, int flags) {
3571 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3572 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3573 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3574 }
3575
3576 @Override
3577 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3578 Bundle args) {
3579 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3580 true /* focused */, true /* newSessionId */, userHandle, args,
3581 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3582 }
3583
3584 @Override
3585 public Bundle getAssistContextExtras(int requestType) {
3586 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3587 null, null, true /* focused */, true /* newSessionId */,
3588 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3589 if (pae == null) {
3590 return null;
3591 }
3592 synchronized (pae) {
3593 while (!pae.haveResult) {
3594 try {
3595 pae.wait();
3596 } catch (InterruptedException e) {
3597 }
3598 }
3599 }
3600 synchronized (mGlobalLock) {
3601 buildAssistBundleLocked(pae, pae.result);
3602 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003603 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003604 }
3605 return pae.extras;
3606 }
3607
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003608 /**
3609 * Binder IPC calls go through the public entry point.
3610 * This can be called with or without the global lock held.
3611 */
3612 private static int checkCallingPermission(String permission) {
3613 return checkPermission(
3614 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3615 }
3616
3617 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003618 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003619 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3620 mAmInternal.enforceCallingPermission(permission, func);
3621 }
3622 }
3623
3624 @VisibleForTesting
3625 int checkGetTasksPermission(String permission, int pid, int uid) {
3626 return checkPermission(permission, pid, uid);
3627 }
3628
3629 static int checkPermission(String permission, int pid, int uid) {
3630 if (permission == null) {
3631 return PackageManager.PERMISSION_DENIED;
3632 }
3633 return checkComponentPermission(permission, pid, uid, -1, true);
3634 }
3635
Wale Ogunwale214f3482018-10-04 11:00:47 -07003636 public static int checkComponentPermission(String permission, int pid, int uid,
3637 int owningUid, boolean exported) {
3638 return ActivityManagerService.checkComponentPermission(
3639 permission, pid, uid, owningUid, exported);
3640 }
3641
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003642 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3643 if (getRecentTasks().isCallerRecents(callingUid)) {
3644 // Always allow the recents component to get tasks
3645 return true;
3646 }
3647
3648 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3649 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3650 if (!allowed) {
3651 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3652 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3653 // Temporary compatibility: some existing apps on the system image may
3654 // still be requesting the old permission and not switched to the new
3655 // one; if so, we'll still allow them full access. This means we need
3656 // to see if they are holding the old permission and are a system app.
3657 try {
3658 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3659 allowed = true;
3660 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3661 + " is using old GET_TASKS but privileged; allowing");
3662 }
3663 } catch (RemoteException e) {
3664 }
3665 }
3666 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3667 + " does not hold REAL_GET_TASKS; limiting output");
3668 }
3669 return allowed;
3670 }
3671
Nicholas Sauer0259e532019-08-30 08:24:55 -07003672 boolean isCrossUserAllowed(int pid, int uid) {
3673 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3674 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3675 }
3676
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003677 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3678 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3679 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3680 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003681 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003682 "enqueueAssistContext()");
3683
3684 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08003685 final ActivityStack stack = getTopDisplayFocusedStack();
3686 ActivityRecord activity = stack != null ? stack.getTopNonFinishingActivity() : null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003687 if (activity == null) {
3688 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3689 return null;
3690 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003691 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003692 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3693 return null;
3694 }
3695 if (focused) {
3696 if (activityToken != null) {
3697 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3698 if (activity != caller) {
3699 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3700 + " is not current top " + activity);
3701 return null;
3702 }
3703 }
3704 } else {
3705 activity = ActivityRecord.forTokenLocked(activityToken);
3706 if (activity == null) {
3707 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3708 + " couldn't be found");
3709 return null;
3710 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003711 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003712 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3713 return null;
3714 }
3715 }
3716
3717 PendingAssistExtras pae;
3718 Bundle extras = new Bundle();
3719 if (args != null) {
3720 extras.putAll(args);
3721 }
3722 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003723 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003724
3725 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3726 userHandle);
3727 pae.isHome = activity.isActivityTypeHome();
3728
3729 // Increment the sessionId if necessary
3730 if (newSessionId) {
3731 mViSessionId++;
3732 }
3733 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003734 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3735 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003736 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003737 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003738 } catch (RemoteException e) {
3739 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3740 return null;
3741 }
3742 return pae;
3743 }
3744 }
3745
3746 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3747 if (result != null) {
3748 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3749 }
3750 if (pae.hint != null) {
3751 pae.extras.putBoolean(pae.hint, true);
3752 }
3753 }
3754
3755 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3756 IAssistDataReceiver receiver;
3757 synchronized (mGlobalLock) {
3758 mPendingAssistExtras.remove(pae);
3759 receiver = pae.receiver;
3760 }
3761 if (receiver != null) {
3762 // Caller wants result sent back to them.
3763 Bundle sendBundle = new Bundle();
3764 // At least return the receiver extras
3765 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3766 try {
3767 pae.receiver.onHandleAssistData(sendBundle);
3768 } catch (RemoteException e) {
3769 }
3770 }
3771 }
3772
3773 public class PendingAssistExtras extends Binder implements Runnable {
3774 public final ActivityRecord activity;
3775 public boolean isHome;
3776 public final Bundle extras;
3777 public final Intent intent;
3778 public final String hint;
3779 public final IAssistDataReceiver receiver;
3780 public final int userHandle;
3781 public boolean haveResult = false;
3782 public Bundle result = null;
3783 public AssistStructure structure = null;
3784 public AssistContent content = null;
3785 public Bundle receiverExtras;
3786
3787 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3788 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3789 int _userHandle) {
3790 activity = _activity;
3791 extras = _extras;
3792 intent = _intent;
3793 hint = _hint;
3794 receiver = _receiver;
3795 receiverExtras = _receiverExtras;
3796 userHandle = _userHandle;
3797 }
3798
3799 @Override
3800 public void run() {
3801 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3802 synchronized (this) {
3803 haveResult = true;
3804 notifyAll();
3805 }
3806 pendingAssistExtrasTimedOut(this);
3807 }
3808 }
3809
3810 @Override
3811 public boolean isAssistDataAllowedOnCurrentActivity() {
3812 int userId;
3813 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003814 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003815 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3816 return false;
3817 }
3818
Wale Ogunwale21e06482019-11-18 05:14:15 -08003819 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003820 if (activity == null) {
3821 return false;
3822 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003823 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003824 }
Alex Johnston302c1fe2020-06-18 20:00:51 +01003825 return DevicePolicyCache.getInstance().isScreenCaptureAllowed(userId, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003826 }
3827
3828 @Override
3829 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3830 long ident = Binder.clearCallingIdentity();
3831 try {
3832 synchronized (mGlobalLock) {
3833 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003834 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003835 if (top != caller) {
3836 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3837 + " is not current top " + top);
3838 return false;
3839 }
3840 if (!top.nowVisible) {
3841 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3842 + " is not visible");
3843 return false;
3844 }
3845 }
3846 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3847 token);
3848 } finally {
3849 Binder.restoreCallingIdentity(ident);
3850 }
3851 }
3852
3853 @Override
3854 public boolean isRootVoiceInteraction(IBinder token) {
3855 synchronized (mGlobalLock) {
3856 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3857 if (r == null) {
3858 return false;
3859 }
3860 return r.rootVoiceInteraction;
3861 }
3862 }
3863
Wale Ogunwalef6733932018-06-27 05:14:34 -07003864 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3865 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3866 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3867 if (activityToCallback == null) return;
3868 activityToCallback.setVoiceSessionLocked(voiceSession);
3869
3870 // Inform the activity
3871 try {
3872 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3873 voiceInteractor);
3874 long token = Binder.clearCallingIdentity();
3875 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003876 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003877 } finally {
3878 Binder.restoreCallingIdentity(token);
3879 }
3880 // TODO: VI Should we cache the activity so that it's easier to find later
3881 // rather than scan through all the stacks and activities?
3882 } catch (RemoteException re) {
3883 activityToCallback.clearVoiceSessionLocked();
3884 // TODO: VI Should this terminate the voice session?
3885 }
3886 }
3887
3888 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3889 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3890 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3891 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3892 boolean wasRunningVoice = mRunningVoice != null;
3893 mRunningVoice = session;
3894 if (!wasRunningVoice) {
3895 mVoiceWakeLock.acquire();
3896 updateSleepIfNeededLocked();
3897 }
3898 }
3899 }
3900
3901 void finishRunningVoiceLocked() {
3902 if (mRunningVoice != null) {
3903 mRunningVoice = null;
3904 mVoiceWakeLock.release();
3905 updateSleepIfNeededLocked();
3906 }
3907 }
3908
3909 @Override
3910 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3911 synchronized (mGlobalLock) {
3912 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3913 if (keepAwake) {
3914 mVoiceWakeLock.acquire();
3915 } else {
3916 mVoiceWakeLock.release();
3917 }
3918 }
3919 }
3920 }
3921
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003922 @Override
3923 public ComponentName getActivityClassForToken(IBinder token) {
3924 synchronized (mGlobalLock) {
3925 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3926 if (r == null) {
3927 return null;
3928 }
3929 return r.intent.getComponent();
3930 }
3931 }
3932
3933 @Override
3934 public String getPackageForToken(IBinder token) {
3935 synchronized (mGlobalLock) {
3936 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3937 if (r == null) {
3938 return null;
3939 }
3940 return r.packageName;
3941 }
3942 }
3943
3944 @Override
3945 public void showLockTaskEscapeMessage(IBinder token) {
3946 synchronized (mGlobalLock) {
3947 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3948 if (r == null) {
3949 return;
3950 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003951 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003952 }
3953 }
3954
3955 @Override
3956 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003957 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003958 final long token = Binder.clearCallingIdentity();
3959 try {
3960 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003961 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003962 }
3963 } finally {
3964 Binder.restoreCallingIdentity(token);
3965 }
3966 }
3967
3968 /**
3969 * Try to place task to provided position. The final position might be different depending on
3970 * current user and stacks state. The task will be moved to target stack if it's currently in
3971 * different stack.
3972 */
3973 @Override
3974 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003975 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003976 synchronized (mGlobalLock) {
3977 long ident = Binder.clearCallingIdentity();
3978 try {
3979 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3980 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003981 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003982 if (task == null) {
3983 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3984 + taskId);
3985 }
3986
Louis Chang149d5c82019-12-30 09:47:39 +08003987 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003988
3989 if (stack == null) {
3990 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3991 + stackId);
3992 }
3993 if (!stack.isActivityTypeStandardOrUndefined()) {
3994 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3995 + " the position of task " + taskId + " in/to non-standard stack");
3996 }
3997
3998 // TODO: Have the callers of this API call a separate reparent method if that is
3999 // what they intended to do vs. having this method also do reparenting.
4000 if (task.getStack() == stack) {
4001 // Change position in current stack.
4002 stack.positionChildAt(task, position);
4003 } else {
4004 // Reparent to new stack.
4005 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
4006 !DEFER_RESUME, "positionTaskInStack");
4007 }
4008 } finally {
4009 Binder.restoreCallingIdentity(ident);
4010 }
4011 }
4012 }
4013
4014 @Override
4015 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
4016 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
4017 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09004018 + Arrays.toString(horizontalSizeConfiguration) + " "
4019 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004020 synchronized (mGlobalLock) {
4021 ActivityRecord record = ActivityRecord.isInStackLocked(token);
4022 if (record == null) {
4023 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
4024 + "found for: " + token);
4025 }
4026 record.setSizeConfigurations(horizontalSizeConfiguration,
4027 verticalSizeConfigurations, smallestSizeConfigurations);
4028 }
4029 }
4030
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004031 @Override
4032 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004033 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004034 synchronized (mGlobalLock) {
4035 mSuppressResizeConfigChanges = suppress;
4036 }
4037 }
4038
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004039 /**
4040 * Moves the top activity in the input stackId to the pinned stack.
4041 *
4042 * @param stackId Id of stack to move the top activity to pinned stack.
4043 * @param bounds Bounds to use for pinned stack.
4044 *
4045 * @return True if the top activity of the input stack was successfully moved to the pinned
4046 * stack.
4047 */
4048 @Override
4049 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004050 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004051 "moveTopActivityToPinnedStack()");
4052 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004053 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004054 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4055 + "Device doesn't support picture-in-picture mode");
4056 }
4057
4058 long ident = Binder.clearCallingIdentity();
4059 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004060 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004061 } finally {
4062 Binder.restoreCallingIdentity(ident);
4063 }
4064 }
4065 }
4066
Hongwei Wang5711b8f2019-11-15 15:44:12 -08004067 @VisibleForTesting
4068 boolean isInPictureInPictureMode(ActivityRecord r) {
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004069 return r != null
4070 && r.getRootTask() != null
4071 && r.inPinnedWindowingMode()
Wale Ogunwale0db64ac2020-04-11 10:00:42 -07004072 && r.getRootTask().isInTask(r) != null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004073 }
4074
4075 @Override
4076 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4077 final long origId = Binder.clearCallingIdentity();
4078 try {
4079 synchronized (mGlobalLock) {
4080 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4081 "enterPictureInPictureMode", token, params);
4082
4083 // If the activity is already in picture in picture mode, then just return early
4084 if (isInPictureInPictureMode(r)) {
4085 return true;
4086 }
4087
4088 // Activity supports picture-in-picture, now check that we can enter PiP at this
4089 // point, if it is
4090 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4091 false /* beforeStopping */)) {
4092 return false;
4093 }
4094
4095 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004096 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004097 if (r.getParent() == null) {
4098 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4099 return;
4100 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004101 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004102 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004103 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4104 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
Louis Chang149d5c82019-12-30 09:47:39 +08004105 mRootWindowContainer.moveActivityToPinnedStack(
Hongwei Wange8e32862020-04-08 13:23:45 -07004106 r, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004107 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004108 stack.setPictureInPictureAspectRatio(aspectRatio);
4109 stack.setPictureInPictureActions(actions);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004110 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004111 };
4112
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004113 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004114 // If the keyguard is showing or occluded, then try and dismiss it before
4115 // entering picture-in-picture (this will prompt the user to authenticate if the
4116 // device is currently locked).
4117 dismissKeyguard(token, new KeyguardDismissCallback() {
4118 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004119 public void onDismissSucceeded() {
4120 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004121 }
4122 }, null /* message */);
4123 } else {
4124 // Enter picture in picture immediately otherwise
4125 enterPipRunnable.run();
4126 }
4127 return true;
4128 }
4129 } finally {
4130 Binder.restoreCallingIdentity(origId);
4131 }
4132 }
4133
4134 @Override
4135 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4136 final long origId = Binder.clearCallingIdentity();
4137 try {
4138 synchronized (mGlobalLock) {
4139 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4140 "setPictureInPictureParams", token, params);
4141
4142 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004143 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004144 if (r.inPinnedWindowingMode()) {
4145 // If the activity is already in picture-in-picture, update the pinned stack now
4146 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4147 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004148 final ActivityStack stack = r.getRootTask();
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004149 stack.setPictureInPictureAspectRatio(
4150 r.pictureInPictureArgs.getAspectRatio());
4151 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004152 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004153 }
4154 } finally {
4155 Binder.restoreCallingIdentity(origId);
4156 }
4157 }
4158
4159 @Override
4160 public int getMaxNumPictureInPictureActions(IBinder token) {
4161 // Currently, this is a static constant, but later, we may change this to be dependent on
4162 // the context of the activity
4163 return 3;
4164 }
4165
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004166 /**
4167 * Checks the state of the system and the activity associated with the given {@param token} to
4168 * verify that picture-in-picture is supported for that activity.
4169 *
4170 * @return the activity record for the given {@param token} if all the checks pass.
4171 */
4172 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4173 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004174 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004175 throw new IllegalStateException(caller
4176 + ": Device doesn't support picture-in-picture mode.");
4177 }
4178
4179 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4180 if (r == null) {
4181 throw new IllegalStateException(caller
4182 + ": Can't find activity for token=" + token);
4183 }
4184
4185 if (!r.supportsPictureInPicture()) {
4186 throw new IllegalStateException(caller
4187 + ": Current activity does not support picture-in-picture.");
4188 }
4189
4190 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004191 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004192 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004193 final float minAspectRatio = mContext.getResources().getFloat(
4194 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4195 final float maxAspectRatio = mContext.getResources().getFloat(
4196 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4197 throw new IllegalArgumentException(String.format(caller
4198 + ": Aspect ratio is too extreme (must be between %f and %f).",
4199 minAspectRatio, maxAspectRatio));
4200 }
4201
4202 // Truncate the number of actions if necessary
4203 params.truncateActions(getMaxNumPictureInPictureActions(token));
4204
4205 return r;
4206 }
4207
4208 @Override
4209 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004210 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004211 synchronized (mGlobalLock) {
4212 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4213 if (r == null) {
4214 throw new IllegalArgumentException("Activity does not exist; token="
4215 + activityToken);
4216 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004217 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004218 }
4219 }
4220
Evan Rosky73a7fe92019-11-18 18:28:01 -08004221 // TODO(b/149338177): remove when CTS no-longer requires it
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004222 @Override
4223 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4224 Rect tempDockedTaskInsetBounds,
4225 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004226 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004227 long ident = Binder.clearCallingIdentity();
4228 try {
4229 synchronized (mGlobalLock) {
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -07004230 final TaskDisplayArea tc = mRootWindowContainer.getDefaultTaskDisplayArea();
4231 final Task primary = tc.getRootSplitScreenPrimaryTask();
4232 final Task secondary = tc.getTask(t -> t.mCreatedByOrganizer && t.isRootTask()
Louis Changa009c762020-02-26 11:21:31 +08004233 && t.inSplitScreenSecondaryWindowingMode());
Evan Rosky73a7fe92019-11-18 18:28:01 -08004234 if (primary == null || secondary == null) {
4235 return;
4236 }
4237 final WindowContainerTransaction wct = new WindowContainerTransaction();
4238 final Rect primaryRect =
4239 tempDockedTaskInsetBounds != null ? tempDockedTaskInsetBounds
4240 : (tempDockedTaskBounds != null ? tempDockedTaskBounds
4241 : dockedBounds);
Wale Ogunwaleadf116e2020-03-27 16:36:01 -07004242 wct.setBounds(primary.mRemoteToken.toWindowContainerToken(), primaryRect);
Evan Rosky73a7fe92019-11-18 18:28:01 -08004243 Rect otherRect = tempOtherTaskInsetBounds != null ? tempOtherTaskInsetBounds
4244 : tempOtherTaskBounds;
4245 if (otherRect == null) {
4246 // Temporary estimation... again this is just for tests.
4247 otherRect = new Rect(secondary.getBounds());
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -07004248 if (tc.getBounds().width() > tc.getBounds().height()) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08004249 otherRect.left = primaryRect.right + 6;
4250 } else {
4251 otherRect.top = primaryRect.bottom + 6;
4252 }
4253 }
Wale Ogunwaleadf116e2020-03-27 16:36:01 -07004254 wct.setBounds(secondary.mRemoteToken.toWindowContainerToken(), otherRect);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004255 mWindowOrganizerController.applyTransaction(wct);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004256 }
4257 } finally {
4258 Binder.restoreCallingIdentity(ident);
4259 }
4260 }
4261
4262 @Override
4263 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004264 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004265 final long ident = Binder.clearCallingIdentity();
4266 try {
4267 synchronized (mGlobalLock) {
4268 mStackSupervisor.setSplitScreenResizing(resizing);
4269 }
4270 } finally {
4271 Binder.restoreCallingIdentity(ident);
4272 }
4273 }
4274
Evan Rosky0037e5f2019-11-05 10:26:24 -08004275 @Override
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004276 public IWindowOrganizerController getWindowOrganizerController() {
Evan Rosky0037e5f2019-11-05 10:26:24 -08004277 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004278 "getWindowOrganizerController()");
4279 return mWindowOrganizerController;
Evan Rosky0037e5f2019-11-05 10:26:24 -08004280 }
4281
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004282 /**
4283 * Check that we have the features required for VR-related API calls, and throw an exception if
4284 * not.
4285 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004286 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004287 if (!mContext.getPackageManager().hasSystemFeature(
4288 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4289 throw new UnsupportedOperationException("VR mode not supported on this device!");
4290 }
4291 }
4292
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004293 @Override
4294 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004295 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004296
4297 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4298
4299 ActivityRecord r;
4300 synchronized (mGlobalLock) {
4301 r = ActivityRecord.isInStackLocked(token);
4302 }
4303
4304 if (r == null) {
4305 throw new IllegalArgumentException();
4306 }
4307
4308 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004309 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004310 VrManagerInternal.NO_ERROR) {
4311 return err;
4312 }
4313
4314 // Clear the binder calling uid since this path may call moveToTask().
4315 final long callingId = Binder.clearCallingIdentity();
4316 try {
4317 synchronized (mGlobalLock) {
4318 r.requestedVrComponent = (enabled) ? packageName : null;
4319
4320 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004321 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004322 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004323 }
4324 return 0;
4325 }
4326 } finally {
4327 Binder.restoreCallingIdentity(callingId);
4328 }
4329 }
4330
4331 @Override
4332 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4333 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4334 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004335 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004336 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4337 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4338 }
Louis Changcdec0802019-11-11 11:45:07 +08004339 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004340 || activity.voiceSession != null) {
4341 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4342 return;
4343 }
4344 if (activity.pendingVoiceInteractionStart) {
4345 Slog.w(TAG, "Pending start of voice interaction already.");
4346 return;
4347 }
4348 activity.pendingVoiceInteractionStart = true;
4349 }
4350 LocalServices.getService(VoiceInteractionManagerInternal.class)
4351 .startLocalVoiceInteraction(callingActivity, options);
4352 }
4353
4354 @Override
4355 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4356 LocalServices.getService(VoiceInteractionManagerInternal.class)
4357 .stopLocalVoiceInteraction(callingActivity);
4358 }
4359
4360 @Override
4361 public boolean supportsLocalVoiceInteraction() {
4362 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4363 .supportsLocalVoiceInteraction();
4364 }
4365
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004366 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004368 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004369
4370 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004371 if (mWindowManager == null) {
4372 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4373 return false;
4374 }
4375
4376 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004377 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004378 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004379 }
4380
Riddle Hsua0022cd2019-09-09 21:12:41 +08004381 mH.sendMessage(PooledLambda.obtainMessage(
4382 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4383 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004384
4385 final long origId = Binder.clearCallingIdentity();
4386 try {
4387 if (values != null) {
4388 Settings.System.clearConfiguration(values);
4389 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004390 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004391 UserHandle.USER_NULL, false /* deferResume */,
4392 mTmpUpdateConfigurationResult);
4393 return mTmpUpdateConfigurationResult.changes != 0;
4394 } finally {
4395 Binder.restoreCallingIdentity(origId);
4396 }
4397 }
4398 }
4399
4400 @Override
4401 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4402 CharSequence message) {
4403 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004404 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004405 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4406 }
4407 final long callingId = Binder.clearCallingIdentity();
4408 try {
4409 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004410 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004411 }
4412 } finally {
4413 Binder.restoreCallingIdentity(callingId);
4414 }
4415 }
4416
4417 @Override
4418 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004419 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004420 "cancelTaskWindowTransition()");
4421 final long ident = Binder.clearCallingIdentity();
4422 try {
4423 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004424 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004425 MATCH_TASK_IN_STACKS_ONLY);
4426 if (task == null) {
4427 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4428 return;
4429 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004430 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004431 }
4432 } finally {
4433 Binder.restoreCallingIdentity(ident);
4434 }
4435 }
4436
4437 @Override
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004438 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004439 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004440 final long ident = Binder.clearCallingIdentity();
4441 try {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004442 return getTaskSnapshot(taskId, isLowResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004443 } finally {
4444 Binder.restoreCallingIdentity(ident);
4445 }
4446 }
4447
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004448 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004449 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004450 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004451 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004452 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004453 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4454 if (task == null) {
4455 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4456 return null;
4457 }
4458 }
4459 // Don't call this while holding the lock as this operation might hit the disk.
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004460 return task.getSnapshot(isLowResolution, restoreFromDisk);
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004461 }
4462
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004463 @Override
4464 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4465 synchronized (mGlobalLock) {
4466 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4467 if (r == null) {
4468 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4469 + token);
4470 return;
4471 }
4472 final long origId = Binder.clearCallingIdentity();
4473 try {
4474 r.setDisablePreviewScreenshots(disable);
4475 } finally {
4476 Binder.restoreCallingIdentity(origId);
4477 }
4478 }
4479 }
4480
Riddle Hsu440f88b2019-11-06 22:17:35 +08004481 @Override
4482 public void invalidateHomeTaskSnapshot(IBinder token) {
4483 synchronized (mGlobalLock) {
4484 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4485 if (r == null || !r.isActivityTypeHome()) {
4486 return;
4487 }
4488 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4489 }
4490 }
4491
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004492 /** Return the user id of the last resumed activity. */
4493 @Override
4494 public @UserIdInt
4495 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004496 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004497 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4498 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004499 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004500 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004501 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004502 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004503 }
4504 }
4505
4506 @Override
4507 public void updateLockTaskFeatures(int userId, int flags) {
4508 final int callingUid = Binder.getCallingUid();
4509 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004510 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004511 "updateLockTaskFeatures()");
4512 }
4513 synchronized (mGlobalLock) {
4514 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4515 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004516 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004517 }
4518 }
4519
4520 @Override
4521 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4522 synchronized (mGlobalLock) {
4523 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4524 if (r == null) {
4525 return;
4526 }
4527 final long origId = Binder.clearCallingIdentity();
4528 try {
4529 r.setShowWhenLocked(showWhenLocked);
4530 } finally {
4531 Binder.restoreCallingIdentity(origId);
4532 }
4533 }
4534 }
4535
4536 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004537 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4538 synchronized (mGlobalLock) {
4539 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4540 if (r == null) {
4541 return;
4542 }
4543 final long origId = Binder.clearCallingIdentity();
4544 try {
4545 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4546 } finally {
4547 Binder.restoreCallingIdentity(origId);
4548 }
4549 }
4550 }
4551
4552 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004553 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4554 synchronized (mGlobalLock) {
4555 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4556 if (r == null) {
4557 return;
4558 }
4559 final long origId = Binder.clearCallingIdentity();
4560 try {
4561 r.setTurnScreenOn(turnScreenOn);
4562 } finally {
4563 Binder.restoreCallingIdentity(origId);
4564 }
4565 }
4566 }
4567
4568 @Override
4569 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004570 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004571 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004572 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004573 synchronized (mGlobalLock) {
4574 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4575 if (r == null) {
4576 return;
4577 }
4578 final long origId = Binder.clearCallingIdentity();
4579 try {
4580 r.registerRemoteAnimations(definition);
4581 } finally {
4582 Binder.restoreCallingIdentity(origId);
4583 }
4584 }
4585 }
4586
4587 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004588 public void unregisterRemoteAnimations(IBinder token) {
4589 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4590 "unregisterRemoteAnimations");
4591 synchronized (mGlobalLock) {
4592 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4593 if (r == null) {
4594 return;
4595 }
4596 final long origId = Binder.clearCallingIdentity();
4597 try {
4598 r.unregisterRemoteAnimations();
4599 } finally {
4600 Binder.restoreCallingIdentity(origId);
4601 }
4602 }
4603 }
4604
4605 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004606 public void registerRemoteAnimationForNextActivityStart(String packageName,
4607 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004608 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004609 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004610 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004611 synchronized (mGlobalLock) {
4612 final long origId = Binder.clearCallingIdentity();
4613 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004614 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004615 packageName, adapter);
4616 } finally {
4617 Binder.restoreCallingIdentity(origId);
4618 }
4619 }
4620 }
4621
Evan Rosky966759f2019-01-15 10:33:58 -08004622 @Override
4623 public void registerRemoteAnimationsForDisplay(int displayId,
4624 RemoteAnimationDefinition definition) {
4625 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4626 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004627 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004628 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004629 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004630 if (display == null) {
4631 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4632 return;
4633 }
4634 final long origId = Binder.clearCallingIdentity();
4635 try {
4636 display.mDisplayContent.registerRemoteAnimations(definition);
4637 } finally {
4638 Binder.restoreCallingIdentity(origId);
4639 }
4640 }
4641 }
4642
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004643 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4644 @Override
4645 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4646 synchronized (mGlobalLock) {
4647 final long origId = Binder.clearCallingIdentity();
4648 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004649 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004650 } finally {
4651 Binder.restoreCallingIdentity(origId);
4652 }
4653 }
4654 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004655
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004656 @Override
4657 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004658 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004659 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004660 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004661 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004662 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004663 }
4664 }
4665
4666 @Override
4667 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004668 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004669 != PERMISSION_GRANTED) {
4670 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4671 + Binder.getCallingPid()
4672 + ", uid=" + Binder.getCallingUid()
4673 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4674 Slog.w(TAG, msg);
4675 throw new SecurityException(msg);
4676 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004677 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004678 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004679 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004680 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004681 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004682 }
4683 }
4684
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004685 @Override
4686 public void stopAppSwitches() {
4687 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4688 synchronized (mGlobalLock) {
4689 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004690 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004691 mDidAppSwitch = false;
4692 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4693 }
4694 }
4695
4696 @Override
4697 public void resumeAppSwitches() {
4698 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4699 synchronized (mGlobalLock) {
4700 // Note that we don't execute any pending app switches... we will
4701 // let those wait until either the timeout, or the next start
4702 // activity request.
4703 mAppSwitchesAllowedTime = 0;
4704 }
4705 }
4706
Ricky Wai906af482019-06-03 17:25:28 +01004707 long getLastStopAppSwitchesTime() {
4708 return mLastStopAppSwitchesTime;
4709 }
4710
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004711 void onStartActivitySetDidAppSwitch() {
4712 if (mDidAppSwitch) {
4713 // This is the second allowed switch since we stopped switches, so now just generally
4714 // allow switches. Use case:
4715 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4716 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4717 // anyone to switch again).
4718 mAppSwitchesAllowedTime = 0;
4719 } else {
4720 mDidAppSwitch = true;
4721 }
4722 }
4723
4724 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004725 boolean shouldDisableNonVrUiLocked() {
4726 return mVrController.shouldDisableNonVrUiLocked();
4727 }
4728
Wale Ogunwale53783742018-09-16 10:21:51 -07004729 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004730 // 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 +00004731 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004732 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004733 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4734 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004735 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004736 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004737 }
4738 mH.post(() -> {
4739 if (!mVrController.onVrModeChanged(r)) {
4740 return;
4741 }
4742 synchronized (mGlobalLock) {
4743 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4744 mWindowManager.disableNonVrUi(disableNonVrUi);
4745 if (disableNonVrUi) {
4746 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4747 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004748 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004749 }
4750 }
4751 });
4752 }
4753
Wale Ogunwale53783742018-09-16 10:21:51 -07004754 @Override
4755 public int getPackageScreenCompatMode(String packageName) {
4756 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4757 synchronized (mGlobalLock) {
4758 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4759 }
4760 }
4761
4762 @Override
4763 public void setPackageScreenCompatMode(String packageName, int mode) {
4764 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4765 "setPackageScreenCompatMode");
4766 synchronized (mGlobalLock) {
4767 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4768 }
4769 }
4770
4771 @Override
4772 public boolean getPackageAskScreenCompat(String packageName) {
4773 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4774 synchronized (mGlobalLock) {
4775 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4776 }
4777 }
4778
4779 @Override
4780 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4781 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4782 "setPackageAskScreenCompat");
4783 synchronized (mGlobalLock) {
4784 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4785 }
4786 }
4787
Wale Ogunwale64258362018-10-16 15:13:37 -07004788 public static String relaunchReasonToString(int relaunchReason) {
4789 switch (relaunchReason) {
4790 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4791 return "window_resize";
4792 case RELAUNCH_REASON_FREE_RESIZE:
4793 return "free_resize";
4794 default:
4795 return null;
4796 }
4797 }
4798
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004799 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004800 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004801 }
4802
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004803 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004804 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004805 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4806 }
4807
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004808 boolean isKeyguardLocked() {
4809 return mKeyguardController.isKeyguardLocked();
4810 }
4811
Garfield Tan01548632018-11-27 10:15:48 -08004812 /**
4813 * Clears launch params for the given package.
4814 * @param packageNames the names of the packages of which the launch params are to be cleared
4815 */
4816 @Override
4817 public void clearLaunchParamsForPackages(List<String> packageNames) {
4818 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4819 "clearLaunchParamsForPackages");
4820 synchronized (mGlobalLock) {
4821 for (int i = 0; i < packageNames.size(); ++i) {
4822 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4823 }
4824 }
4825 }
4826
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004827 /**
4828 * Makes the display with the given id a single task instance display. I.e the display can only
4829 * contain one task.
4830 */
4831 @Override
4832 public void setDisplayToSingleTaskInstance(int displayId) {
4833 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4834 "setDisplayToSingleTaskInstance");
4835 final long origId = Binder.clearCallingIdentity();
4836 try {
Louis Chang677921f2019-12-06 16:44:24 +08004837 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004838 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004839 if (display != null) {
4840 display.setDisplayToSingleTaskInstance();
4841 }
4842 } finally {
4843 Binder.restoreCallingIdentity(origId);
4844 }
4845 }
4846
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004847 /**
4848 * Requests that an activity should enter picture-in-picture mode if possible.
4849 */
4850 @Override
4851 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4852 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4853 "requestPictureInPictureMode");
4854 final long origId = Binder.clearCallingIdentity();
4855 try {
4856 synchronized (mGlobalLock) {
4857 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4858 if (activity == null) {
4859 return;
4860 }
4861
jorgegil@google.com2e9cf022020-06-04 14:58:24 -07004862 if (isInPictureInPictureMode(activity)) {
4863 throw new IllegalStateException("Activity is already in PIP mode");
4864 }
4865
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004866 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4867 "requestPictureInPictureMode", /* beforeStopping */ false);
4868 if (!canEnterPictureInPicture) {
4869 throw new IllegalStateException(
4870 "Requested PIP on an activity that doesn't support it");
4871 }
4872
4873 try {
4874 final ClientTransaction transaction = ClientTransaction.obtain(
4875 activity.app.getThread(),
4876 activity.token);
4877 transaction.addCallback(EnterPipRequestedItem.obtain());
4878 getLifecycleManager().scheduleTransaction(transaction);
4879 } catch (Exception e) {
4880 Slog.w(TAG, "Failed to send enter pip requested item: "
4881 + activity.intent.getComponent(), e);
4882 }
4883 }
4884 } finally {
4885 Binder.restoreCallingIdentity(origId);
4886 }
4887 }
4888
Wale Ogunwale31913b52018-10-13 08:29:31 -07004889 void dumpLastANRLocked(PrintWriter pw) {
4890 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4891 if (mLastANRState == null) {
4892 pw.println(" <no ANR has occurred since boot>");
4893 } else {
4894 pw.println(mLastANRState);
4895 }
4896 }
4897
4898 void dumpLastANRTracesLocked(PrintWriter pw) {
4899 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4900
4901 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4902 if (ArrayUtils.isEmpty(files)) {
4903 pw.println(" <no ANR has occurred since boot>");
4904 return;
4905 }
4906 // Find the latest file.
4907 File latest = null;
4908 for (File f : files) {
4909 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4910 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004911 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004912 }
4913 pw.print("File: ");
4914 pw.print(latest.getName());
4915 pw.println();
4916 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4917 String line;
4918 while ((line = in.readLine()) != null) {
4919 pw.println(line);
4920 }
4921 } catch (IOException e) {
4922 pw.print("Unable to read: ");
4923 pw.print(e);
4924 pw.println();
4925 }
4926 }
4927
4928 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4929 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4930 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4931 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4932 }
4933
4934 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4935 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4936 pw.println(header);
4937
Louis Chang149d5c82019-12-30 09:47:39 +08004938 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004939 dumpPackage);
4940 boolean needSep = printedAnything;
4941
4942 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08004943 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Dianne Hackborn9106f2a2020-04-30 16:23:20 -07004944 " ResumedActivity: ", null);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004945 if (printed) {
4946 printedAnything = true;
4947 needSep = false;
4948 }
4949
4950 if (dumpPackage == null) {
4951 if (needSep) {
4952 pw.println();
4953 }
4954 printedAnything = true;
4955 mStackSupervisor.dump(pw, " ");
Winson Chung268eccb2020-03-26 13:43:44 -07004956 mTaskOrganizerController.dump(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004957 }
4958
4959 if (!printedAnything) {
4960 pw.println(" (nothing)");
4961 }
4962 }
4963
4964 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004965 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08004966 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004967 pw.println(" ");
4968 }
4969
4970 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4971 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4972 getActivityStartController().dump(pw, "", dumpPackage);
4973 }
4974
4975 /**
4976 * There are three things that cmd can be:
4977 * - a flattened component name that matches an existing activity
4978 * - the cmd arg isn't the flattened component name of an existing activity:
4979 * dump all activity whose component contains the cmd as a substring
4980 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004981 * <p>
4982 * The caller should not hold lock when calling this method because it will wait for the
4983 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004984 *
4985 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4986 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4987 */
4988 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4989 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4990 ArrayList<ActivityRecord> activities;
4991
4992 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004993 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004994 dumpFocusedStackOnly);
4995 }
4996
4997 if (activities.size() <= 0) {
4998 return false;
4999 }
5000
5001 String[] newArgs = new String[args.length - opti];
5002 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5003
Louis Changcdec0802019-11-11 11:45:07 +08005004 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005005 boolean needSep = false;
5006 for (int i = activities.size() - 1; i >= 0; i--) {
5007 ActivityRecord r = activities.get(i);
5008 if (needSep) {
5009 pw.println();
5010 }
5011 needSep = true;
5012 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005013 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005014 if (lastTask != task) {
5015 lastTask = task;
5016 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005017 pw.print(" id="); pw.print(lastTask.mTaskId);
5018 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005019 if (dumpAll) {
5020 lastTask.dump(pw, " ");
5021 }
5022 }
5023 }
5024 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5025 }
5026 return true;
5027 }
5028
5029 /**
5030 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5031 * there is a thread associated with the activity.
5032 */
5033 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5034 final ActivityRecord r, String[] args, boolean dumpAll) {
5035 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005036 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005037 synchronized (mGlobalLock) {
5038 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5039 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5040 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005041 if (r.hasProcess()) {
5042 pw.println(r.app.getPid());
5043 appThread = r.app.getThread();
5044 } else {
5045 pw.println("(not running)");
5046 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005047 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005048 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005049 }
5050 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005051 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005052 // flush anything that is already in the PrintWriter since the thread is going
5053 // to write to the file descriptor directly
5054 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005055 try (TransferPipe tp = new TransferPipe()) {
5056 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5057 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005058 } catch (IOException e) {
5059 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5060 } catch (RemoteException e) {
5061 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5062 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005063 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005064 }
5065
sanryhuang498e77e2018-12-06 14:57:01 +08005066 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5067 boolean testPssMode) {
5068 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5069 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5070 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
wilsonshih66071962020-07-10 10:45:23 +08005071 final int tokenSize = mRootWindowContainer.mSleepTokens.size();
5072 for (int i = 0; i < tokenSize; i++) {
5073 final RootWindowContainer.SleepToken st =
5074 mRootWindowContainer.mSleepTokens.valueAt(i);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005075 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5076 st.toString());
5077 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005078 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5079 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5080 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005081 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5082 testPssMode);
5083 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005084 }
5085
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005086 int getCurrentUserId() {
5087 return mAmInternal.getCurrentUserId();
5088 }
5089
5090 private void enforceNotIsolatedCaller(String caller) {
5091 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5092 throw new SecurityException("Isolated process not allowed to call " + caller);
5093 }
5094 }
5095
Wale Ogunwalef6733932018-06-27 05:14:34 -07005096 public Configuration getConfiguration() {
5097 Configuration ci;
5098 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005099 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005100 ci.userSetLocale = false;
5101 }
5102 return ci;
5103 }
5104
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005105 /**
5106 * Current global configuration information. Contains general settings for the entire system,
5107 * also corresponds to the merged configuration of the default display.
5108 */
5109 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005110 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005111 // while initializing process record for system, see {@link
5112 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005113 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005114 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005115 }
5116
5117 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5118 boolean initLocale) {
5119 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5120 }
5121
5122 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5123 boolean initLocale, boolean deferResume) {
5124 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5125 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5126 UserHandle.USER_NULL, deferResume);
5127 }
5128
Wale Ogunwale59507092018-10-29 09:00:30 -07005129 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005130 final long origId = Binder.clearCallingIdentity();
5131 try {
5132 synchronized (mGlobalLock) {
5133 updateConfigurationLocked(values, null, false, true, userId,
5134 false /* deferResume */);
5135 }
5136 } finally {
5137 Binder.restoreCallingIdentity(origId);
5138 }
5139 }
5140
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005141 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5142 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5143 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5144 deferResume, null /* result */);
5145 }
5146
5147 /**
5148 * Do either or both things: (1) change the current configuration, and (2)
5149 * make sure the given activity is running with the (now) current
5150 * configuration. Returns true if the activity has been left running, or
5151 * false if <var>starting</var> is being destroyed to match the new
5152 * configuration.
5153 *
5154 * @param userId is only used when persistent parameter is set to true to persist configuration
5155 * for that particular user
5156 */
5157 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5158 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5159 ActivityTaskManagerService.UpdateConfigurationResult result) {
5160 int changes = 0;
5161 boolean kept = true;
5162
Riddle Hsua0022cd2019-09-09 21:12:41 +08005163 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005164 try {
5165 if (values != null) {
5166 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5167 deferResume);
5168 }
5169
5170 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5171 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005172 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005173 }
5174
5175 if (result != null) {
5176 result.changes = changes;
5177 result.activityRelaunched = !kept;
5178 }
5179 return kept;
5180 }
5181
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005182 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005183 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005184 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005185
Louis Chang677921f2019-12-06 16:44:24 +08005186 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005187 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005188
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005189 mTempConfig.setTo(getGlobalConfiguration());
5190 final int changes = mTempConfig.updateFrom(values);
5191 if (changes == 0) {
5192 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5193 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5194 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5195 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005196 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005197 return 0;
5198 }
5199
5200 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5201 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005202 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005203 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005204 values.colorMode,
5205 values.densityDpi,
5206 values.fontScale,
5207 values.hardKeyboardHidden,
5208 values.keyboard,
5209 values.keyboardHidden,
5210 values.mcc,
5211 values.mnc,
5212 values.navigation,
5213 values.navigationHidden,
5214 values.orientation,
5215 values.screenHeightDp,
5216 values.screenLayout,
5217 values.screenWidthDp,
5218 values.smallestScreenWidthDp,
5219 values.touchscreen,
5220 values.uiMode);
5221
5222
5223 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5224 final LocaleList locales = values.getLocales();
5225 int bestLocaleIndex = 0;
5226 if (locales.size() > 1) {
5227 if (mSupportedSystemLocales == null) {
5228 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5229 }
5230 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5231 }
5232 SystemProperties.set("persist.sys.locale",
5233 locales.get(bestLocaleIndex).toLanguageTag());
5234 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005235
5236 final Message m = PooledLambda.obtainMessage(
5237 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5238 locales.get(bestLocaleIndex));
5239 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005240 }
5241
Yunfan Chen75157d72018-07-27 14:47:21 +09005242 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005243
5244 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005245 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005246
5247 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5248 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005249 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005250
5251 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005252 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005253
5254 AttributeCache ac = AttributeCache.instance();
5255 if (ac != null) {
5256 ac.updateConfiguration(mTempConfig);
5257 }
5258
5259 // Make sure all resources in our process are updated right now, so that anyone who is going
5260 // to retrieve resource values after we return will be sure to get the new ones. This is
5261 // especially important during boot, where the first config change needs to guarantee all
5262 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005263 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005264
5265 // We need another copy of global config because we're scheduling some calls instead of
5266 // running them in place. We need to be sure that object we send will be handled unchanged.
5267 final Configuration configCopy = new Configuration(mTempConfig);
5268 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005269 final Message msg = PooledLambda.obtainMessage(
5270 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5271 this, userId, configCopy);
5272 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005273 }
5274
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005275 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5276 for (int i = pidMap.size() - 1; i >= 0; i--) {
5277 final int pid = pidMap.keyAt(i);
5278 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005279 if (DEBUG_CONFIGURATION) {
5280 Slog.v(TAG_CONFIGURATION, "Update process config of "
5281 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005282 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005283 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005284 }
5285
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005286 final Message msg = PooledLambda.obtainMessage(
5287 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5288 mAmInternal, changes, initLocale);
5289 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005290
5291 // Override configuration of the default display duplicates global config, so we need to
5292 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005293 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005294 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005295
5296 return changes;
5297 }
5298
Riddle Hsua0022cd2019-09-09 21:12:41 +08005299 /** @see WindowSurfacePlacer#deferLayout */
5300 void deferWindowLayout() {
5301 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5302 // Reset the reasons at the first entrance because we only care about the changes in the
5303 // deferred scope.
5304 mLayoutReasons = 0;
5305 }
5306
5307 mWindowManager.mWindowPlacerLocked.deferLayout();
5308 }
5309
5310 /** @see WindowSurfacePlacer#continueLayout */
5311 void continueWindowLayout() {
5312 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5313 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5314 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5315 }
5316 }
5317
5318 /**
5319 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5320 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5321 * defer count is gone.
5322 */
5323 void addWindowLayoutReasons(@LayoutReason int reasons) {
5324 mLayoutReasons |= reasons;
5325 }
5326
Wale Ogunwalef6733932018-06-27 05:14:34 -07005327 private void updateEventDispatchingLocked(boolean booted) {
5328 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5329 }
5330
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005331 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5332 final ContentResolver resolver = mContext.getContentResolver();
5333 Settings.System.putConfigurationForUser(resolver, config, userId);
5334 }
5335
5336 private void sendLocaleToMountDaemonMsg(Locale l) {
5337 try {
5338 IBinder service = ServiceManager.getService("mount");
5339 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5340 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5341 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5342 } catch (RemoteException e) {
5343 Log.e(TAG, "Error storing locale for decryption UI", e);
5344 }
5345 }
5346
Alison Cichowlas3e340502018-08-07 17:15:01 -04005347 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5348 mStartActivitySources.remove(permissionToken);
5349 mExpiredStartAsCallerTokens.add(permissionToken);
5350 }
5351
5352 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5353 mExpiredStartAsCallerTokens.remove(permissionToken);
5354 }
5355
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005356 boolean isActivityStartsLoggingEnabled() {
5357 return mAmInternal.isActivityStartsLoggingEnabled();
5358 }
5359
Michal Karpinski8596ded2018-11-14 14:43:48 +00005360 boolean isBackgroundActivityStartsEnabled() {
5361 return mAmInternal.isBackgroundActivityStartsEnabled();
5362 }
5363
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005364 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5365 if (r == null || !r.hasProcess()) {
5366 return KEY_DISPATCHING_TIMEOUT_MS;
5367 }
5368 return getInputDispatchingTimeoutLocked(r.app);
5369 }
5370
5371 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005372 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005373 }
5374
Wale Ogunwalef6733932018-06-27 05:14:34 -07005375 /**
5376 * Decide based on the configuration whether we should show the ANR,
5377 * crash, etc dialogs. The idea is that if there is no affordance to
5378 * press the on-screen buttons, or the user experience would be more
5379 * greatly impacted than the crash itself, we shouldn't show the dialog.
5380 *
5381 * A thought: SystemUI might also want to get told about this, the Power
5382 * dialog / global actions also might want different behaviors.
5383 */
5384 private void updateShouldShowDialogsLocked(Configuration config) {
5385 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5386 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5387 && config.navigation == Configuration.NAVIGATION_NONAV);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005388 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5389 HIDE_ERROR_DIALOGS, 0) != 0;
Yuncheol Heo5d9b2712020-04-16 17:31:32 -07005390 mShowDialogs = inputMethodExists
Nikolas Havrikov7771e6e2020-06-19 11:45:34 +02005391 && ActivityTaskManager.currentUiModeSupportsErrorDialogs(config)
Yuncheol Heo5d9b2712020-04-16 17:31:32 -07005392 && !hideDialogsSet;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005393 }
5394
5395 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5396 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5397 FONT_SCALE, 1.0f, userId);
5398
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005399 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005400 if (getGlobalConfiguration().fontScale == scaleFactor) {
5401 return;
5402 }
5403
5404 final Configuration configuration
5405 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5406 configuration.fontScale = scaleFactor;
5407 updatePersistentConfiguration(configuration, userId);
5408 }
5409 }
5410
5411 // Actually is sleeping or shutting down or whatever else in the future
5412 // is an inactive state.
5413 boolean isSleepingOrShuttingDownLocked() {
5414 return isSleepingLocked() || mShuttingDown;
5415 }
5416
5417 boolean isSleepingLocked() {
5418 return mSleeping;
5419 }
5420
Riddle Hsu16567132018-08-16 21:37:47 +08005421 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005422 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005423 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005424 if (task.isActivityTypeStandard()) {
5425 if (mCurAppTimeTracker != r.appTimeTracker) {
5426 // We are switching app tracking. Complete the current one.
5427 if (mCurAppTimeTracker != null) {
5428 mCurAppTimeTracker.stop();
5429 mH.obtainMessage(
5430 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005431 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005432 mCurAppTimeTracker = null;
5433 }
5434 if (r.appTimeTracker != null) {
5435 mCurAppTimeTracker = r.appTimeTracker;
5436 startTimeTrackingFocusedActivityLocked();
5437 }
5438 } else {
5439 startTimeTrackingFocusedActivityLocked();
5440 }
5441 } else {
5442 r.appTimeTracker = null;
5443 }
5444 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5445 // TODO: Probably not, because we don't want to resume voice on switching
5446 // back to this activity
5447 if (task.voiceInteractor != null) {
5448 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5449 } else {
5450 finishRunningVoiceLocked();
5451
5452 if (mLastResumedActivity != null) {
5453 final IVoiceInteractionSession session;
5454
Louis Changcdec0802019-11-11 11:45:07 +08005455 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005456 if (lastResumedActivityTask != null
5457 && lastResumedActivityTask.voiceSession != null) {
5458 session = lastResumedActivityTask.voiceSession;
5459 } else {
5460 session = mLastResumedActivity.voiceSession;
5461 }
5462
5463 if (session != null) {
5464 // We had been in a voice interaction session, but now focused has
5465 // move to something different. Just finish the session, we can't
5466 // return to it and retain the proper state and synchronization with
5467 // the voice interaction service.
5468 finishVoiceTask(session);
5469 }
5470 }
5471 }
5472
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005473 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5474 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005475 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005476 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5477
Wale Ogunwalef6733932018-06-27 05:14:34 -07005478 updateResumedAppTrace(r);
5479 mLastResumedActivity = r;
5480
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005481 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005482
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005483 if (prevTask == null || task != prevTask) {
5484 if (prevTask != null) {
5485 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5486 }
5487 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5488 }
5489
Wale Ogunwalef6733932018-06-27 05:14:34 -07005490 applyUpdateLockStateLocked(r);
5491 applyUpdateVrModeLocked(r);
5492
Jeff Changd136e772019-11-05 20:33:52 +08005493 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005494 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005495 r == null ? "NULL" : r.shortComponentName,
5496 reason);
5497 }
5498
wilsonshih66071962020-07-10 10:45:23 +08005499 final class SleepTokenAcquirerImpl implements ActivityTaskManagerInternal.SleepTokenAcquirer {
5500 private final String mTag;
5501 private final SparseArray<RootWindowContainer.SleepToken> mSleepTokens =
5502 new SparseArray<>();
5503
5504 SleepTokenAcquirerImpl(@NonNull String tag) {
5505 mTag = tag;
5506 }
5507
5508 @Override
5509 public void acquire(int displayId) {
5510 synchronized (mGlobalLock) {
5511 if (!mSleepTokens.contains(displayId)) {
5512 mSleepTokens.append(displayId,
5513 mRootWindowContainer.createSleepToken(mTag, displayId));
5514 updateSleepIfNeededLocked();
5515 }
5516 }
5517 }
5518
5519 @Override
5520 public void release(int displayId) {
5521 synchronized (mGlobalLock) {
5522 final RootWindowContainer.SleepToken token = mSleepTokens.get(displayId);
5523 if (token != null) {
5524 mRootWindowContainer.removeSleepToken(token);
5525 mSleepTokens.remove(displayId);
5526 }
5527 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005528 }
5529 }
5530
5531 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005532 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005533 final boolean wasSleeping = mSleeping;
5534 boolean updateOomAdj = false;
5535
5536 if (!shouldSleep) {
5537 // If wasSleeping is true, we need to wake up activity manager state from when
5538 // we started sleeping. In either case, we need to apply the sleep tokens, which
5539 // will wake up stacks or put them to sleep as appropriate.
5540 if (wasSleeping) {
5541 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005542 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5543 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005544 startTimeTrackingFocusedActivityLocked();
5545 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005546 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005547 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5548 }
Louis Chang149d5c82019-12-30 09:47:39 +08005549 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005550 if (wasSleeping) {
5551 updateOomAdj = true;
5552 }
5553 } else if (!mSleeping && shouldSleep) {
5554 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005555 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5556 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005557 if (mCurAppTimeTracker != null) {
5558 mCurAppTimeTracker.stop();
5559 }
5560 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005561 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005562 mStackSupervisor.goingToSleepLocked();
5563 updateResumedAppTrace(null /* resumed */);
5564 updateOomAdj = true;
5565 }
5566 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005567 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005568 }
5569 }
5570
5571 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005572 mH.removeCallbacks(mUpdateOomAdjRunnable);
5573 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005574 }
5575
Wale Ogunwale53783742018-09-16 10:21:51 -07005576 void updateCpuStats() {
5577 mH.post(mAmInternal::updateCpuStats);
5578 }
5579
Hui Yu03d12402018-12-06 18:00:37 -08005580 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5581 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005582 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5583 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005584 mH.sendMessage(m);
5585 }
5586
Hui Yu03d12402018-12-06 18:00:37 -08005587 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005588 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005589 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005590 if (task != null) {
5591 final ActivityRecord rootActivity = task.getRootActivity();
5592 if (rootActivity != null) {
5593 taskRoot = rootActivity.mActivityComponent;
5594 }
5595 }
5596
Hui Yu03d12402018-12-06 18:00:37 -08005597 final Message m = PooledLambda.obtainMessage(
5598 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005599 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005600 mH.sendMessage(m);
5601 }
5602
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005603 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5604 String hostingType) {
5605 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005606 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5607 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005608 + activity.processName);
5609 }
5610 // Post message to start process to avoid possible deadlock of calling into AMS with the
5611 // ATMS lock held.
5612 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5613 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5614 isTop, hostingType, activity.intent.getComponent());
5615 mH.sendMessage(m);
5616 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005617 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005618 }
5619 }
5620
Wale Ogunwale53783742018-09-16 10:21:51 -07005621 void setBooting(boolean booting) {
5622 mAmInternal.setBooting(booting);
5623 }
5624
5625 boolean isBooting() {
5626 return mAmInternal.isBooting();
5627 }
5628
5629 void setBooted(boolean booted) {
5630 mAmInternal.setBooted(booted);
5631 }
5632
5633 boolean isBooted() {
5634 return mAmInternal.isBooted();
5635 }
5636
5637 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5638 mH.post(() -> {
5639 if (finishBooting) {
5640 mAmInternal.finishBooting();
5641 }
5642 if (enableScreen) {
5643 mInternal.enableScreenAfterBoot(isBooted());
5644 }
5645 });
5646 }
5647
5648 void setHeavyWeightProcess(ActivityRecord root) {
5649 mHeavyWeightProcess = root.app;
5650 final Message m = PooledLambda.obtainMessage(
5651 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005652 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005653 mH.sendMessage(m);
5654 }
5655
5656 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5657 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5658 return;
5659 }
5660
5661 mHeavyWeightProcess = null;
5662 final Message m = PooledLambda.obtainMessage(
5663 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5664 proc.mUserId);
5665 mH.sendMessage(m);
5666 }
5667
5668 private void cancelHeavyWeightProcessNotification(int userId) {
5669 final INotificationManager inm = NotificationManager.getService();
5670 if (inm == null) {
5671 return;
5672 }
5673 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005674 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005675 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5676 } catch (RuntimeException e) {
5677 Slog.w(TAG, "Error canceling notification for service", e);
5678 } catch (RemoteException e) {
5679 }
5680
5681 }
5682
5683 private void postHeavyWeightProcessNotification(
5684 WindowProcessController proc, Intent intent, int userId) {
5685 if (proc == null) {
5686 return;
5687 }
5688
5689 final INotificationManager inm = NotificationManager.getService();
5690 if (inm == null) {
5691 return;
5692 }
5693
5694 try {
5695 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5696 String text = mContext.getString(R.string.heavy_weight_notification,
5697 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5698 Notification notification =
5699 new Notification.Builder(context,
5700 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5701 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5702 .setWhen(0)
5703 .setOngoing(true)
5704 .setTicker(text)
5705 .setColor(mContext.getColor(
5706 com.android.internal.R.color.system_notification_accent_color))
5707 .setContentTitle(text)
5708 .setContentText(
5709 mContext.getText(R.string.heavy_weight_notification_detail))
5710 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5711 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5712 new UserHandle(userId)))
5713 .build();
5714 try {
5715 inm.enqueueNotificationWithTag("android", "android", null,
5716 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5717 } catch (RuntimeException e) {
5718 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5719 } catch (RemoteException e) {
5720 }
5721 } catch (PackageManager.NameNotFoundException e) {
5722 Slog.w(TAG, "Unable to create context for heavy notification", e);
5723 }
5724
5725 }
5726
Philip P. Moltmannee295092020-02-10 08:46:26 -08005727 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5728 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5729 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005730
5731 ActivityRecord activity = null;
5732 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5733 activity = ActivityRecord.isInStackLocked(token);
5734 if (activity == null) {
5735 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5736 return null;
5737 }
5738 if (activity.finishing) {
5739 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5740 return null;
5741 }
5742 }
5743
5744 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005745 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5746 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005747 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5748 if (noCreate) {
5749 return rec;
5750 }
5751 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5752 if (activity.pendingResults == null) {
5753 activity.pendingResults = new HashSet<>();
5754 }
5755 activity.pendingResults.add(rec.ref);
5756 }
5757 return rec;
5758 }
5759
Andrii Kulian52d255c2018-07-13 11:32:19 -07005760 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005761 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005762 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005763 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5764 mCurAppTimeTracker.start(resumedActivity.packageName);
5765 }
5766 }
5767
5768 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5769 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005770 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005771 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5772 }
5773 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005774 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005775 constructResumedTraceName(resumed.packageName), 0);
5776 }
5777 mTracedResumedActivity = resumed;
5778 }
5779
5780 private String constructResumedTraceName(String packageName) {
5781 return "focused app: " + packageName;
5782 }
5783
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005784 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005785 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005786 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005787 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005788 // mainStack is null during startup.
5789 if (mainStack != null) {
5790 if (changes != 0 && starting == null) {
5791 // If the configuration changed, and the caller is not already
5792 // in the process of starting an activity, then find the top
5793 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005794 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005795 }
5796
5797 if (starting != null) {
5798 kept = starting.ensureActivityConfiguration(changes,
5799 false /* preserveWindow */);
5800 // And we need to make sure at this point that all other activities
5801 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005802 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005803 !PRESERVE_WINDOWS);
5804 }
5805 }
5806
5807 return kept;
5808 }
5809
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005810 void scheduleAppGcsLocked() {
5811 mH.post(() -> mAmInternal.scheduleAppGcs());
5812 }
5813
Wale Ogunwale53783742018-09-16 10:21:51 -07005814 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5815 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5816 }
5817
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005818 /**
5819 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5820 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5821 * on demand.
5822 */
5823 IPackageManager getPackageManager() {
5824 return AppGlobals.getPackageManager();
5825 }
5826
5827 PackageManagerInternal getPackageManagerInternalLocked() {
5828 if (mPmInternal == null) {
5829 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5830 }
5831 return mPmInternal;
5832 }
5833
Darryl L Johnsona0982222020-02-18 18:21:51 -08005834 ComponentName getSysUiServiceComponentLocked() {
5835 if (mSysUiServiceComponent == null) {
5836 final PackageManagerInternal pm = getPackageManagerInternalLocked();
5837 mSysUiServiceComponent = pm.getSystemUiServiceComponent();
5838 }
5839 return mSysUiServiceComponent;
5840 }
5841
Hai Zhangf4da9be2019-05-01 13:46:06 +08005842 PermissionPolicyInternal getPermissionPolicyInternal() {
5843 if (mPermissionPolicyInternal == null) {
5844 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5845 }
5846 return mPermissionPolicyInternal;
5847 }
5848
Wale Ogunwale008163e2018-07-23 23:11:08 -07005849 AppWarnings getAppWarningsLocked() {
5850 return mAppWarnings;
5851 }
5852
Wale Ogunwale214f3482018-10-04 11:00:47 -07005853 Intent getHomeIntent() {
5854 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5855 intent.setComponent(mTopComponent);
5856 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5857 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5858 intent.addCategory(Intent.CATEGORY_HOME);
5859 }
5860 return intent;
5861 }
5862
Chilun2ef71f72018-11-16 17:57:15 +08005863 /**
5864 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5865 * activities.
5866 *
Chilun939b05c2020-02-19 14:50:59 +08005867 * @param preferredPackage Specify a preferred package name, otherwise use the package name
5868 * defined in config_secondaryHomePackage.
Chilun2ef71f72018-11-16 17:57:15 +08005869 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5870 */
5871 Intent getSecondaryHomeIntent(String preferredPackage) {
5872 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005873 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5874 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5875 if (preferredPackage == null || useSystemProvidedLauncher) {
Chilun939b05c2020-02-19 14:50:59 +08005876 // Using the package name stored in config if no preferred package name or forced.
5877 final String secondaryHomePackage = mContext.getResources().getString(
5878 com.android.internal.R.string.config_secondaryHomePackage);
5879 intent.setPackage(secondaryHomePackage);
Chilun2ef71f72018-11-16 17:57:15 +08005880 } else {
5881 intent.setPackage(preferredPackage);
5882 }
5883 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5884 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5885 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5886 }
5887 return intent;
5888 }
5889
Wale Ogunwale214f3482018-10-04 11:00:47 -07005890 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5891 if (info == null) return null;
5892 ApplicationInfo newInfo = new ApplicationInfo(info);
5893 newInfo.initForUser(userId);
5894 return newInfo;
5895 }
5896
Wale Ogunwale9c103022018-10-18 07:44:54 -07005897 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005898 if (uid == SYSTEM_UID) {
5899 // The system gets to run in any process. If there are multiple processes with the same
5900 // uid, just pick the first (this should never happen).
5901 final SparseArray<WindowProcessController> procs =
5902 mProcessNames.getMap().get(processName);
5903 if (procs == null) return null;
5904 final int procCount = procs.size();
5905 for (int i = 0; i < procCount; i++) {
5906 final int procUid = procs.keyAt(i);
5907 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5908 // Don't use an app process or different user process for system component.
5909 continue;
5910 }
5911 return procs.valueAt(i);
5912 }
5913 }
5914
5915 return mProcessNames.get(processName, uid);
5916 }
5917
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005918 WindowProcessController getProcessController(IApplicationThread thread) {
5919 if (thread == null) {
5920 return null;
5921 }
5922
5923 final IBinder threadBinder = thread.asBinder();
5924 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5925 for (int i = pmap.size()-1; i >= 0; i--) {
5926 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5927 for (int j = procs.size() - 1; j >= 0; j--) {
5928 final WindowProcessController proc = procs.valueAt(j);
5929 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5930 return proc;
5931 }
5932 }
5933 }
5934
5935 return null;
5936 }
5937
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005938 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005939 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005940 if (proc == null) return null;
5941 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5942 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005943 }
5944 return null;
5945 }
5946
Riddle Hsua0536432019-02-16 00:38:59 +08005947 int getUidState(int uid) {
5948 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005949 }
5950
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005951 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005952 // A uid is considered to be foreground if it has a visible non-toast window.
5953 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005954 }
5955
Ricky Wai96f5c352019-04-10 18:40:17 +01005956 boolean isDeviceOwner(int uid) {
5957 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005958 }
5959
Ricky Wai96f5c352019-04-10 18:40:17 +01005960 void setDeviceOwnerUid(int uid) {
5961 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005962 }
5963
Wale Ogunwale9de19442018-10-18 19:05:03 -07005964 /**
Louis Changc2236422020-09-14 17:52:02 +08005965 * @return allowlist tag for a uid from mPendingTempAllowlist, null if not currently on
5966 * the allowlist
Wale Ogunwale9de19442018-10-18 19:05:03 -07005967 */
Louis Changc2236422020-09-14 17:52:02 +08005968 String getPendingTempAllowlistTagForUidLocked(int uid) {
5969 return mPendingTempAllowlist.get(uid);
Wale Ogunwale9de19442018-10-18 19:05:03 -07005970 }
5971
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005972 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5973 if (true || Build.IS_USER) {
5974 return;
5975 }
5976
5977 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5978 StrictMode.allowThreadDiskWrites();
5979 try {
5980 File tracesDir = new File("/data/anr");
5981 File tracesFile = null;
5982 try {
5983 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5984
5985 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005986 String timeString =
5987 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5988 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005989 sb.append(": ");
5990 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5991 sb.append(" since ");
5992 sb.append(msg);
5993 FileOutputStream fos = new FileOutputStream(tracesFile);
5994 fos.write(sb.toString().getBytes());
5995 if (app == null) {
5996 fos.write("\n*** No application process!".getBytes());
5997 }
5998 fos.close();
5999 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6000 } catch (IOException e) {
6001 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6002 return;
6003 }
6004
6005 if (app != null && app.getPid() > 0) {
6006 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6007 firstPids.add(app.getPid());
6008 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6009 }
6010
6011 File lastTracesFile = null;
6012 File curTracesFile = null;
6013 for (int i=9; i>=0; i--) {
6014 String name = String.format(Locale.US, "slow%02d.txt", i);
6015 curTracesFile = new File(tracesDir, name);
6016 if (curTracesFile.exists()) {
6017 if (lastTracesFile != null) {
6018 curTracesFile.renameTo(lastTracesFile);
6019 } else {
6020 curTracesFile.delete();
6021 }
6022 }
6023 lastTracesFile = curTracesFile;
6024 }
6025 tracesFile.renameTo(curTracesFile);
6026 } finally {
6027 StrictMode.setThreadPolicy(oldPolicy);
6028 }
6029 }
6030
Michal Karpinskida34cd42019-04-02 19:46:52 +01006031 boolean isAssociatedCompanionApp(int userId, int uid) {
6032 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6033 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006034 return false;
6035 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006036 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006037 }
6038
Issei Suzuki734bc942019-06-05 13:59:52 +02006039 void notifySingleTaskDisplayEmpty(int displayId) {
6040 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6041 }
6042
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006043 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006044 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006045
6046
Wale Ogunwale98875612018-10-12 07:53:02 -07006047 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6048 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006049
Riddle Hsud93a6c42018-11-29 21:50:06 +08006050 H(Looper looper) {
6051 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006052 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006053
6054 @Override
6055 public void handleMessage(Message msg) {
6056 switch (msg.what) {
6057 case REPORT_TIME_TRACKER_MSG: {
6058 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6059 tracker.deliverResult(mContext);
6060 } break;
6061 }
6062 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006063 }
6064
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006065 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006066 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006067
6068 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006069 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006070 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006071
6072 @Override
6073 public void handleMessage(Message msg) {
6074 switch (msg.what) {
6075 case DISMISS_DIALOG_UI_MSG: {
6076 final Dialog d = (Dialog) msg.obj;
6077 d.dismiss();
6078 break;
6079 }
6080 }
6081 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006082 }
6083
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006084 final class LocalService extends ActivityTaskManagerInternal {
6085 @Override
wilsonshih66071962020-07-10 10:45:23 +08006086 public SleepTokenAcquirer createSleepTokenAcquirer(@NonNull String tag) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006087 Objects.requireNonNull(tag);
wilsonshih66071962020-07-10 10:45:23 +08006088 return new SleepTokenAcquirerImpl(tag);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006089 }
6090
6091 @Override
6092 public ComponentName getHomeActivityForUser(int userId) {
6093 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006094 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006095 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006096 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006097 }
6098 }
6099
6100 @Override
6101 public void onLocalVoiceInteractionStarted(IBinder activity,
6102 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6103 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006104 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006105 }
6106 }
6107
6108 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006109 public void notifySingleTaskDisplayDrawn(int displayId) {
6110 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6111 }
6112
6113 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006114 public List<IBinder> getTopVisibleActivities() {
6115 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006116 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006117 }
6118 }
6119
6120 @Override
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00006121 public boolean hasResumedActivity(int uid) {
6122 synchronized (mGlobalLock) {
6123 final ArraySet<WindowProcessController> processes = mProcessMap.getProcesses(uid);
6124 for (int i = 0, n = processes.size(); i < n; i++) {
6125 final WindowProcessController process = processes.valueAt(i);
6126 if (process.hasResumedActivity()) {
6127 return true;
6128 }
6129 }
6130 }
6131 return false;
6132 }
6133
6134 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006135 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6136 int userId, Intent[] intents, Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006137 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006138 final String[] resolvedTypes = new String[intents.length];
6139
6140 // UID of the package on user userId.
6141 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6142 // packageUid may not be initialized.
6143 int packageUid = 0;
6144 final long ident = Binder.clearCallingIdentity();
6145
6146 try {
6147 for (int i = 0; i < intents.length; i++) {
6148 resolvedTypes[i] =
6149 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6150 }
6151
6152 packageUid = AppGlobals.getPackageManager().getPackageUid(
6153 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6154 } catch (RemoteException e) {
6155 // Shouldn't happen.
6156 } finally {
6157 Binder.restoreCallingIdentity(ident);
6158 }
6159
Riddle Hsu591bf612019-02-14 17:55:31 +08006160 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006161 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006162 intents, resolvedTypes, null /* resultTo */,
6163 SafeActivityOptions.fromBundle(bOptions), userId,
6164 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6165 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006166 }
6167
6168 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006169 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006170 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6171 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6172 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006173 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006174 assertPackageMatchesCallingUid(callingPackage);
Jeff Sharkey1d1e7532020-06-03 13:05:01 -06006175 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6176 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6177 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
6178 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006179 }
6180
6181 @Override
6182 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006183 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6184 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6185 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6186 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006187 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006188 assertPackageMatchesCallingUid(callingPackage);
Jeff Sharkey1d1e7532020-06-03 13:05:01 -06006189 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6190 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6191 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6192 reason, validateIncomingUser, originatingPendingIntent,
6193 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006194 }
6195
6196 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006197 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006198 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6199 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006200 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006201 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006202 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006203 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006204 false /*validateIncomingUser*/);
6205 }
6206
6207 @Override
lumark588a3e82018-07-20 18:53:54 +08006208 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006209 synchronized (mGlobalLock) {
6210
6211 // We might change the visibilities here, so prepare an empty app transition which
6212 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006213 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006214 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006215 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006216 return;
6217 }
Louis Chang677921f2019-12-06 16:44:24 +08006218 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006219 final boolean wasTransitionSet =
6220 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006221 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006222 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006223 }
Louis Chang149d5c82019-12-30 09:47:39 +08006224 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006225
6226 // If there was a transition set already we don't want to interfere with it as we
6227 // might be starting it too early.
6228 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006229 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006230 }
6231 }
6232 if (callback != null) {
6233 callback.run();
6234 }
6235 }
6236
6237 @Override
6238 public void notifyKeyguardTrustedChanged() {
6239 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006240 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006241 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006242 }
6243 }
6244 }
6245
6246 /**
6247 * Called after virtual display Id is updated by
6248 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6249 * {@param vrVr2dDisplayId}.
6250 */
6251 @Override
6252 public void setVr2dDisplayId(int vr2dDisplayId) {
6253 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6254 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006255 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006256 }
6257 }
6258
6259 @Override
6260 public void setFocusedActivity(IBinder token) {
6261 synchronized (mGlobalLock) {
6262 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6263 if (r == null) {
6264 throw new IllegalArgumentException(
6265 "setFocusedActivity: No activity record matching token=" + token);
6266 }
Louis Chang19443452018-10-09 12:10:21 +08006267 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006268 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006269 }
6270 }
6271 }
6272
6273 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006274 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006275 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006276 }
6277
6278 @Override
6279 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006280 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006281 }
6282
6283 @Override
6284 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006285 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006286 }
6287
6288 @Override
6289 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6290 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6291 }
6292
6293 @Override
6294 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006295 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006296 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006297
6298 @Override
6299 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6300 synchronized (mGlobalLock) {
6301 mActiveVoiceInteractionServiceComponent = component;
6302 }
6303 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006304
6305 @Override
Galia Peycheva480275a2020-03-18 17:33:42 +01006306 public void notifyDreamStateChanged(boolean dreaming) {
6307 synchronized (mGlobalLock) {
6308 mDreaming = dreaming;
6309 }
6310 }
6311
6312 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006313 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6314 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6315 return;
6316 }
6317 synchronized (mGlobalLock) {
6318 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6319 if (types == null) {
6320 if (uid < 0) {
6321 return;
6322 }
6323 types = new ArrayMap<>();
6324 mAllowAppSwitchUids.put(userId, types);
6325 }
6326 if (uid < 0) {
6327 types.remove(type);
6328 } else {
6329 types.put(type, uid);
6330 }
6331 }
6332 }
6333
6334 @Override
6335 public void onUserStopped(int userId) {
6336 synchronized (mGlobalLock) {
6337 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6338 mAllowAppSwitchUids.remove(userId);
6339 }
6340 }
6341
6342 @Override
6343 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6344 synchronized (mGlobalLock) {
6345 return ActivityTaskManagerService.this.isGetTasksAllowed(
6346 caller, callingPid, callingUid);
6347 }
6348 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006349
Riddle Hsua0536432019-02-16 00:38:59 +08006350 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006351 @Override
6352 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006353 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006354 mProcessNames.put(proc.mName, proc.mUid, proc);
6355 }
6356 }
6357
Riddle Hsua0536432019-02-16 00:38:59 +08006358 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006359 @Override
6360 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006361 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006362 mProcessNames.remove(name, uid);
6363 }
6364 }
6365
Riddle Hsua0536432019-02-16 00:38:59 +08006366 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006367 @Override
6368 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006369 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006370 if (proc == mHomeProcess) {
6371 mHomeProcess = null;
6372 }
6373 if (proc == mPreviousProcess) {
6374 mPreviousProcess = null;
6375 }
6376 }
6377 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006378
Riddle Hsua0536432019-02-16 00:38:59 +08006379 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006380 @Override
6381 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006382 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006383 return mTopProcessState;
6384 }
6385 }
6386
Riddle Hsua0536432019-02-16 00:38:59 +08006387 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006388 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006389 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006390 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006391 return proc == mHeavyWeightProcess;
6392 }
6393 }
6394
Riddle Hsua0536432019-02-16 00:38:59 +08006395 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006396 @Override
6397 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006398 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006399 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6400 }
6401 }
6402
6403 @Override
6404 public void finishHeavyWeightApp() {
6405 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006406 if (mHeavyWeightProcess != null) {
6407 mHeavyWeightProcess.finishActivities();
6408 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006409 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6410 mHeavyWeightProcess);
6411 }
6412 }
6413
Galia Peycheva480275a2020-03-18 17:33:42 +01006414 @Override
6415 public boolean isDreaming() {
6416 synchronized (mGlobalLock) {
6417 return mDreaming;
6418 }
6419 }
6420
Riddle Hsua0536432019-02-16 00:38:59 +08006421 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006422 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006423 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006424 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006425 return isSleepingLocked();
6426 }
6427 }
6428
6429 @Override
6430 public boolean isShuttingDown() {
6431 synchronized (mGlobalLock) {
6432 return mShuttingDown;
6433 }
6434 }
6435
6436 @Override
6437 public boolean shuttingDown(boolean booted, int timeout) {
6438 synchronized (mGlobalLock) {
6439 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006440 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006441 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006442 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006443 return mStackSupervisor.shutdownLocked(timeout);
6444 }
6445 }
6446
6447 @Override
6448 public void enableScreenAfterBoot(boolean booted) {
bepheis gaoa312f812020-08-10 22:20:47 +08006449 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
6450 mWindowManager.enableScreenAfterBoot();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006451 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006452 updateEventDispatchingLocked(booted);
6453 }
6454 }
6455
6456 @Override
6457 public boolean showStrictModeViolationDialog() {
6458 synchronized (mGlobalLock) {
6459 return mShowDialogs && !mSleeping && !mShuttingDown;
6460 }
6461 }
6462
6463 @Override
6464 public void showSystemReadyErrorDialogsIfNeeded() {
6465 synchronized (mGlobalLock) {
6466 try {
6467 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6468 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6469 + " data partition or your device will be unstable.");
6470 mUiHandler.post(() -> {
6471 if (mShowDialogs) {
6472 AlertDialog d = new BaseErrorDialog(mUiContext);
6473 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6474 d.setCancelable(false);
6475 d.setTitle(mUiContext.getText(R.string.android_system_label));
6476 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6477 d.setButton(DialogInterface.BUTTON_POSITIVE,
6478 mUiContext.getText(R.string.ok),
6479 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6480 d.show();
6481 }
6482 });
6483 }
6484 } catch (RemoteException e) {
6485 }
6486
6487 if (!Build.isBuildConsistent()) {
6488 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6489 mUiHandler.post(() -> {
6490 if (mShowDialogs) {
6491 AlertDialog d = new BaseErrorDialog(mUiContext);
6492 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6493 d.setCancelable(false);
6494 d.setTitle(mUiContext.getText(R.string.android_system_label));
6495 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6496 d.setButton(DialogInterface.BUTTON_POSITIVE,
6497 mUiContext.getText(R.string.ok),
6498 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6499 d.show();
6500 }
6501 });
6502 }
6503 }
6504 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006505
6506 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006507 public void onProcessMapped(int pid, WindowProcessController proc) {
6508 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006509 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006510 }
6511 }
6512
6513 @Override
6514 public void onProcessUnMapped(int pid) {
6515 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006516 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006517 }
6518 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006519
6520 @Override
6521 public void onPackageDataCleared(String name) {
6522 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006523 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006524 mAppWarnings.onPackageDataCleared(name);
6525 }
6526 }
6527
6528 @Override
6529 public void onPackageUninstalled(String name) {
6530 synchronized (mGlobalLock) {
6531 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006532 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006533 }
6534 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006535
6536 @Override
6537 public void onPackageAdded(String name, boolean replacing) {
6538 synchronized (mGlobalLock) {
6539 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6540 }
6541 }
6542
6543 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006544 public void onPackageReplaced(ApplicationInfo aInfo) {
6545 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006546 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006547 }
6548 }
6549
6550 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006551 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6552 synchronized (mGlobalLock) {
6553 return compatibilityInfoForPackageLocked(ai);
6554 }
6555 }
6556
Yunfan Chen75157d72018-07-27 14:47:21 +09006557 /**
6558 * Set the corresponding display information for the process global configuration. To be
6559 * called when we need to show IME on a different display.
6560 *
6561 * @param pid The process id associated with the IME window.
6562 * @param displayId The ID of the display showing the IME.
6563 */
6564 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006565 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006566 // Don't update process-level configuration for Multi-Client IME process since other
6567 // IMEs on other displays will also receive this configuration change due to IME
6568 // services use the same application config/context.
6569 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006570
Yunfan Chen75157d72018-07-27 14:47:21 +09006571 if (pid == MY_PID || pid < 0) {
6572 if (DEBUG_CONFIGURATION) {
6573 Slog.w(TAG,
6574 "Trying to update display configuration for system/invalid process.");
6575 }
6576 return;
6577 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006578 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006579 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006580 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006581 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006582 // Call might come when display is not yet added or has been removed.
6583 if (DEBUG_CONFIGURATION) {
6584 Slog.w(TAG, "Trying to update display configuration for non-existing "
6585 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006586 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006587 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006588 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006589 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006590 if (process == null) {
6591 if (DEBUG_CONFIGURATION) {
6592 Slog.w(TAG, "Trying to update display configuration for invalid "
6593 + "process, pid=" + pid);
6594 }
6595 return;
6596 }
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006597 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006598 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006599 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006600
6601 @Override
6602 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006603 int requestCode, int resultCode, Intent data) {
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06006604 final ActivityRecord r;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006605 synchronized (mGlobalLock) {
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06006606 r = ActivityRecord.isInStackLocked(activityToken);
6607 if (r == null || r.getRootTask() == null) {
6608 return;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006609 }
6610 }
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06006611
6612 // Carefully collect grants without holding lock
6613 final NeededUriGrants dataGrants = collectGrants(data, r);
6614
6615 synchronized (mGlobalLock) {
6616 r.sendResult(callingUid, resultWho, requestCode, resultCode, data, dataGrants);
6617 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006618 }
6619
6620 @Override
6621 public void clearPendingResultForActivity(IBinder activityToken,
6622 WeakReference<PendingIntentRecord> pir) {
6623 synchronized (mGlobalLock) {
6624 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6625 if (r != null && r.pendingResults != null) {
6626 r.pendingResults.remove(pir);
6627 }
6628 }
6629 }
6630
6631 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006632 public ActivityTokens getTopActivityForTask(int taskId) {
6633 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006634 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006635 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006636 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6637 + " Requested task not found");
6638 return null;
6639 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006640 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006641 if (activity == null) {
6642 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6643 + " Requested activity not found");
6644 return null;
6645 }
6646 if (!activity.attachedToProcess()) {
6647 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6648 + activity);
6649 return null;
6650 }
6651 return new ActivityTokens(activity.appToken, activity.assistToken,
6652 activity.app.getThread());
6653 }
6654 }
6655
6656 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006657 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006658 @Nullable String featureId, int callingUid, int userId, IBinder token,
6659 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6660 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006661 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006662 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6663 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006664 }
6665 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006666
6667 @Override
6668 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6669 synchronized (mGlobalLock) {
6670 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6671 if (r == null) {
6672 return null;
6673 }
6674 if (r.mServiceConnectionsHolder == null) {
6675 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6676 ActivityTaskManagerService.this, r);
6677 }
6678
6679 return r.mServiceConnectionsHolder;
6680 }
6681 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006682
6683 @Override
6684 public Intent getHomeIntent() {
6685 synchronized (mGlobalLock) {
6686 return ActivityTaskManagerService.this.getHomeIntent();
6687 }
6688 }
6689
6690 @Override
6691 public boolean startHomeActivity(int userId, String reason) {
6692 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006693 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006694 }
6695 }
6696
6697 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006698 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006699 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006700 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006701 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006702 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006703 }
Chilun8b1f1be2019-03-13 17:14:36 +08006704 }
6705
6706 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006707 public boolean startHomeOnAllDisplays(int userId, String reason) {
6708 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006709 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006710 }
6711 }
6712
Riddle Hsua0536432019-02-16 00:38:59 +08006713 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006714 @Override
6715 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006716 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006717 if (mFactoryTest == FACTORY_TEST_OFF) {
6718 return false;
6719 }
6720 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6721 && wpc.mName.equals(mTopComponent.getPackageName())) {
6722 return true;
6723 }
6724 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6725 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6726 }
6727 }
6728
6729 @Override
6730 public void updateTopComponentForFactoryTest() {
6731 synchronized (mGlobalLock) {
6732 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6733 return;
6734 }
6735 final ResolveInfo ri = mContext.getPackageManager()
6736 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6737 final CharSequence errorMsg;
6738 if (ri != null) {
6739 final ActivityInfo ai = ri.activityInfo;
6740 final ApplicationInfo app = ai.applicationInfo;
6741 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6742 mTopAction = Intent.ACTION_FACTORY_TEST;
6743 mTopData = null;
6744 mTopComponent = new ComponentName(app.packageName, ai.name);
6745 errorMsg = null;
6746 } else {
6747 errorMsg = mContext.getResources().getText(
6748 com.android.internal.R.string.factorytest_not_system);
6749 }
6750 } else {
6751 errorMsg = mContext.getResources().getText(
6752 com.android.internal.R.string.factorytest_no_action);
6753 }
6754 if (errorMsg == null) {
6755 return;
6756 }
6757
6758 mTopAction = null;
6759 mTopData = null;
6760 mTopComponent = null;
6761 mUiHandler.post(() -> {
6762 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6763 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006764 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006765 });
6766 }
6767 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006768
Riddle Hsua0536432019-02-16 00:38:59 +08006769 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006770 @Override
6771 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6772 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006773 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006774 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006775 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006776
6777 wpc.clearRecentTasks();
6778 wpc.clearActivities();
6779
6780 if (wpc.isInstrumenting()) {
6781 finishInstrumentationCallback.run();
6782 }
6783
Jorim Jaggid0752812018-10-16 16:07:20 +02006784 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006785 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006786 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006787 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006788 // If there was nothing to resume, and we are not already restarting
6789 // this process, but there is a visible activity that is hosted by the
6790 // process...then make sure all visible activities are running, taking
6791 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006792 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006793 !PRESERVE_WINDOWS);
6794 }
6795 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006796 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006797 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006798 }
6799 }
6800 }
6801
6802 @Override
6803 public void closeSystemDialogs(String reason) {
6804 enforceNotIsolatedCaller("closeSystemDialogs");
6805
6806 final int pid = Binder.getCallingPid();
6807 final int uid = Binder.getCallingUid();
6808 final long origId = Binder.clearCallingIdentity();
6809 try {
6810 synchronized (mGlobalLock) {
6811 // Only allow this from foreground processes, so that background
6812 // applications can't abuse it to prevent system UI from being shown.
6813 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006814 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006815 if (!proc.isPerceptible()) {
6816 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6817 + " from background process " + proc);
6818 return;
6819 }
6820 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006821 mWindowManager.closeSystemDialogs(reason);
6822
Galia Peycheva72d581e2020-06-12 10:06:40 +02006823 mRootWindowContainer.closeSystemDialogActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006824 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006825 // Call into AM outside the synchronized block.
6826 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006827 } finally {
6828 Binder.restoreCallingIdentity(origId);
6829 }
6830 }
6831
6832 @Override
6833 public void cleanupDisabledPackageComponents(
6834 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6835 synchronized (mGlobalLock) {
6836 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006837 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006838 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006839 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006840 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006841 }
6842
6843 // Clean-up disabled tasks
6844 getRecentTasks().cleanupDisabledPackageTasksLocked(
6845 packageName, disabledClasses, userId);
6846 }
6847 }
6848
6849 @Override
6850 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6851 int userId) {
6852 synchronized (mGlobalLock) {
6853
6854 boolean didSomething =
6855 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006856 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006857 null, doit, evenPersistent, userId);
6858 return didSomething;
6859 }
6860 }
6861
6862 @Override
6863 public void resumeTopActivities(boolean scheduleIdle) {
6864 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006865 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006866 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006867 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006868 }
6869 }
6870 }
6871
Riddle Hsua0536432019-02-16 00:38:59 +08006872 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006873 @Override
6874 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006875 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006876 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6877 }
6878 }
6879
Riddle Hsua0536432019-02-16 00:38:59 +08006880 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006881 @Override
6882 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006883 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006884 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6885 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6886 }
6887 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006888 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006889 } finally {
6890 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6891 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006892 }
6893 }
6894
6895 @Override
6896 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6897 try {
6898 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6899 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6900 }
6901 } catch (RemoteException ex) {
6902 throw new SecurityException("Fail to check is caller a privileged app", ex);
6903 }
6904
6905 synchronized (mGlobalLock) {
6906 final long ident = Binder.clearCallingIdentity();
6907 try {
6908 if (mAmInternal.shouldConfirmCredentials(userId)) {
6909 if (mKeyguardController.isKeyguardLocked()) {
6910 // Showing launcher to avoid user entering credential twice.
6911 startHomeActivity(currentUserId, "notifyLockedProfile");
6912 }
Louis Chang149d5c82019-12-30 09:47:39 +08006913 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006914 }
6915 } finally {
6916 Binder.restoreCallingIdentity(ident);
6917 }
6918 }
6919 }
6920
6921 @Override
6922 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6923 mAmInternal.enforceCallingPermission(
6924 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6925
6926 synchronized (mGlobalLock) {
6927 final long ident = Binder.clearCallingIdentity();
6928 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006929 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6930 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006931 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006932 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6933 UserHandle.CURRENT);
6934 } finally {
6935 Binder.restoreCallingIdentity(ident);
6936 }
6937 }
6938 }
6939
6940 @Override
6941 public void writeActivitiesToProto(ProtoOutputStream proto) {
6942 synchronized (mGlobalLock) {
6943 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006944 mRootWindowContainer.dumpDebug(
6945 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006946 }
6947 }
6948
6949 @Override
6950 public void saveANRState(String reason) {
6951 synchronized (mGlobalLock) {
6952 final StringWriter sw = new StringWriter();
6953 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6954 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6955 if (reason != null) {
6956 pw.println(" Reason: " + reason);
6957 }
6958 pw.println();
6959 getActivityStartController().dump(pw, " ", null);
6960 pw.println();
6961 pw.println("-------------------------------------------------------------------------------");
6962 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6963 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6964 "" /* header */);
6965 pw.println();
6966 pw.close();
6967
6968 mLastANRState = sw.toString();
6969 }
6970 }
6971
6972 @Override
6973 public void clearSavedANRState() {
6974 synchronized (mGlobalLock) {
6975 mLastANRState = null;
6976 }
6977 }
6978
6979 @Override
6980 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6981 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6982 synchronized (mGlobalLock) {
6983 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6984 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6985 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6986 dumpLastANRLocked(pw);
6987 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6988 dumpLastANRTracesLocked(pw);
6989 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6990 dumpActivityStarterLocked(pw, dumpPackage);
6991 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6992 dumpActivityContainersLocked(pw);
6993 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6994 if (getRecentTasks() != null) {
6995 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6996 }
6997 }
6998 }
6999 }
7000
7001 @Override
7002 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7003 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7004 int wakefulness) {
7005 synchronized (mGlobalLock) {
7006 if (mHomeProcess != null && (dumpPackage == null
7007 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7008 if (needSep) {
7009 pw.println();
7010 needSep = false;
7011 }
7012 pw.println(" mHomeProcess: " + mHomeProcess);
7013 }
7014 if (mPreviousProcess != null && (dumpPackage == null
7015 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7016 if (needSep) {
7017 pw.println();
7018 needSep = false;
7019 }
7020 pw.println(" mPreviousProcess: " + mPreviousProcess);
7021 }
7022 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7023 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7024 StringBuilder sb = new StringBuilder(128);
7025 sb.append(" mPreviousProcessVisibleTime: ");
7026 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7027 pw.println(sb);
7028 }
7029 if (mHeavyWeightProcess != null && (dumpPackage == null
7030 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7031 if (needSep) {
7032 pw.println();
7033 needSep = false;
7034 }
7035 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7036 }
7037 if (dumpPackage == null) {
7038 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007039 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007040 }
7041 if (dumpAll) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007042 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7043 if (dumpPackage == null && topFocusedStack != null) {
7044 pw.println(" mConfigWillChange: " + topFocusedStack.mConfigWillChange);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007045 }
7046 if (mCompatModePackages.getPackages().size() > 0) {
7047 boolean printed = false;
7048 for (Map.Entry<String, Integer> entry
7049 : mCompatModePackages.getPackages().entrySet()) {
7050 String pkg = entry.getKey();
7051 int mode = entry.getValue();
7052 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7053 continue;
7054 }
7055 if (!printed) {
7056 pw.println(" mScreenCompatPackages:");
7057 printed = true;
7058 }
7059 pw.println(" " + pkg + ": " + mode);
7060 }
7061 }
7062 }
7063
7064 if (dumpPackage == null) {
7065 pw.println(" mWakefulness="
7066 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007067 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007068 if (mRunningVoice != null) {
7069 pw.println(" mRunningVoice=" + mRunningVoice);
7070 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7071 }
7072 pw.println(" mSleeping=" + mSleeping);
7073 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7074 pw.println(" mVrController=" + mVrController);
7075 }
7076 if (mCurAppTimeTracker != null) {
7077 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7078 }
7079 if (mAllowAppSwitchUids.size() > 0) {
7080 boolean printed = false;
7081 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7082 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7083 for (int j = 0; j < types.size(); j++) {
7084 if (dumpPackage == null ||
7085 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7086 if (needSep) {
7087 pw.println();
7088 needSep = false;
7089 }
7090 if (!printed) {
7091 pw.println(" mAllowAppSwitchUids:");
7092 printed = true;
7093 }
7094 pw.print(" User ");
7095 pw.print(mAllowAppSwitchUids.keyAt(i));
7096 pw.print(": Type ");
7097 pw.print(types.keyAt(j));
7098 pw.print(" = ");
7099 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7100 pw.println();
7101 }
7102 }
7103 }
7104 }
7105 if (dumpPackage == null) {
7106 if (mController != null) {
7107 pw.println(" mController=" + mController
7108 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7109 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007110 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7111 pw.println(" mLaunchingActivityWakeLock="
7112 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007113 }
7114
7115 return needSep;
7116 }
7117 }
7118
7119 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007120 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7121 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007122 synchronized (mGlobalLock) {
7123 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007124 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007125 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7126 if (topFocusedStack != null) {
7127 proto.write(CONFIG_WILL_CHANGE, topFocusedStack.mConfigWillChange);
7128 }
sanryhuang498e77e2018-12-06 14:57:01 +08007129 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7130 if (mRunningVoice != null) {
7131 final long vrToken = proto.start(
7132 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7133 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7134 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007135 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007136 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7137 proto.end(vrToken);
7138 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007139 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007140 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007141 if (mController != null) {
7142 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007143 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7144 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007145 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7146 proto.end(token);
7147 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007148 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7149 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007150 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007151 }
7152
7153 if (mHomeProcess != null && (dumpPackage == null
7154 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007155 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007156 }
7157
7158 if (mPreviousProcess != null && (dumpPackage == null
7159 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007160 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007161 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7162 }
7163
7164 if (mHeavyWeightProcess != null && (dumpPackage == null
7165 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007166 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007167 }
7168
7169 for (Map.Entry<String, Integer> entry
7170 : mCompatModePackages.getPackages().entrySet()) {
7171 String pkg = entry.getKey();
7172 int mode = entry.getValue();
7173 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7174 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7175 proto.write(PACKAGE, pkg);
7176 proto.write(MODE, mode);
7177 proto.end(compatToken);
7178 }
7179 }
7180
7181 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007182 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007183 }
7184
7185 }
7186 }
7187
7188 @Override
7189 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7190 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7191 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007192 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7193 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007194 }
7195
7196 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007197 public void dumpForOom(PrintWriter pw) {
7198 synchronized (mGlobalLock) {
7199 pw.println(" mHomeProcess: " + mHomeProcess);
7200 pw.println(" mPreviousProcess: " + mPreviousProcess);
7201 if (mHeavyWeightProcess != null) {
7202 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7203 }
7204 }
7205 }
7206
7207 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007208 public boolean canGcNow() {
7209 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007210 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007211 }
7212 }
7213
Riddle Hsua0536432019-02-16 00:38:59 +08007214 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007215 @Override
7216 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007217 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007218 if (mRootWindowContainer == null) {
7219 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007220 // oomadj after AMS created.
7221 return null;
7222 }
Louis Chang149d5c82019-12-30 09:47:39 +08007223 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007224 return top != null ? top.app : null;
7225 }
7226 }
7227
Riddle Hsua0536432019-02-16 00:38:59 +08007228 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007229 @Override
7230 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007231 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007232 if (mRootWindowContainer != null) {
7233 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007234 }
7235 }
7236 }
7237
7238 @Override
7239 public void scheduleDestroyAllActivities(String reason) {
7240 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007241 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007242 }
7243 }
7244
7245 @Override
7246 public void removeUser(int userId) {
7247 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007248 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007249 }
7250 }
7251
7252 @Override
7253 public boolean switchUser(int userId, UserState userState) {
7254 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007255 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007256 }
7257 }
7258
7259 @Override
7260 public void onHandleAppCrash(WindowProcessController wpc) {
7261 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007262 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007263 }
7264 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007265
7266 @Override
7267 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7268 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007269 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007270 }
7271 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007272
Riddle Hsua0536432019-02-16 00:38:59 +08007273 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007274 @Override
7275 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007276 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007277 }
7278
Riddle Hsua0536432019-02-16 00:38:59 +08007279 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007280 @Override
7281 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007282 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007283 }
7284
Riddle Hsua0536432019-02-16 00:38:59 +08007285 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007286 @Override
7287 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007288 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007289 }
7290
Riddle Hsua0536432019-02-16 00:38:59 +08007291 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007292 @Override
7293 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007294 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007295 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007296
7297 @Override
Louis Changc2236422020-09-14 17:52:02 +08007298 public void onUidAddedToPendingTempAllowlist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007299 synchronized (mGlobalLockWithoutBoost) {
Louis Changc2236422020-09-14 17:52:02 +08007300 mPendingTempAllowlist.put(uid, tag);
Wale Ogunwale9de19442018-10-18 19:05:03 -07007301 }
7302 }
7303
7304 @Override
Louis Changc2236422020-09-14 17:52:02 +08007305 public void onUidRemovedFromPendingTempAllowlist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007306 synchronized (mGlobalLockWithoutBoost) {
Louis Changc2236422020-09-14 17:52:02 +08007307 mPendingTempAllowlist.remove(uid);
Wale Ogunwale9de19442018-10-18 19:05:03 -07007308 }
7309 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007310
7311 @Override
7312 public boolean handleAppCrashInActivityController(String processName, int pid,
7313 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7314 Runnable killCrashingAppCallback) {
7315 synchronized (mGlobalLock) {
7316 if (mController == null) {
7317 return false;
7318 }
7319
7320 try {
7321 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7322 stackTrace)) {
7323 killCrashingAppCallback.run();
7324 return true;
7325 }
7326 } catch (RemoteException e) {
7327 mController = null;
7328 Watchdog.getInstance().setActivityController(null);
7329 }
7330 return false;
7331 }
7332 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007333
7334 @Override
7335 public void removeRecentTasksByPackageName(String packageName, int userId) {
7336 synchronized (mGlobalLock) {
7337 mRecentTasks.removeTasksByPackageName(packageName, userId);
7338 }
7339 }
7340
7341 @Override
7342 public void cleanupRecentTasksForUser(int userId) {
7343 synchronized (mGlobalLock) {
7344 mRecentTasks.cleanupLocked(userId);
7345 }
7346 }
7347
7348 @Override
7349 public void loadRecentTasksForUser(int userId) {
7350 synchronized (mGlobalLock) {
7351 mRecentTasks.loadUserRecentsLocked(userId);
7352 }
7353 }
7354
7355 @Override
7356 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7357 synchronized (mGlobalLock) {
7358 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7359 }
7360 }
7361
7362 @Override
7363 public void flushRecentTasks() {
7364 mRecentTasks.flush();
7365 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007366
7367 @Override
7368 public WindowProcessController getHomeProcess() {
7369 synchronized (mGlobalLock) {
7370 return mHomeProcess;
7371 }
7372 }
7373
7374 @Override
7375 public WindowProcessController getPreviousProcess() {
7376 synchronized (mGlobalLock) {
7377 return mPreviousProcess;
7378 }
7379 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007380
7381 @Override
7382 public void clearLockedTasks(String reason) {
7383 synchronized (mGlobalLock) {
7384 getLockTaskController().clearLockedTasks(reason);
7385 }
7386 }
7387
7388 @Override
7389 public void updateUserConfiguration() {
7390 synchronized (mGlobalLock) {
7391 final Configuration configuration = new Configuration(getGlobalConfiguration());
7392 final int currentUserId = mAmInternal.getCurrentUserId();
7393 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7394 configuration, currentUserId, Settings.System.canWrite(mContext));
7395 updateConfigurationLocked(configuration, null /* starting */,
7396 false /* initLocale */, false /* persistent */, currentUserId,
7397 false /* deferResume */);
7398 }
7399 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007400
7401 @Override
7402 public boolean canShowErrorDialogs() {
7403 synchronized (mGlobalLock) {
7404 return mShowDialogs && !mSleeping && !mShuttingDown
7405 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7406 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7407 mAmInternal.getCurrentUserId())
7408 && !(UserManager.isDeviceInDemoMode(mContext)
7409 && mAmInternal.getCurrentUser().isDemo());
7410 }
7411 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007412
7413 @Override
7414 public void setProfileApp(String profileApp) {
7415 synchronized (mGlobalLock) {
7416 mProfileApp = profileApp;
7417 }
7418 }
7419
7420 @Override
7421 public void setProfileProc(WindowProcessController wpc) {
7422 synchronized (mGlobalLock) {
7423 mProfileProc = wpc;
7424 }
7425 }
7426
7427 @Override
7428 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7429 synchronized (mGlobalLock) {
7430 mProfilerInfo = profilerInfo;
7431 }
7432 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007433
7434 @Override
7435 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7436 synchronized (mGlobalLock) {
7437 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7438 }
7439 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007440
7441 @Override
Zak Cohen84b43182020-03-09 14:36:01 -07007442 public ActivityManager.TaskSnapshot getTaskSnapshotBlocking(
7443 int taskId, boolean isLowResolution) {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08007444 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution,
Zak Cohen84b43182020-03-09 14:36:01 -07007445 true /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007446 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007447
7448 @Override
7449 public boolean isUidForeground(int uid) {
7450 synchronized (mGlobalLock) {
7451 return ActivityTaskManagerService.this.isUidForeground(uid);
7452 }
7453 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007454
7455 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007456 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007457 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007458 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007459 }
7460 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007461
7462 @Override
7463 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007464 // Translate package names into UIDs
7465 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007466 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007467 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7468 if (uid >= 0) {
7469 result.add(uid);
7470 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007471 }
7472 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007473 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007474 }
7475 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007476 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007477}