blob: 2f3e60cc1368a553df636c75941ffb2d6ae11918 [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.metrics.LogMaker;
187import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700188import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700189import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700190import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700191import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700192import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700193import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700194import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700195import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700196import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800197import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700198import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700199import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700201import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100202import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700203import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700204import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700205import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700206import android.os.SystemClock;
207import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700208import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700209import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700210import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700211import android.os.UserManager;
212import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700213import android.os.storage.IStorageManager;
214import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700215import android.provider.Settings;
Galia Peycheva6861e912019-08-21 10:20:23 +0200216import android.service.dreams.DreamActivity;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700217import android.service.voice.IVoiceInteractionSession;
218import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900219import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700220import android.telecom.TelecomManager;
221import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100222import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700223import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700224import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700225import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700226import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700227import android.util.SparseArray;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700228import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700229import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700230import android.view.IRecentsAnimationRunner;
231import android.view.RemoteAnimationAdapter;
232import android.view.RemoteAnimationDefinition;
Louis Changa009c762020-02-26 11:21:31 +0800233import android.view.WindowManager;
Wale Ogunwale568f9f412020-03-21 22:27:35 -0700234import android.window.IWindowOrganizerController;
Wale Ogunwale57946582020-03-21 14:29:07 -0700235import android.window.WindowContainerTransaction;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700236
Evan Rosky4505b352018-09-06 11:20:40 -0700237import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700238import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.app.AssistUtils;
240import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700241import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700243import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700244import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
245import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700246import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700247import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700248import com.android.internal.policy.IKeyguardDismissCallback;
249import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700250import com.android.internal.util.ArrayUtils;
251import com.android.internal.util.FastPrintWriter;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800252import com.android.internal.util.FrameworkStatsLog;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800253import com.android.internal.util.function.pooled.PooledConsumer;
254import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700255import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700256import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700257import com.android.server.LocalServices;
258import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700259import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800260import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700261import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700262import com.android.server.am.ActivityManagerService;
Wale Ogunwale59507092018-10-29 09:00:30 -0700263import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
264import com.android.server.am.AppTimeTracker;
265import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700266import com.android.server.am.PendingIntentController;
267import com.android.server.am.PendingIntentRecord;
268import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700269import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700270import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700271import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800272import com.android.server.policy.PermissionPolicyInternal;
Jeff Sharkey307ea7a2020-04-13 10:24:49 -0600273import com.android.server.uri.NeededUriGrants;
Evan Rosky4505b352018-09-06 11:20:40 -0700274import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700275import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700276
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700278import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700280import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700281import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700282import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700283import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700284import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800285import java.lang.annotation.ElementType;
286import java.lang.annotation.Retention;
287import java.lang.annotation.RetentionPolicy;
288import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700289import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700290import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700291import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700292import java.util.Arrays;
Jeff Sharkey8b0cff72020-03-09 15:49:01 -0600293import java.util.Collection;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700294import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400295import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700296import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700297import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700298import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700299import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000300import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700301import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700302
303/**
304 * System service for managing activities and their containers (task, stacks, displays,... ).
305 *
306 * {@hide}
307 */
308public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700309 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800310 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000311 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700312 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
313 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
314 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
315 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700316 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700317
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700318 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700319 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700320 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700321 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100322 // How long we permit background activity starts after an activity in the process
323 // started or finished.
324 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700325
Wale Ogunwale98875612018-10-12 07:53:02 -0700326 /** Used to indicate that an app transition should be animated. */
327 static final boolean ANIMATE = true;
328
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700329 /** Hardware-reported OpenGLES version. */
330 final int GL_ES_VERSION;
331
Wale Ogunwale31913b52018-10-13 08:29:31 -0700332 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
333 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
334 public static final String DUMP_LASTANR_CMD = "lastanr" ;
335 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
336 public static final String DUMP_STARTER_CMD = "starter" ;
337 public static final String DUMP_CONTAINERS_CMD = "containers" ;
338 public static final String DUMP_RECENTS_CMD = "recents" ;
339 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
340
Wale Ogunwale64258362018-10-16 15:13:37 -0700341 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
342 public static final int RELAUNCH_REASON_NONE = 0;
343 /** This activity is being relaunched due to windowing mode change. */
344 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
345 /** This activity is being relaunched due to a free-resize operation. */
346 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
347
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700348 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700349
Wale Ogunwalef6733932018-06-27 05:14:34 -0700350 /**
351 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
352 * change at runtime. Use mContext for non-UI purposes.
353 */
354 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700355 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700356 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700357 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700358 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700359 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700360 private PackageManagerInternal mPmInternal;
Darryl L Johnsona0982222020-02-18 18:21:51 -0800361 /** The cached sys ui service component name from package manager. */
362 private ComponentName mSysUiServiceComponent;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800363 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800364 @VisibleForTesting
365 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700366 PowerManagerInternal mPowerManagerInternal;
367 private UsageStatsManagerInternal mUsageStatsInternal;
368
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700369 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700370 IntentFirewall mIntentFirewall;
371
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700372 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800373 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800374 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700375 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800376 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
377 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
378 *
379 * @see WindowManagerThreadPriorityBooster
380 */
381 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700382 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800383 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700384 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700385 private UserManagerService mUserManager;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800386 private AppOpsManager mAppOpsManager;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700387 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800388 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700389 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700390 /** All processes currently running that might have a window organized by name. */
391 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100392 /** All processes we currently have running mapped by pid and uid */
393 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700394 /** This is the process holding what we currently consider to be the "home" activity. */
395 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700396 /** The currently running heavy-weight process, if any. */
397 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700398 boolean mHasHeavyWeightFeature;
Sergey Nikolaienkov30c947d2020-04-15 19:55:48 +0200399 boolean mHasLeanbackFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700400 /**
401 * This is the process holding the activity the user last visited that is in a different process
402 * from the one they are currently in.
403 */
404 WindowProcessController mPreviousProcess;
405 /** The time at which the previous process was last visible. */
406 long mPreviousProcessVisibleTime;
407
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700408 /** List of intents that were used to start the most recent tasks. */
409 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700410 /** State of external calls telling us if the device is awake or asleep. */
411 private boolean mKeyguardShown = false;
412
413 // Wrapper around VoiceInteractionServiceManager
414 private AssistUtils mAssistUtils;
415
416 // VoiceInteraction session ID that changes for each new request except when
417 // being called for multi-window assist in a single session.
418 private int mViSessionId = 1000;
419
420 // How long to wait in getAssistContextExtras for the activity and foreground services
421 // to respond with the result.
422 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
423
424 // How long top wait when going through the modern assist (which doesn't need to block
425 // on getting this result before starting to launch its UI).
426 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
427
428 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
429 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
430
Alison Cichowlas3e340502018-08-07 17:15:01 -0400431 // Permission tokens are used to temporarily granted a trusted app the ability to call
432 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
433 // showing any appropriate error messages to the user.
434 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
435 10 * MINUTE_IN_MILLIS;
436
437 // How long before the service actually expires a token. This is slightly longer than
438 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
439 // expiration exception.
440 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
441 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
442
443 // How long the service will remember expired tokens, for the purpose of providing error
444 // messaging when a client uses an expired token.
445 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
446 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
447
448 // Activity tokens of system activities that are delegating their call to
449 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
450 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
451
452 // Permission tokens that have expired, but we remember for error reporting.
453 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
454
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700455 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
456
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700457 // Keeps track of the active voice interaction service component, notified from
458 // VoiceInteractionManagerService
459 ComponentName mActiveVoiceInteractionServiceComponent;
460
Michal Karpinskida34cd42019-04-02 19:46:52 +0100461 // A map userId and all its companion app uids
462 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000463
Wale Ogunwalee2172292018-10-25 10:11:10 -0700464 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700465 KeyguardController mKeyguardController;
466 private final ClientLifecycleManager mLifecycleManager;
467 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700468 /** The controller for all operations related to locktask. */
469 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700470 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700471
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700472 boolean mSuppressResizeConfigChanges;
473
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700474 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700475 new UpdateConfigurationResult();
476
477 static final class UpdateConfigurationResult {
478 // Configuration changes that were updated.
479 int changes;
480 // If the activity was relaunched to match the new configuration.
481 boolean activityRelaunched;
482
483 void reset() {
484 changes = 0;
485 activityRelaunched = false;
486 }
487 }
488
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700489 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700490 private int mConfigurationSeq;
491 // To cache the list of supported system locales
492 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700493
494 /**
495 * Temp object used when global and/or display override configuration is updated. It is also
496 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
497 * anyone...
498 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700499 private Configuration mTempConfig = new Configuration();
500
Wale Ogunwalef6733932018-06-27 05:14:34 -0700501 /** Temporary to avoid allocations. */
502 final StringBuilder mStringBuilder = new StringBuilder(256);
503
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700504 // Amount of time after a call to stopAppSwitches() during which we will
505 // prevent further untrusted switches from happening.
506 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
507
508 /**
509 * The time at which we will allow normal application switches again,
510 * after a call to {@link #stopAppSwitches()}.
511 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700512 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700513 /**
514 * This is set to true after the first switch after mAppSwitchesAllowedTime
515 * is set; any switches after that will clear the time.
516 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700517 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700518
Ricky Wai906af482019-06-03 17:25:28 +0100519 /**
520 * Last stop app switches time, apps finished before this time cannot start background activity
521 * even if they are in grace period.
522 */
523 private long mLastStopAppSwitchesTime;
524
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700525 IActivityController mController = null;
526 boolean mControllerIsAMonkey = false;
527
Wale Ogunwale214f3482018-10-04 11:00:47 -0700528 final int mFactoryTest;
529
530 /** Used to control how we initialize the service. */
531 ComponentName mTopComponent;
532 String mTopAction = Intent.ACTION_MAIN;
533 String mTopData;
534
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800535 /** Profiling app information. */
536 String mProfileApp = null;
537 WindowProcessController mProfileProc = null;
538 ProfilerInfo mProfilerInfo = null;
539
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700540 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700541 * Dump of the activity state at the time of the last ANR. Cleared after
542 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
543 */
544 String mLastANRState;
545
546 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700547 * Used to retain an update lock when the foreground activity is in
548 * immersive mode.
549 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700550 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700551
552 /**
553 * Packages that are being allowed to perform unrestricted app switches. Mapping is
554 * User -> Type -> uid.
555 */
556 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
557
558 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700559 private int mThumbnailWidth;
560 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700561
562 /**
563 * Flag that indicates if multi-window is enabled.
564 *
565 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
566 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
567 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
568 * At least one of the forms of multi-window must be enabled in order for this flag to be
569 * initialized to 'true'.
570 *
571 * @see #mSupportsSplitScreenMultiWindow
572 * @see #mSupportsFreeformWindowManagement
573 * @see #mSupportsPictureInPicture
574 * @see #mSupportsMultiDisplay
575 */
576 boolean mSupportsMultiWindow;
577 boolean mSupportsSplitScreenMultiWindow;
578 boolean mSupportsFreeformWindowManagement;
579 boolean mSupportsPictureInPicture;
580 boolean mSupportsMultiDisplay;
581 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700582 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700583
584 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
585
586 // VR Vr2d Display Id.
587 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700588
Wale Ogunwalef6733932018-06-27 05:14:34 -0700589 /**
590 * Set while we are wanting to sleep, to prevent any
591 * activities from being started/resumed.
592 *
593 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
594 *
595 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
596 * while in the sleep state until there is a pending transition out of sleep, in which case
597 * mSleeping is set to false, and remains false while awake.
598 *
599 * Whether mSleeping can quickly toggled between true/false without the device actually
600 * display changing states is undefined.
601 */
602 private boolean mSleeping = false;
603
604 /**
Galia Peycheva480275a2020-03-18 17:33:42 +0100605 * The mDreaming state is set by the {@link DreamManagerService} when it receives a request to
606 * start/stop the dream. It is set to true shortly before the {@link DreamService} is started.
607 * It is set to false after the {@link DreamService} is stopped.
608 */
609 private boolean mDreaming = false;
610
611 /**
Wale Ogunwalef6733932018-06-27 05:14:34 -0700612 * The process state used for processes that are running the top activities.
613 * This changes between TOP and TOP_SLEEPING to following mSleeping.
614 */
615 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
616
Riddle Hsua0022cd2019-09-09 21:12:41 +0800617 @Retention(RetentionPolicy.SOURCE)
618 @IntDef({
619 LAYOUT_REASON_CONFIG_CHANGED,
620 LAYOUT_REASON_VISIBILITY_CHANGED,
621 })
622 @interface LayoutReason {}
623 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
624 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
625
626 /** The reasons to perform surface placement. */
627 @LayoutReason
628 private int mLayoutReasons;
629
Wale Ogunwalef6733932018-06-27 05:14:34 -0700630 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
631 // automatically. Important for devices without direct input devices.
632 private boolean mShowDialogs = true;
633
634 /** Set if we are shutting down the system, similar to sleeping. */
635 boolean mShuttingDown = false;
636
637 /**
638 * We want to hold a wake lock while running a voice interaction session, since
639 * this may happen with the screen off and we need to keep the CPU running to
640 * be able to continue to interact with the user.
641 */
642 PowerManager.WakeLock mVoiceWakeLock;
643
644 /**
645 * Set while we are running a voice interaction. This overrides sleeping while it is active.
646 */
647 IVoiceInteractionSession mRunningVoice;
648
649 /**
650 * The last resumed activity. This is identical to the current resumed activity most
651 * of the time but could be different when we're pausing one activity before we resume
652 * another activity.
653 */
654 ActivityRecord mLastResumedActivity;
655
656 /**
657 * The activity that is currently being traced as the active resumed activity.
658 *
659 * @see #updateResumedAppTrace
660 */
661 private @Nullable ActivityRecord mTracedResumedActivity;
662
663 /** If non-null, we are tracking the time the user spends in the currently focused app. */
664 AppTimeTracker mCurAppTimeTracker;
665
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700666 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700667
Wale Ogunwale53783742018-09-16 10:21:51 -0700668 /**
669 * Packages that the user has asked to have run in screen size
670 * compatibility mode instead of filling the screen.
671 */
672 CompatModePackages mCompatModePackages;
673
Wale Ogunwalef6733932018-06-27 05:14:34 -0700674 private FontScaleSettingObserver mFontScaleSettingObserver;
675
Wale Ogunwale568f9f412020-03-21 22:27:35 -0700676 WindowOrganizerController mWindowOrganizerController;
677 TaskOrganizerController mTaskOrganizerController;
Robert Carr8a2f9132019-11-11 15:03:15 -0800678
Ricky Wai96f5c352019-04-10 18:40:17 +0100679 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000680
Wale Ogunwalef6733932018-06-27 05:14:34 -0700681 private final class FontScaleSettingObserver extends ContentObserver {
682 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
683 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
684
685 public FontScaleSettingObserver() {
686 super(mH);
687 final ContentResolver resolver = mContext.getContentResolver();
688 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
689 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
690 UserHandle.USER_ALL);
691 }
692
693 @Override
Jeff Sharkey8b0cff72020-03-09 15:49:01 -0600694 public void onChange(boolean selfChange, Collection<Uri> uris, int flags,
Riddle Hsu9c024d12020-03-09 16:10:07 +0800695 @UserIdInt int userId) {
696 for (Uri uri : uris) {
697 if (mFontScaleUri.equals(uri)) {
698 updateFontScaleIfNeeded(userId);
699 } else if (mHideErrorDialogsUri.equals(uri)) {
700 synchronized (mGlobalLock) {
701 updateShouldShowDialogsLocked(getGlobalConfiguration());
702 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700703 }
704 }
705 }
706 }
707
Riddle Hsua0536432019-02-16 00:38:59 +0800708 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
709 @Target(ElementType.METHOD)
710 @Retention(RetentionPolicy.SOURCE)
711 @interface HotPath {
712 int NONE = 0;
713 int OOM_ADJUSTMENT = 1;
714 int LRU_UPDATE = 2;
715 int PROCESS_CHANGE = 3;
716 int caller() default NONE;
717 }
718
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800719 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
720 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900721 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800722 mAmInternal.updateOomAdj();
723 }
724 };
725
Charles Chen8d98dd22018-12-26 17:36:54 +0800726 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
727 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700728 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700729 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700730 mSystemThread = ActivityThread.currentActivityThread();
731 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700732 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800733 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700734 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale568f9f412020-03-21 22:27:35 -0700735 mWindowOrganizerController = new WindowOrganizerController(this);
736 mTaskOrganizerController = mWindowOrganizerController.mTaskOrganizerController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700737 }
738
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700739 public void onSystemReady() {
740 synchronized (mGlobalLock) {
Sergey Nikolaienkov30c947d2020-04-15 19:55:48 +0200741 final PackageManager pm = mContext.getPackageManager();
742 mHasHeavyWeightFeature = pm.hasSystemFeature(FEATURE_CANT_SAVE_STATE);
743 mHasLeanbackFeature = pm.hasSystemFeature(FEATURE_LEANBACK);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700744 mAssistUtils = new AssistUtils(mContext);
745 mVrController.onSystemReady();
746 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700747 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700748 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700749 }
750
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700751 public void onInitPowerManagement() {
752 synchronized (mGlobalLock) {
753 mStackSupervisor.initPowerManagement();
754 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
755 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
756 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
757 mVoiceWakeLock.setReferenceCounted(false);
758 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700759 }
760
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700761 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700762 mFontScaleSettingObserver = new FontScaleSettingObserver();
763 }
764
Wale Ogunwale59507092018-10-29 09:00:30 -0700765 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700766 final boolean freeformWindowManagement =
767 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
768 || Settings.Global.getInt(
769 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
770
771 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
772 final boolean supportsPictureInPicture = supportsMultiWindow &&
773 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
774 final boolean supportsSplitScreenMultiWindow =
775 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
776 final boolean supportsMultiDisplay = mContext.getPackageManager()
777 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700778 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
779 final boolean forceResizable = Settings.Global.getInt(
780 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700781 final boolean sizeCompatFreeform = Settings.Global.getInt(
782 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700783
784 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900785 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700786
787 final Configuration configuration = new Configuration();
788 Settings.System.getConfiguration(resolver, configuration);
789 if (forceRtl) {
790 // This will take care of setting the correct layout direction flags
791 configuration.setLayoutDirection(configuration.locale);
792 }
793
794 synchronized (mGlobalLock) {
795 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700796 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700797 final boolean multiWindowFormEnabled = freeformWindowManagement
798 || supportsSplitScreenMultiWindow
799 || supportsPictureInPicture
800 || supportsMultiDisplay;
801 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
802 mSupportsMultiWindow = true;
803 mSupportsFreeformWindowManagement = freeformWindowManagement;
804 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
805 mSupportsPictureInPicture = supportsPictureInPicture;
806 mSupportsMultiDisplay = supportsMultiDisplay;
807 } else {
808 mSupportsMultiWindow = false;
809 mSupportsFreeformWindowManagement = false;
810 mSupportsSplitScreenMultiWindow = false;
811 mSupportsPictureInPicture = false;
812 mSupportsMultiDisplay = false;
813 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700814 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700815 // This happens before any activities are started, so we can change global configuration
816 // in-place.
817 updateConfigurationLocked(configuration, null, true);
818 final Configuration globalConfig = getGlobalConfiguration();
819 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
820
821 // Load resources only after the current configuration has been set.
822 final Resources res = mContext.getResources();
823 mThumbnailWidth = res.getDimensionPixelSize(
824 com.android.internal.R.dimen.thumbnail_width);
825 mThumbnailHeight = res.getDimensionPixelSize(
826 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700827 }
828 }
829
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800830 public WindowManagerGlobalLock getGlobalLock() {
831 return mGlobalLock;
832 }
833
Yunfan Chen585f2932019-01-29 16:04:45 +0900834 /** For test purpose only. */
835 @VisibleForTesting
836 public ActivityTaskManagerInternal getAtmInternal() {
837 return mInternal;
838 }
839
Riddle Hsud93a6c42018-11-29 21:50:06 +0800840 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
841 Looper looper) {
842 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700843 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700844 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700845 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800846 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700847 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700848 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700849 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700850
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700851 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700852 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700853 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700854 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700855 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700856 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700857 mKeyguardController = mStackSupervisor.getKeyguardController();
858 }
859
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700860 public void onActivityManagerInternalAdded() {
861 synchronized (mGlobalLock) {
862 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
863 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
864 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700865 }
866
Yunfan Chen75157d72018-07-27 14:47:21 +0900867 int increaseConfigurationSeqLocked() {
868 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
869 return mConfigurationSeq;
870 }
871
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700872 protected ActivityStackSupervisor createStackSupervisor() {
873 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
874 supervisor.initialize();
875 return supervisor;
876 }
877
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800878 protected AppWarnings createAppWarnings(
879 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
880 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
881 }
882
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700883 public void setWindowManager(WindowManagerService wm) {
884 synchronized (mGlobalLock) {
885 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800886 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800887 mTempConfig.setToDefaults();
888 mTempConfig.setLocales(LocaleList.getDefault());
889 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800890 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700891 mLockTaskController.setWindowManager(wm);
892 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800893 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700894 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700895 }
896
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700897 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
898 synchronized (mGlobalLock) {
899 mUsageStatsInternal = usageStatsManager;
900 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700901 }
902
Wale Ogunwalef6733932018-06-27 05:14:34 -0700903 UserManagerService getUserManager() {
904 if (mUserManager == null) {
905 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
906 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
907 }
908 return mUserManager;
909 }
910
Philip P. Moltmannee295092020-02-10 08:46:26 -0800911 AppOpsManager getAppOpsManager() {
912 if (mAppOpsManager == null) {
913 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Wale Ogunwalef6733932018-06-27 05:14:34 -0700914 }
Philip P. Moltmannee295092020-02-10 08:46:26 -0800915 return mAppOpsManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700916 }
917
918 boolean hasUserRestriction(String restriction, int userId) {
919 return getUserManager().hasUserRestriction(restriction, userId);
920 }
921
Michal Karpinski15486842019-04-25 17:33:42 +0100922 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
Philip P. Moltmannee295092020-02-10 08:46:26 -0800923 final int mode = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
924 callingUid, callingPackage, /* featureId */ null, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100925 if (mode == AppOpsManager.MODE_DEFAULT) {
926 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
927 == PERMISSION_GRANTED;
928 }
929 return mode == AppOpsManager.MODE_ALLOWED;
930 }
931
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700932 @VisibleForTesting
933 protected void setRecentTasks(RecentTasks recentTasks) {
934 mRecentTasks = recentTasks;
935 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700936 }
937
938 RecentTasks getRecentTasks() {
939 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700940 }
941
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700942 ClientLifecycleManager getLifecycleManager() {
943 return mLifecycleManager;
944 }
945
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700946 ActivityStartController getActivityStartController() {
947 return mActivityStartController;
948 }
949
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700950 TaskChangeNotificationController getTaskChangeNotificationController() {
951 return mTaskChangeNotificationController;
952 }
953
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700954 LockTaskController getLockTaskController() {
955 return mLockTaskController;
956 }
957
Yunfan Chen75157d72018-07-27 14:47:21 +0900958 /**
959 * Return the global configuration used by the process corresponding to the input pid. This is
960 * usually the global configuration with some overrides specific to that process.
961 */
962 Configuration getGlobalConfigurationForCallingPid() {
963 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800964 return getGlobalConfigurationForPid(pid);
965 }
966
967 /**
968 * Return the global configuration used by the process corresponding to the given pid.
969 */
970 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900971 if (pid == MY_PID || pid < 0) {
972 return getGlobalConfiguration();
973 }
974 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100975 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900976 return app != null ? app.getConfiguration() : getGlobalConfiguration();
977 }
978 }
979
980 /**
981 * Return the device configuration info used by the process corresponding to the input pid.
982 * The value is consistent with the global configuration for the process.
983 */
984 @Override
985 public ConfigurationInfo getDeviceConfigurationInfo() {
986 ConfigurationInfo config = new ConfigurationInfo();
987 synchronized (mGlobalLock) {
988 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
989 config.reqTouchScreen = globalConfig.touchscreen;
990 config.reqKeyboardType = globalConfig.keyboard;
991 config.reqNavigation = globalConfig.navigation;
992 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
993 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
994 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
995 }
996 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
997 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
998 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
999 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001000 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +09001001 }
1002 return config;
1003 }
1004
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001005 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -07001006 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001007 }
1008
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001009 public static final class Lifecycle extends SystemService {
1010 private final ActivityTaskManagerService mService;
1011
1012 public Lifecycle(Context context) {
1013 super(context);
1014 mService = new ActivityTaskManagerService(context);
1015 }
1016
1017 @Override
1018 public void onStart() {
1019 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001020 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001021 }
1022
Garfield Tan891146c2018-10-09 12:14:00 -07001023 @Override
1024 public void onUnlockUser(int userId) {
1025 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001026 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001027 }
1028 }
1029
1030 @Override
1031 public void onCleanupUser(int userId) {
1032 synchronized (mService.getGlobalLock()) {
1033 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1034 }
1035 }
1036
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001037 public ActivityTaskManagerService getService() {
1038 return mService;
1039 }
1040 }
1041
1042 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 public final int startActivity(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001044 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1045 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1046 Bundle bOptions) {
1047 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1048 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001049 UserHandle.getCallingUserId());
1050 }
1051
1052 @Override
1053 public final int startActivities(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001054 String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
1055 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001056 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001057 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001058 enforceNotIsolatedCaller(reason);
1059 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001061 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001062 callingFeatureId, intents, resolvedTypes, resultTo,
1063 SafeActivityOptions.fromBundle(bOptions), userId, reason,
1064 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001065 }
1066
1067 @Override
1068 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001069 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1070 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1071 Bundle bOptions, int userId) {
1072 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1073 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001074 true /*validateIncomingUser*/);
1075 }
1076
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001077 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001078 @Nullable String callingFeatureId, Intent intent, String resolvedType,
1079 IBinder resultTo, String resultWho, int requestCode, int startFlags,
1080 ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001081 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001082 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001083
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001084 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001085 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1086
1087 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001088 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001089 .setCaller(caller)
1090 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001091 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001092 .setResolvedType(resolvedType)
1093 .setResultTo(resultTo)
1094 .setResultWho(resultWho)
1095 .setRequestCode(requestCode)
1096 .setStartFlags(startFlags)
1097 .setProfilerInfo(profilerInfo)
1098 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001099 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001100 .execute();
1101
1102 }
1103
1104 @Override
1105 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1106 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001107 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1108 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001109 // Refuse possible leaked file descriptors
1110 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1111 throw new IllegalArgumentException("File descriptors passed in Intent");
1112 }
1113
1114 if (!(target instanceof PendingIntentRecord)) {
1115 throw new IllegalArgumentException("Bad PendingIntent object");
1116 }
1117
1118 PendingIntentRecord pir = (PendingIntentRecord)target;
1119
1120 synchronized (mGlobalLock) {
1121 // If this is coming from the currently resumed activity, it is
1122 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001123 final ActivityStack stack = getTopDisplayFocusedStack();
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001124 if (stack != null && stack.mResumedActivity != null
1125 && stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001126 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001127 }
1128 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001129 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001130 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001131 }
1132
1133 @Override
1134 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1135 Bundle bOptions) {
1136 // Refuse possible leaked file descriptors
1137 if (intent != null && intent.hasFileDescriptors()) {
1138 throw new IllegalArgumentException("File descriptors passed in Intent");
1139 }
1140 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1141
1142 synchronized (mGlobalLock) {
1143 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1144 if (r == null) {
1145 SafeActivityOptions.abort(options);
1146 return false;
1147 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001148 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001149 // The caller is not running... d'oh!
1150 SafeActivityOptions.abort(options);
1151 return false;
1152 }
1153 intent = new Intent(intent);
1154 // The caller is not allowed to change the data.
1155 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1156 // And we are resetting to find the next component...
1157 intent.setComponent(null);
1158
1159 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1160
1161 ActivityInfo aInfo = null;
1162 try {
1163 List<ResolveInfo> resolves =
1164 AppGlobals.getPackageManager().queryIntentActivities(
1165 intent, r.resolvedType,
1166 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1167 UserHandle.getCallingUserId()).getList();
1168
1169 // Look for the original activity in the list...
1170 final int N = resolves != null ? resolves.size() : 0;
1171 for (int i=0; i<N; i++) {
1172 ResolveInfo rInfo = resolves.get(i);
1173 if (rInfo.activityInfo.packageName.equals(r.packageName)
1174 && rInfo.activityInfo.name.equals(r.info.name)) {
1175 // We found the current one... the next matching is
1176 // after it.
1177 i++;
1178 if (i<N) {
1179 aInfo = resolves.get(i).activityInfo;
1180 }
1181 if (debug) {
1182 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1183 + "/" + r.info.name);
1184 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1185 ? "null" : aInfo.packageName + "/" + aInfo.name));
1186 }
1187 break;
1188 }
1189 }
1190 } catch (RemoteException e) {
1191 }
1192
1193 if (aInfo == null) {
1194 // Nobody who is next!
1195 SafeActivityOptions.abort(options);
1196 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1197 return false;
1198 }
1199
1200 intent.setComponent(new ComponentName(
1201 aInfo.applicationInfo.packageName, aInfo.name));
1202 intent.setFlags(intent.getFlags()&~(
1203 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1204 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1205 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1206 FLAG_ACTIVITY_NEW_TASK));
1207
1208 // Okay now we need to start the new activity, replacing the currently running activity.
1209 // This is a little tricky because we want to start the new one as if the current one is
1210 // finished, but not finish the current one first so that there is no flicker.
1211 // And thus...
1212 final boolean wasFinishing = r.finishing;
1213 r.finishing = true;
1214
1215 // Propagate reply information over to the new activity.
1216 final ActivityRecord resultTo = r.resultTo;
1217 final String resultWho = r.resultWho;
1218 final int requestCode = r.requestCode;
1219 r.resultTo = null;
1220 if (resultTo != null) {
1221 resultTo.removeResultsLocked(r, resultWho, requestCode);
1222 }
1223
1224 final long origId = Binder.clearCallingIdentity();
1225 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001226 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001227 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001228 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001229 .setResolvedType(r.resolvedType)
1230 .setActivityInfo(aInfo)
1231 .setResultTo(resultTo != null ? resultTo.appToken : null)
1232 .setResultWho(resultWho)
1233 .setRequestCode(requestCode)
1234 .setCallingPid(-1)
1235 .setCallingUid(r.launchedFromUid)
1236 .setCallingPackage(r.launchedFromPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001237 .setCallingFeatureId(r.launchedFromFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001238 .setRealCallingPid(-1)
1239 .setRealCallingUid(r.launchedFromUid)
1240 .setActivityOptions(options)
1241 .execute();
1242 Binder.restoreCallingIdentity(origId);
1243
1244 r.finishing = wasFinishing;
1245 if (res != ActivityManager.START_SUCCESS) {
1246 return false;
1247 }
1248 return true;
1249 }
1250 }
1251
Galia Peychevaed401cc2020-03-19 20:28:09 +01001252 private void enforceCallerIsDream(String callerPackageName) {
Galia Peycheva52e89222020-02-18 23:41:43 +01001253 final long origId = Binder.clearCallingIdentity();
Galia Peychevaed401cc2020-03-19 20:28:09 +01001254 try {
1255 if (!ActivityRecord.canLaunchDreamActivity(callerPackageName)) {
1256 throw new SecurityException("The dream activity can be started only when the device"
1257 + " is dreaming and only by the active dream package.");
1258 }
1259 } finally {
1260 Binder.restoreCallingIdentity(origId);
Galia Peycheva52e89222020-02-18 23:41:43 +01001261 }
Galia Peychevaed401cc2020-03-19 20:28:09 +01001262 }
1263
1264 @Override
1265 public boolean startDreamActivity(@NonNull Intent intent) {
1266 assertPackageMatchesCallingUid(intent.getPackage());
1267 enforceCallerIsDream(intent.getPackage());
Galia Peycheva52e89222020-02-18 23:41:43 +01001268
Galia Peycheva6861e912019-08-21 10:20:23 +02001269 final ActivityInfo a = new ActivityInfo();
1270 a.theme = com.android.internal.R.style.Theme_Dream;
1271 a.exported = true;
1272 a.name = DreamActivity.class.getName();
Galia Peycheva6861e912019-08-21 10:20:23 +02001273 a.enabled = true;
1274 a.launchMode = ActivityInfo.LAUNCH_SINGLE_INSTANCE;
Galia Peycheva6861e912019-08-21 10:20:23 +02001275 a.persistableMode = ActivityInfo.PERSIST_NEVER;
1276 a.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1277 a.colorMode = ActivityInfo.COLOR_MODE_DEFAULT;
1278 a.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1279
Galia Peycheva45f48d32020-02-20 15:39:10 +01001280 final ActivityOptions options = ActivityOptions.makeBasic();
1281 options.setLaunchActivityType(ACTIVITY_TYPE_DREAM);
1282
Galia Peychevaed401cc2020-03-19 20:28:09 +01001283 synchronized (mGlobalLock) {
1284 final WindowProcessController process = mProcessMap.getProcess(Binder.getCallingPid());
1285
1286 a.packageName = process.mInfo.packageName;
1287 a.applicationInfo = process.mInfo;
1288 a.processName = process.mInfo.processName;
1289 a.uiOptions = process.mInfo.uiOptions;
1290 a.taskAffinity = "android:" + a.packageName + "/dream";
1291
1292 final int callingUid = Binder.getCallingUid();
1293 final int callingPid = Binder.getCallingPid();
1294
1295 final long origId = Binder.clearCallingIdentity();
1296 try {
1297 getActivityStartController().obtainStarter(intent, "dream")
1298 .setCallingUid(callingUid)
1299 .setCallingPid(callingPid)
1300 .setActivityInfo(a)
1301 .setActivityOptions(options.toBundle())
1302 // To start the dream from background, we need to start it from a persistent
1303 // system process. Here we set the real calling uid to the system server uid
1304 .setRealCallingUid(Binder.getCallingUid())
1305 .setAllowBackgroundActivityStart(true)
1306 .execute();
1307 return true;
1308 } finally {
1309 Binder.restoreCallingIdentity(origId);
1310 }
Galia Peycheva6861e912019-08-21 10:20:23 +02001311 }
1312 }
1313
1314 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001315 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001316 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1317 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1318 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001319 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001320 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001321 enforceNotIsolatedCaller("startActivityAndWait");
1322 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1323 userId, "startActivityAndWait");
1324 // TODO: Switch to user app stacks here.
1325 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1326 .setCaller(caller)
1327 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001328 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001329 .setResolvedType(resolvedType)
1330 .setResultTo(resultTo)
1331 .setResultWho(resultWho)
1332 .setRequestCode(requestCode)
1333 .setStartFlags(startFlags)
1334 .setActivityOptions(bOptions)
1335 .setUserId(userId)
1336 .setProfilerInfo(profilerInfo)
1337 .setWaitResult(res)
1338 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001339 return res;
1340 }
1341
1342 @Override
1343 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001344 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1345 String resultWho, int requestCode, int startFlags, Configuration config,
1346 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001347 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001348 enforceNotIsolatedCaller("startActivityWithConfig");
1349 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1350 "startActivityWithConfig");
1351 // TODO: Switch to user app stacks here.
1352 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1353 .setCaller(caller)
1354 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001355 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001356 .setResolvedType(resolvedType)
1357 .setResultTo(resultTo)
1358 .setResultWho(resultWho)
1359 .setRequestCode(requestCode)
1360 .setStartFlags(startFlags)
1361 .setGlobalConfiguration(config)
1362 .setActivityOptions(bOptions)
1363 .setUserId(userId)
1364 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001365 }
1366
Robert Carr8a2f9132019-11-11 15:03:15 -08001367 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001368 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1369 int callingUid = Binder.getCallingUid();
1370 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1371 throw new SecurityException("Only the system process can request a permission token, "
1372 + "received request from uid: " + callingUid);
1373 }
1374 IBinder permissionToken = new Binder();
1375 synchronized (mGlobalLock) {
1376 mStartActivitySources.put(permissionToken, delegatorToken);
1377 }
1378
1379 Message expireMsg = PooledLambda.obtainMessage(
1380 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1381 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1382
1383 Message forgetMsg = PooledLambda.obtainMessage(
1384 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1385 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1386
1387 return permissionToken;
1388 }
1389
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001390 @Override
1391 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1392 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001393 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1394 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001395 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001396 // permission grants) as any app that may launch one of your own activities. So we only
1397 // allow this in two cases:
1398 // 1) The caller is an activity that is part of the core framework, and then only when it
1399 // is running as the system.
1400 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1401 // can only be requested by a system activity, which may then delegate this call to
1402 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001403 final ActivityRecord sourceRecord;
1404 final int targetUid;
1405 final String targetPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001406 final String targetFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001407 final boolean isResolver;
1408 synchronized (mGlobalLock) {
1409 if (resultTo == null) {
1410 throw new SecurityException("Must be called from an activity");
1411 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001412 final IBinder sourceToken;
1413 if (permissionToken != null) {
1414 // To even attempt to use a permissionToken, an app must also have this signature
1415 // permission.
1416 mAmInternal.enforceCallingPermission(
1417 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1418 "startActivityAsCaller");
1419 // If called with a permissionToken, we want the sourceRecord from the delegator
1420 // activity that requested this token.
1421 sourceToken = mStartActivitySources.remove(permissionToken);
1422 if (sourceToken == null) {
1423 // Invalid permissionToken, check if it recently expired.
1424 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1425 throw new SecurityException("Called with expired permission token: "
1426 + permissionToken);
1427 } else {
1428 throw new SecurityException("Called with invalid permission token: "
1429 + permissionToken);
1430 }
1431 }
1432 } else {
1433 // This method was called directly by the source.
1434 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001435 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001436
Louis Chang149d5c82019-12-30 09:47:39 +08001437 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001438 if (sourceRecord == null) {
1439 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001440 }
1441 if (sourceRecord.app == null) {
1442 throw new SecurityException("Called without a process attached to activity");
1443 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001444
1445 // Whether called directly or from a delegate, the source activity must be from the
1446 // android package.
1447 if (!sourceRecord.info.packageName.equals("android")) {
1448 throw new SecurityException("Must be called from an activity that is "
1449 + "declared in the android package");
1450 }
1451
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001452 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 // This is still okay, as long as this activity is running under the
1454 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001455 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001457 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458 + " must be system uid or original calling uid "
1459 + sourceRecord.launchedFromUid);
1460 }
1461 }
1462 if (ignoreTargetSecurity) {
1463 if (intent.getComponent() == null) {
1464 throw new SecurityException(
1465 "Component must be specified with ignoreTargetSecurity");
1466 }
1467 if (intent.getSelector() != null) {
1468 throw new SecurityException(
1469 "Selector not allowed with ignoreTargetSecurity");
1470 }
1471 }
1472 targetUid = sourceRecord.launchedFromUid;
1473 targetPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001474 targetFeatureId = sourceRecord.launchedFromFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001475 isResolver = sourceRecord.isResolverOrChildActivity();
1476 }
1477
1478 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001479 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001480 }
1481
1482 // TODO: Switch to user app stacks here.
1483 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001484 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001485 .setCallingUid(targetUid)
1486 .setCallingPackage(targetPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001487 .setCallingFeatureId(targetFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001488 .setResolvedType(resolvedType)
1489 .setResultTo(resultTo)
1490 .setResultWho(resultWho)
1491 .setRequestCode(requestCode)
1492 .setStartFlags(startFlags)
1493 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001494 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001495 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1496 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001497 // The target may well be in the background, which would normally prevent it
1498 // from starting an activity. Here we definitely want the start to succeed.
1499 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001500 .execute();
1501 } catch (SecurityException e) {
1502 // XXX need to figure out how to propagate to original app.
1503 // A SecurityException here is generally actually a fault of the original
1504 // calling activity (such as a fairly granting permissions), so propagate it
1505 // back to them.
1506 /*
1507 StringBuilder msg = new StringBuilder();
1508 msg.append("While launching");
1509 msg.append(intent.toString());
1510 msg.append(": ");
1511 msg.append(e.getMessage());
1512 */
1513 throw e;
1514 }
1515 }
1516
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001517 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1518 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001519 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001520 }
1521
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001522 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001523 public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1524 int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001525 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1526 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001527 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001528 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001529 if (session == null || interactor == null) {
1530 throw new NullPointerException("null session or interactor");
1531 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001532 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001533 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001534 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001535 .setCallingUid(callingUid)
1536 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001537 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001538 .setResolvedType(resolvedType)
1539 .setVoiceSession(session)
1540 .setVoiceInteractor(interactor)
1541 .setStartFlags(startFlags)
1542 .setProfilerInfo(profilerInfo)
1543 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001544 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001545 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001546 .execute();
1547 }
1548
1549 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001550 public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1551 int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1552 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001553 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001554 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1555 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001556
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001557 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001558 .setCallingUid(callingUid)
1559 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001560 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001561 .setResolvedType(resolvedType)
1562 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001563 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001564 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001565 .execute();
1566 }
1567
Riddle Hsu609a8e22019-06-27 16:46:29 -06001568 /**
1569 * Start the recents activity to perform the recents animation.
1570 *
1571 * @param intent The intent to start the recents activity.
1572 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1573 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001574 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001575 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1576 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001577 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001578 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001579 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001580 final long origId = Binder.clearCallingIdentity();
1581 try {
1582 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001583 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
Philip P. Moltmannee295092020-02-10 08:46:26 -08001584 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001585 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001586 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001587
1588 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001589 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001590 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001591 recentsFeatureId, recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001592 if (recentsAnimationRunner == null) {
1593 anim.preloadRecentsActivity();
1594 } else {
1595 anim.startRecentsActivity(recentsAnimationRunner);
1596 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 }
1598 } finally {
1599 Binder.restoreCallingIdentity(origId);
1600 }
1601 }
1602
1603 @Override
1604 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001605 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001606 "startActivityFromRecents()");
1607
1608 final int callingPid = Binder.getCallingPid();
1609 final int callingUid = Binder.getCallingUid();
1610 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1611 final long origId = Binder.clearCallingIdentity();
1612 try {
1613 synchronized (mGlobalLock) {
1614 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1615 safeOptions);
1616 }
1617 } finally {
1618 Binder.restoreCallingIdentity(origId);
1619 }
1620 }
1621
1622 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001623 * Public API to check if the client is allowed to start an activity on specified display.
1624 *
1625 * If the target display is private or virtual, some restrictions will apply.
1626 *
1627 * @param displayId Target display id.
1628 * @param intent Intent used to launch the activity.
1629 * @param resolvedType The MIME type of the intent.
1630 * @param userId The id of the user for whom the call is made.
1631 * @return {@code true} if a call to start an activity on the target display should succeed and
1632 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1633 */
1634 @Override
1635 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1636 String resolvedType, int userId) {
1637 final int callingUid = Binder.getCallingUid();
1638 final int callingPid = Binder.getCallingPid();
1639 final long origId = Binder.clearCallingIdentity();
1640
1641 try {
1642 // Collect information about the target of the Intent.
1643 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1644 0 /* startFlags */, null /* profilerInfo */, userId,
1645 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1646 UserHandle.USER_NULL));
1647 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1648
1649 synchronized (mGlobalLock) {
1650 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1651 aInfo);
1652 }
1653 } finally {
1654 Binder.restoreCallingIdentity(origId);
1655 }
1656 }
1657
1658 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001659 * This is the internal entry point for handling Activity.finish().
1660 *
1661 * @param token The Binder token referencing the Activity we want to finish.
1662 * @param resultCode Result code, if any, from this Activity.
1663 * @param resultData Result data (Intent), if any, from this Activity.
1664 * @param finishTask Whether to finish the task associated with this Activity.
1665 *
1666 * @return Returns true if the activity successfully finished, or false if it is still running.
1667 */
1668 @Override
1669 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1670 int finishTask) {
1671 // Refuse possible leaked file descriptors
1672 if (resultData != null && resultData.hasFileDescriptors()) {
1673 throw new IllegalArgumentException("File descriptors passed in Intent");
1674 }
1675
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06001676 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001677 synchronized (mGlobalLock) {
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06001678 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001679 if (r == null) {
1680 return true;
1681 }
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06001682 }
1683
1684 // Carefully collect grants without holding lock
1685 final NeededUriGrants resultGrants = collectGrants(resultData, r.resultTo);
1686
1687 synchronized (mGlobalLock) {
Louis Chang73269792020-06-09 16:02:42 +08001688 // Sanity check in case activity was removed before entering global lock.
1689 if (!r.isInHistory()) {
1690 return true;
1691 }
1692
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001693 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001694 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001695 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001696 if (rootR == null) {
1697 Slog.w(TAG, "Finishing task with all activities already finished");
1698 }
1699 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1700 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001701 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001702 return false;
1703 }
1704
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001705 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1706 // We should consolidate.
1707 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001708 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001709 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001710 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001711 if (next != null) {
1712 // ask watcher if this is allowed
1713 boolean resumeOK = true;
1714 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001715 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001716 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001717 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001718 Watchdog.getInstance().setActivityController(null);
1719 }
1720
1721 if (!resumeOK) {
1722 Slog.i(TAG, "Not finishing activity because controller resumed");
1723 return false;
1724 }
1725 }
1726 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001727
1728 // note down that the process has finished an activity and is in background activity
1729 // starts grace period
1730 if (r.app != null) {
1731 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1732 }
1733
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001734 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001735 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001736 try {
1737 boolean res;
1738 final boolean finishWithRootActivity =
1739 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1740 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1741 || (finishWithRootActivity && r == rootR)) {
1742 // If requested, remove the task that is associated to this activity only if it
1743 // was the root activity in the task. The result code and data is ignored
1744 // because we don't support returning them across task boundaries. Also, to
1745 // keep backwards compatibility we remove the task from recents when finishing
1746 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001747 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001748 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001749 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001750 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001751 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001752 } else {
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06001753 r.finishIfPossible(resultCode, resultData, resultGrants,
1754 "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001755 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 if (!res) {
1757 Slog.i(TAG, "Failed to finish by app-request");
1758 }
1759 }
1760 return res;
1761 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001762 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001763 Binder.restoreCallingIdentity(origId);
1764 }
1765 }
1766 }
1767
1768 @Override
1769 public boolean finishActivityAffinity(IBinder token) {
1770 synchronized (mGlobalLock) {
1771 final long origId = Binder.clearCallingIdentity();
1772 try {
1773 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1774 if (r == null) {
1775 return false;
1776 }
1777
1778 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1779 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001780 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001781 return false;
1782 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001783
1784 final PooledFunction p = PooledLambda.obtainFunction(
1785 ActivityRecord::finishIfSameAffinity, r,
1786 PooledLambda.__(ActivityRecord.class));
1787 r.getTask().forAllActivities(
1788 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1789 p.recycle();
1790
Andrii Kuliande93eff2019-07-12 12:21:27 -07001791 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001792 } finally {
1793 Binder.restoreCallingIdentity(origId);
1794 }
1795 }
1796 }
1797
1798 @Override
1799 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1800 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001801 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001802 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001803 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001804 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1805 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001806 return;
1807 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001808 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1809 false /* processPausingActivities */, config);
1810 if (stopProfiling && r.hasProcess()) {
1811 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001812 }
1813 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001814 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001815 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001816 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001817 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001818 }
1819
1820 @Override
1821 public final void activityResumed(IBinder token) {
1822 final long origId = Binder.clearCallingIdentity();
1823 synchronized (mGlobalLock) {
1824 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001825 }
1826 Binder.restoreCallingIdentity(origId);
1827 }
1828
1829 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001830 public final void activityTopResumedStateLost() {
1831 final long origId = Binder.clearCallingIdentity();
1832 synchronized (mGlobalLock) {
1833 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1834 }
1835 Binder.restoreCallingIdentity(origId);
1836 }
1837
1838 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001839 public final void activityPaused(IBinder token) {
1840 final long origId = Binder.clearCallingIdentity();
1841 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001842 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001843 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1844 if (r != null) {
1845 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001846 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001847 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001848 }
1849 Binder.restoreCallingIdentity(origId);
1850 }
1851
1852 @Override
1853 public final void activityStopped(IBinder token, Bundle icicle,
1854 PersistableBundle persistentState, CharSequence description) {
1855 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1856
1857 // Refuse possible leaked file descriptors
1858 if (icicle != null && icicle.hasFileDescriptors()) {
1859 throw new IllegalArgumentException("File descriptors passed in Bundle");
1860 }
1861
1862 final long origId = Binder.clearCallingIdentity();
1863
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001864 String restartingName = null;
1865 int restartingUid = 0;
1866 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001867 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001868 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001869 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001870 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001871 if (r.attachedToProcess()
1872 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1873 // The activity was requested to restart from
1874 // {@link #restartActivityProcessIfVisible}.
1875 restartingName = r.app.mName;
1876 restartingUid = r.app.mUid;
1877 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001878 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001879 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001880 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001881 }
1882
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001883 if (restartingName != null) {
1884 // In order to let the foreground activity can be restarted with its saved state from
1885 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1886 // until the activity reports stopped with the state. And the activity record will be
1887 // kept because the record state is restarting, then the activity will be restarted
1888 // immediately if it is still the top one.
1889 mStackSupervisor.removeRestartTimeouts(r);
1890 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1891 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001892 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893
1894 Binder.restoreCallingIdentity(origId);
1895 }
1896
1897 @Override
1898 public final void activityDestroyed(IBinder token) {
1899 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1900 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001901 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001902 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001903 try {
1904 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1905 if (activity != null) {
1906 activity.destroyed("activityDestroyed");
1907 }
1908 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001909 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001910 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001911 }
1912 }
1913 }
1914
1915 @Override
1916 public final void activityRelaunched(IBinder token) {
1917 final long origId = Binder.clearCallingIdentity();
1918 synchronized (mGlobalLock) {
1919 mStackSupervisor.activityRelaunchedLocked(token);
1920 }
1921 Binder.restoreCallingIdentity(origId);
1922 }
1923
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001924 @Override
1925 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1926 synchronized (mGlobalLock) {
1927 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1928 if (r == null) {
1929 return;
1930 }
1931 final long origId = Binder.clearCallingIdentity();
1932 try {
1933 r.setRequestedOrientation(requestedOrientation);
1934 } finally {
1935 Binder.restoreCallingIdentity(origId);
1936 }
1937 }
1938 }
1939
1940 @Override
1941 public int getRequestedOrientation(IBinder token) {
1942 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001943 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1944 return (r != null)
1945 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001946 }
1947 }
1948
1949 @Override
1950 public void setImmersive(IBinder token, boolean immersive) {
1951 synchronized (mGlobalLock) {
1952 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1953 if (r == null) {
1954 throw new IllegalArgumentException();
1955 }
1956 r.immersive = immersive;
1957
1958 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001959 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001960 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001961 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 }
1963 }
1964 }
1965
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001966 void applyUpdateLockStateLocked(ActivityRecord r) {
1967 // Modifications to the UpdateLock state are done on our handler, outside
1968 // the activity manager's locks. The new state is determined based on the
1969 // state *now* of the relevant activity record. The object is passed to
1970 // the handler solely for logging detail, not to be consulted/modified.
1971 final boolean nextState = r != null && r.immersive;
1972 mH.post(() -> {
1973 if (mUpdateLock.isHeld() != nextState) {
1974 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1975 "Applying new update lock state '" + nextState + "' for " + r);
1976 if (nextState) {
1977 mUpdateLock.acquire();
1978 } else {
1979 mUpdateLock.release();
1980 }
1981 }
1982 });
1983 }
1984
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001985 @Override
1986 public boolean isImmersive(IBinder token) {
1987 synchronized (mGlobalLock) {
1988 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1989 if (r == null) {
1990 throw new IllegalArgumentException();
1991 }
1992 return r.immersive;
1993 }
1994 }
1995
1996 @Override
1997 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001998 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002000 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
2001 if (topFocusedStack == null) {
2002 return false;
2003 }
2004
2005 final ActivityRecord r = topFocusedStack.topRunningActivity();
2006 return r != null && r.immersive;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002007 }
2008 }
2009
2010 @Override
2011 public void overridePendingTransition(IBinder token, String packageName,
2012 int enterAnim, int exitAnim) {
2013 synchronized (mGlobalLock) {
2014 ActivityRecord self = ActivityRecord.isInStackLocked(token);
2015 if (self == null) {
2016 return;
2017 }
2018
2019 final long origId = Binder.clearCallingIdentity();
2020
2021 if (self.isState(
2022 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08002023 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
Ming-Shin Lub6d70022020-03-27 23:51:56 +08002024 packageName, enterAnim, exitAnim, null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002025 }
2026
2027 Binder.restoreCallingIdentity(origId);
2028 }
2029 }
2030
2031 @Override
2032 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002033 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002034 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002035 final ActivityStack stack = getTopDisplayFocusedStack();
2036 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002037 if (r == null) {
2038 return ActivityManager.COMPAT_MODE_UNKNOWN;
2039 }
Wale Ogunwale53783742018-09-16 10:21:51 -07002040 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002041 }
2042 }
2043
2044 @Override
2045 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002046 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002047 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002048 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002049 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002050 final ActivityStack stack = getTopDisplayFocusedStack();
2051 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002052 if (r == null) {
2053 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
2054 return;
2055 }
2056 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07002057 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002058 }
2059 }
2060
2061 @Override
2062 public int getLaunchedFromUid(IBinder activityToken) {
2063 ActivityRecord srec;
2064 synchronized (mGlobalLock) {
2065 srec = ActivityRecord.forTokenLocked(activityToken);
2066 }
2067 if (srec == null) {
2068 return -1;
2069 }
2070 return srec.launchedFromUid;
2071 }
2072
2073 @Override
2074 public String getLaunchedFromPackage(IBinder activityToken) {
2075 ActivityRecord srec;
2076 synchronized (mGlobalLock) {
2077 srec = ActivityRecord.forTokenLocked(activityToken);
2078 }
2079 if (srec == null) {
2080 return null;
2081 }
2082 return srec.launchedFromPackage;
2083 }
2084
2085 @Override
2086 public boolean convertFromTranslucent(IBinder token) {
2087 final long origId = Binder.clearCallingIdentity();
2088 try {
2089 synchronized (mGlobalLock) {
2090 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2091 if (r == null) {
2092 return false;
2093 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002094 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002095 }
2096 } finally {
2097 Binder.restoreCallingIdentity(origId);
2098 }
2099 }
2100
2101 @Override
2102 public boolean convertToTranslucent(IBinder token, Bundle options) {
2103 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2104 final long origId = Binder.clearCallingIdentity();
2105 try {
2106 synchronized (mGlobalLock) {
2107 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2108 if (r == null) {
2109 return false;
2110 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002111 final ActivityRecord under = r.getTask().getActivityBelow(r);
2112 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002113 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2114 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002115 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002116 }
2117 } finally {
2118 Binder.restoreCallingIdentity(origId);
2119 }
2120 }
2121
2122 @Override
2123 public void notifyActivityDrawn(IBinder token) {
2124 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2125 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002126 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002127 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002128 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002129 }
2130 }
2131 }
2132
2133 @Override
2134 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2135 synchronized (mGlobalLock) {
2136 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2137 if (r == null) {
2138 return;
2139 }
2140 r.reportFullyDrawnLocked(restoredFromBundle);
2141 }
2142 }
2143
2144 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002145 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002146 synchronized (mGlobalLock) {
2147 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002148 if (stack != null) {
2149 final int displayId = stack.getDisplayId();
2150 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002151 }
2152 return DEFAULT_DISPLAY;
2153 }
2154 }
2155
2156 @Override
2157 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002158 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002159 long ident = Binder.clearCallingIdentity();
2160 try {
2161 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002162 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002163 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002164 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002165 }
2166 return null;
2167 }
2168 } finally {
2169 Binder.restoreCallingIdentity(ident);
2170 }
2171 }
2172
2173 @Override
2174 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002175 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002176 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2177 final long callingId = Binder.clearCallingIdentity();
2178 try {
2179 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002180 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002181 if (stack == null) {
2182 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2183 return;
2184 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002185 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002186 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002187 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002188 }
2189 }
2190 } finally {
2191 Binder.restoreCallingIdentity(callingId);
2192 }
2193 }
2194
2195 @Override
2196 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002197 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002198 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2199 final long callingId = Binder.clearCallingIdentity();
2200 try {
2201 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002202 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002203 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002204 if (task == null) {
2205 return;
2206 }
2207 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002208 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002209 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002210 }
2211 }
2212 } finally {
2213 Binder.restoreCallingIdentity(callingId);
2214 }
2215 }
2216
2217 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002218 public void restartActivityProcessIfVisible(IBinder activityToken) {
2219 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2220 final long callingId = Binder.clearCallingIdentity();
2221 try {
2222 synchronized (mGlobalLock) {
2223 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2224 if (r == null) {
2225 return;
2226 }
2227 r.restartProcessIfVisible();
2228 }
2229 } finally {
2230 Binder.restoreCallingIdentity(callingId);
2231 }
2232 }
2233
2234 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002235 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002236 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002237 synchronized (mGlobalLock) {
2238 final long ident = Binder.clearCallingIdentity();
2239 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002240 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002241 "remove-task");
2242 } finally {
2243 Binder.restoreCallingIdentity(ident);
2244 }
2245 }
2246 }
2247
2248 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002249 public void removeAllVisibleRecentTasks() {
2250 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2251 synchronized (mGlobalLock) {
2252 final long ident = Binder.clearCallingIdentity();
2253 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002254 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002255 } finally {
2256 Binder.restoreCallingIdentity(ident);
2257 }
2258 }
2259 }
2260
2261 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002262 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2263 synchronized (mGlobalLock) {
2264 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2265 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002266 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002267 }
2268 }
2269 return false;
2270 }
2271
2272 @Override
2273 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2274 Intent resultData) {
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06002275 final ActivityRecord r;
2276 synchronized (mGlobalLock) {
2277 r = ActivityRecord.isInStackLocked(token);
2278 if (r == null) {
2279 return false;
2280 }
2281 }
2282
2283 // Carefully collect grants without holding lock
2284 final NeededUriGrants destGrants = collectGrants(destIntent, r);
2285 final NeededUriGrants resultGrants = collectGrants(resultData, r.resultTo);
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002286
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002287 synchronized (mGlobalLock) {
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06002288 return r.getRootTask().navigateUpTo(
2289 r, destIntent, destGrants, resultCode, resultData, resultGrants);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002290 }
2291 }
2292
2293 /**
2294 * Attempts to move a task backwards in z-order (the order of activities within the task is
2295 * unchanged).
2296 *
2297 * There are several possible results of this call:
2298 * - if the task is locked, then we will show the lock toast
2299 * - if there is a task behind the provided task, then that task is made visible and resumed as
2300 * this task is moved to the back
2301 * - otherwise, if there are no other tasks in the stack:
2302 * - if this task is in the pinned stack, then we remove the stack completely, which will
2303 * have the effect of moving the task to the top or bottom of the fullscreen stack
2304 * (depending on whether it is visible)
2305 * - otherwise, we simply return home and hide this task
2306 *
2307 * @param token A reference to the activity we wish to move
2308 * @param nonRoot If false then this only works if the activity is the root
2309 * of a task; if true it will work for any activity in a task.
2310 * @return Returns true if the move completed, false if not.
2311 */
2312 @Override
2313 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002314 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002315 synchronized (mGlobalLock) {
2316 final long origId = Binder.clearCallingIdentity();
2317 try {
2318 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002319 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002320 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002321 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002322 }
2323 } finally {
2324 Binder.restoreCallingIdentity(origId);
2325 }
2326 }
2327 return false;
2328 }
2329
2330 @Override
2331 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002332 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002333 long ident = Binder.clearCallingIdentity();
2334 Rect rect = new Rect();
2335 try {
2336 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002337 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002338 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2339 if (task == null) {
2340 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2341 return rect;
2342 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002343 if (task.getParent() != null) {
2344 rect.set(task.getBounds());
2345 } else if (task.mLastNonFullscreenBounds != null) {
2346 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002347 }
2348 }
2349 } finally {
2350 Binder.restoreCallingIdentity(ident);
2351 }
2352 return rect;
2353 }
2354
2355 @Override
2356 public ActivityManager.TaskDescription getTaskDescription(int id) {
2357 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002358 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002359 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002360 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002361 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2362 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002363 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002364 }
2365 }
2366 return null;
2367 }
2368
2369 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002370 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002371 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08002372 return setTaskWindowingModeSplitScreenPrimary(taskId, toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002373 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002374 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002375 synchronized (mGlobalLock) {
2376 final long ident = Binder.clearCallingIdentity();
2377 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002378 if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2379 return setTaskWindowingModeSplitScreen(taskId, windowingMode, toTop);
2380 }
Louis Chang149d5c82019-12-30 09:47:39 +08002381 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002382 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002383 if (task == null) {
2384 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002385 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002386 }
2387
2388 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2389 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2390
2391 if (!task.isActivityTypeStandardOrUndefined()) {
2392 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2393 + " non-standard task " + taskId + " to windowing mode="
2394 + windowingMode);
2395 }
2396
2397 final ActivityStack stack = task.getStack();
2398 if (toTop) {
2399 stack.moveToFront("setTaskWindowingMode", task);
2400 }
Louis Changa009c762020-02-26 11:21:31 +08002401 // Convert some windowing-mode changes into root-task reparents for split-screen.
2402 if (stack.inSplitScreenWindowingMode()) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07002403 stack.getDisplayArea().onSplitScreenModeDismissed();
Louis Changa009c762020-02-26 11:21:31 +08002404
2405 } else {
2406 stack.setWindowingMode(windowingMode);
2407 stack.getDisplay().ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2408 true /* notifyClients */);
2409 }
Winson Chung7ccc6812020-01-23 16:15:10 -08002410 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002411 } finally {
2412 Binder.restoreCallingIdentity(ident);
2413 }
2414 }
2415 }
2416
2417 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002418 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002419 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002420 ActivityRecord r = getCallingRecordLocked(token);
2421 return r != null ? r.info.packageName : null;
2422 }
2423 }
2424
2425 @Override
2426 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002427 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002428 ActivityRecord r = getCallingRecordLocked(token);
2429 return r != null ? r.intent.getComponent() : null;
2430 }
2431 }
2432
2433 private ActivityRecord getCallingRecordLocked(IBinder token) {
2434 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2435 if (r == null) {
2436 return null;
2437 }
2438 return r.resultTo;
2439 }
2440
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06002441 private NeededUriGrants collectGrants(Intent intent, ActivityRecord target) {
2442 if (target != null) {
2443 return mUgmInternal.checkGrantUriPermissionFromIntent(intent,
2444 Binder.getCallingUid(), target.packageName, target.mUserId);
2445 } else {
2446 return null;
2447 }
2448 }
2449
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002450 @Override
2451 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002452 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002453
2454 synchronized (mGlobalLock) {
2455 final long origId = Binder.clearCallingIdentity();
2456 try {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002457 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
2458 if (topFocusedStack != null) {
2459 topFocusedStack.unhandledBackLocked();
2460 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002461 } finally {
2462 Binder.restoreCallingIdentity(origId);
2463 }
2464 }
2465 }
2466
Mark Renouf446251d2019-04-26 10:22:41 -04002467 @Override
2468 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2469 synchronized (mGlobalLock) {
2470 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2471 if (r == null) {
2472 return;
2473 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002474 ActivityStack stack = r.getRootTask();
Winson Chunga1f869d2020-03-21 23:02:48 -07002475 final TaskOrganizerController taskOrgController =
2476 mWindowOrganizerController.mTaskOrganizerController;
2477 if (taskOrgController.handleInterceptBackPressedOnTaskRoot(stack)) {
2478 // This task is handled by a task organizer that has requested the back pressed
2479 // callback
2480 } else if (stack != null && (stack.isSingleTaskInstance())) {
Mark Renouf446251d2019-04-26 10:22:41 -04002481 // Single-task stacks are used for activities which are presented in floating
2482 // windows above full screen activities. Instead of directly finishing the
2483 // task, a task change listener is used to notify SystemUI so the action can be
2484 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002485 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002486 mTaskChangeNotificationController
2487 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2488 } else {
2489 try {
2490 callback.requestFinish();
2491 } catch (RemoteException e) {
2492 Slog.e(TAG, "Failed to invoke request finish callback", e);
2493 }
2494 }
2495 }
2496 }
2497
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002498 /**
2499 * TODO: Add mController hook
2500 */
2501 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002502 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2503 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002504 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002505
2506 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2507 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002508 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
Riddle Hsueae6ef3e2020-05-13 01:07:33 +08002509 SafeActivityOptions.fromBundle(bOptions));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002510 }
2511 }
2512
Ricky Waiaca8a772019-04-04 16:01:06 +01002513 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
Riddle Hsueae6ef3e2020-05-13 01:07:33 +08002514 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002515 final int callingPid = Binder.getCallingPid();
2516 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002517 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002518 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002519 SafeActivityOptions.abort(options);
2520 return;
2521 }
2522 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002523 WindowProcessController callerApp = null;
2524 if (appThread != null) {
2525 callerApp = getProcessController(appThread);
2526 }
2527 final ActivityStarter starter = getActivityStartController().obtainStarter(
2528 null /* intent */, "moveTaskToFront");
2529 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
Galia Peychevaed401cc2020-03-19 20:28:09 +01002530 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002531 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002532 return;
2533 }
2534 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002535 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002536 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002537 if (task == null) {
2538 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002539 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002540 return;
2541 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002542 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002543 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002544 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002545 return;
2546 }
2547 ActivityOptions realOptions = options != null
2548 ? options.getOptions(mStackSupervisor)
2549 : null;
2550 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2551 false /* forceNonResizable */);
2552
Wale Ogunwale21e06482019-11-18 05:14:15 -08002553 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002554 if (topActivity != null) {
2555
2556 // We are reshowing a task, use a starting window to hide the initial draw delay
2557 // so the transition can start earlier.
2558 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
Riddle Hsueae6ef3e2020-05-13 01:07:33 +08002559 true /* taskSwitch */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002560 }
2561 } finally {
2562 Binder.restoreCallingIdentity(origId);
2563 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002564 }
2565
Ricky Waiaca8a772019-04-04 16:01:06 +01002566 /**
2567 * Return true if callingUid is system, or packageName belongs to that callingUid.
2568 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002569 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002570 try {
2571 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2572 if (packageName == null) {
2573 return false;
2574 }
2575 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2576 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2577 UserHandle.getUserId(callingUid));
2578 return UserHandle.isSameApp(callingUid, uid);
2579 }
2580 } catch (RemoteException e) {
2581 // Should not happen
2582 }
2583 return true;
2584 }
2585
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002586 /**
2587 * Checks that the provided package name matches the current calling UID, throws a security
2588 * exception if it doesn't.
2589 */
2590 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2591 final int callingUid = Binder.getCallingUid();
2592 if (isSameApp(callingUid, packageName)) {
2593 return;
2594 }
2595 final String msg = "Permission Denial: package=" + packageName
2596 + " does not belong to uid=" + callingUid;
2597 Slog.w(TAG, msg);
2598 throw new SecurityException(msg);
2599 }
2600
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002601 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2602 int callingPid, int callingUid, String name) {
2603 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2604 return true;
2605 }
2606
2607 if (getRecentTasks().isCallerRecents(sourceUid)) {
2608 return true;
2609 }
2610
2611 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2612 if (perm == PackageManager.PERMISSION_GRANTED) {
2613 return true;
2614 }
2615 if (checkAllowAppSwitchUid(sourceUid)) {
2616 return true;
2617 }
2618
2619 // If the actual IPC caller is different from the logical source, then
2620 // also see if they are allowed to control app switches.
2621 if (callingUid != -1 && callingUid != sourceUid) {
2622 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2623 if (perm == PackageManager.PERMISSION_GRANTED) {
2624 return true;
2625 }
2626 if (checkAllowAppSwitchUid(callingUid)) {
2627 return true;
2628 }
2629 }
2630
2631 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2632 return false;
2633 }
2634
2635 private boolean checkAllowAppSwitchUid(int uid) {
2636 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2637 if (types != null) {
2638 for (int i = types.size() - 1; i >= 0; i--) {
2639 if (types.valueAt(i).intValue() == uid) {
2640 return true;
2641 }
2642 }
2643 }
2644 return false;
2645 }
2646
2647 @Override
2648 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2649 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2650 "setActivityController()");
2651 synchronized (mGlobalLock) {
2652 mController = controller;
2653 mControllerIsAMonkey = imAMonkey;
2654 Watchdog.getInstance().setActivityController(controller);
2655 }
2656 }
2657
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002658 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002659 synchronized (mGlobalLock) {
2660 return mController != null && mControllerIsAMonkey;
2661 }
2662 }
2663
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002664 @Override
2665 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2666 synchronized (mGlobalLock) {
2667 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2668 }
2669 }
2670
2671 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002672 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
Winson Chunge5ab0172020-03-21 23:00:24 -07002673 return getFilteredTasks(maxNum, false /* filterForVisibleRecents */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002674 }
2675
Winson Chunge5ab0172020-03-21 23:00:24 -07002676 /**
2677 * @param filterOnlyVisibleRecents whether to filter the tasks based on whether they would ever
2678 * be visible in the recent task list in systemui
2679 */
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002680 @Override
2681 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
Winson Chunge5ab0172020-03-21 23:00:24 -07002682 boolean filterOnlyVisibleRecents) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002683 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002684 final int callingPid = Binder.getCallingPid();
2685 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002686 final int[] profileIds = getUserManager().getProfileIds(
2687 UserHandle.getUserId(callingUid), true);
2688 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2689 for (int i = 0; i < profileIds.length; i++) {
2690 callingProfileIds.add(profileIds[i]);
2691 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002692 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2693
2694 synchronized (mGlobalLock) {
2695 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2696
Nicholas Sauer0259e532019-08-30 08:24:55 -07002697 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Winson Chunge5ab0172020-03-21 23:00:24 -07002698 mRootWindowContainer.getRunningTasks(maxNum, list, filterOnlyVisibleRecents, callingUid,
2699 allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002700 }
2701
2702 return list;
2703 }
2704
2705 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002706 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2707 synchronized (mGlobalLock) {
2708 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002709 try {
2710 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2711 if (r == null) return;
2712
2713 final PooledConsumer c = PooledLambda.obtainConsumer(
2714 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2715 r, resultWho, requestCode);
2716 // TODO: This should probably only loop over the task since you need to be in the
2717 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002718 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002719 c.recycle();
2720
2721 updateOomAdj();
2722 } finally {
2723 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002724 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002725 }
2726 }
2727
2728 @Override
2729 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002730 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002731 ActivityStack stack = ActivityRecord.getStackLocked(token);
2732 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002733 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002734 }
2735 return false;
2736 }
2737 }
2738
2739 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002740 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002741 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002742 synchronized (mGlobalLock) {
2743 final long ident = Binder.clearCallingIdentity();
2744 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002745 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002746 if (task == null) {
2747 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2748 return;
2749 }
2750
2751 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2752 + " to stackId=" + stackId + " toTop=" + toTop);
2753
Louis Chang149d5c82019-12-30 09:47:39 +08002754 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002755 if (stack == null) {
2756 throw new IllegalStateException(
2757 "moveTaskToStack: No stack for stackId=" + stackId);
2758 }
2759 if (!stack.isActivityTypeStandardOrUndefined()) {
2760 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2761 + taskId + " to stack " + stackId);
2762 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002763 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2764 "moveTaskToStack");
2765 } finally {
2766 Binder.restoreCallingIdentity(ident);
2767 }
2768 }
2769 }
2770
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002771 /**
2772 * Moves the specified task to the primary-split-screen stack.
2773 *
2774 * @param taskId Id of task to move.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002775 * @param toTop If the task and stack should be moved to the top.
Winson Chung7ccc6812020-01-23 16:15:10 -08002776 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002777 */
2778 @Override
Evan Rosky73a7fe92019-11-18 18:28:01 -08002779 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002780 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002781 "setTaskWindowingModeSplitScreenPrimary()");
2782 synchronized (mGlobalLock) {
2783 final long ident = Binder.clearCallingIdentity();
2784 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002785 return setTaskWindowingModeSplitScreen(taskId, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY,
2786 toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002787 } finally {
2788 Binder.restoreCallingIdentity(ident);
2789 }
2790 }
2791 }
2792
2793 /**
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002794 * Moves the specified task into a split-screen tile.
2795 */
2796 private boolean setTaskWindowingModeSplitScreen(int taskId, int windowingMode, boolean toTop) {
2797 if (!WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2798 throw new IllegalArgumentException("Calling setTaskWindowingModeSplitScreen with non"
2799 + "split-screen mode: " + windowingMode);
2800 }
2801 if (isInLockTaskMode()) {
2802 Slog.w(TAG, "setTaskWindowingModeSplitScreen: Is in lock task mode="
2803 + getLockTaskModeState());
2804 return false;
2805 }
2806
2807 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2808 MATCH_TASK_IN_STACKS_ONLY);
2809 if (task == null) {
2810 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2811 return false;
2812 }
2813 if (!task.isActivityTypeStandardOrUndefined()) {
2814 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2815 + " non-standard task " + taskId + " to split-screen windowing mode");
2816 }
Wale Ogunwale0d465192020-01-23 19:14:44 -08002817 if (!task.supportsSplitScreenWindowingMode()) {
2818 return false;
2819 }
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002820
2821 final int prevMode = task.getWindowingMode();
Louis Changcf3d1452020-04-16 16:36:05 +08002822 if (prevMode == windowingMode) {
2823 // The task is already in split-screen and with correct windowing mode.
2824 return true;
2825 }
2826
Louis Changa009c762020-02-26 11:21:31 +08002827 moveTaskToSplitScreenPrimaryTask(task, toTop);
Wale Ogunwale0d465192020-01-23 19:14:44 -08002828 return prevMode != task.getWindowingMode();
2829 }
2830
Louis Changa009c762020-02-26 11:21:31 +08002831 void moveTaskToSplitScreenPrimaryTask(Task task, boolean toTop) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07002832 final TaskDisplayArea taskDisplayArea = task.getDisplayArea();
2833 final ActivityStack primarySplitTask = taskDisplayArea.getRootSplitScreenPrimaryTask();
Louis Changa009c762020-02-26 11:21:31 +08002834 if (primarySplitTask == null) {
2835 throw new IllegalStateException("Can't enter split without associated organized task");
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002836 }
Louis Changa009c762020-02-26 11:21:31 +08002837
2838 if (toTop) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07002839 taskDisplayArea.positionStackAt(POSITION_TOP, primarySplitTask,
Andrii Kulian9ea12da2020-03-27 17:16:38 -07002840 false /* includingParents */);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002841 }
2842 WindowContainerTransaction wct = new WindowContainerTransaction();
Wale Ogunwale465b1e12020-03-31 12:15:51 -07002843 // Clear out current windowing mode before reparenting to split taks.
2844 wct.setWindowingMode(
2845 task.getStack().mRemoteToken.toWindowContainerToken(), WINDOWING_MODE_UNDEFINED);
Wale Ogunwaleadf116e2020-03-27 16:36:01 -07002846 wct.reparent(task.getStack().mRemoteToken.toWindowContainerToken(),
2847 primarySplitTask.mRemoteToken.toWindowContainerToken(), toTop);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07002848 mWindowOrganizerController.applyTransaction(wct);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002849 }
2850
2851 /**
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002852 * Removes stacks in the input windowing modes from the system if they are of activity type
2853 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2854 */
2855 @Override
2856 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002857 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002858 "removeStacksInWindowingModes()");
2859
2860 synchronized (mGlobalLock) {
2861 final long ident = Binder.clearCallingIdentity();
2862 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002863 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002864 } finally {
2865 Binder.restoreCallingIdentity(ident);
2866 }
2867 }
2868 }
2869
2870 @Override
2871 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002872 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002873 "removeStacksWithActivityTypes()");
2874
2875 synchronized (mGlobalLock) {
2876 final long ident = Binder.clearCallingIdentity();
2877 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002878 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002879 } finally {
2880 Binder.restoreCallingIdentity(ident);
2881 }
2882 }
2883 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884
2885 @Override
2886 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2887 int userId) {
2888 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002889 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2890 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002891 callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002892 synchronized (mGlobalLock) {
Winson Chung66b08f02020-03-03 14:32:35 -08002893 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, userId, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002894 }
2895 }
2896
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002897 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002898 @Override
2899 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002900 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002901 long ident = Binder.clearCallingIdentity();
2902 try {
2903 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002904 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002905 }
2906 } finally {
2907 Binder.restoreCallingIdentity(ident);
2908 }
2909 }
2910
2911 @Override
2912 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002913 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002914 long ident = Binder.clearCallingIdentity();
2915 try {
2916 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002917 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002918 }
2919 } finally {
2920 Binder.restoreCallingIdentity(ident);
2921 }
2922 }
2923
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002924 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002926 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2927 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2928 long ident = Binder.clearCallingIdentity();
2929 try {
2930 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002931 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002932 }
2933 } finally {
2934 Binder.restoreCallingIdentity(ident);
2935 }
2936 }
2937
2938 @Override
2939 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2940 int displayId) {
2941 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2942 long ident = Binder.clearCallingIdentity();
2943 try {
2944 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002945 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002946 }
2947 } finally {
2948 Binder.restoreCallingIdentity(ident);
2949 }
2950 }
2951
2952 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002953 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002954 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002955 final long callingUid = Binder.getCallingUid();
2956 final long origId = Binder.clearCallingIdentity();
2957 try {
2958 synchronized (mGlobalLock) {
2959 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002960 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002961 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2962 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2963 }
2964 } finally {
2965 Binder.restoreCallingIdentity(origId);
2966 }
2967 }
2968
2969 @Override
2970 public void startLockTaskModeByToken(IBinder token) {
2971 synchronized (mGlobalLock) {
2972 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2973 if (r == null) {
2974 return;
2975 }
Louis Changcdec0802019-11-11 11:45:07 +08002976 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002977 }
2978 }
2979
2980 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002981 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002982 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002983 // This makes inner call to look as if it was initiated by system.
2984 long ident = Binder.clearCallingIdentity();
2985 try {
2986 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002987 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002988 MATCH_TASK_IN_STACKS_ONLY);
2989 if (task == null) {
2990 return;
2991 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002992
2993 // When starting lock task mode the stack must be in front and focused
2994 task.getStack().moveToFront("startSystemLockTaskMode");
2995 startLockTaskModeLocked(task, true /* isSystemCaller */);
2996 }
2997 } finally {
2998 Binder.restoreCallingIdentity(ident);
2999 }
3000 }
3001
3002 @Override
3003 public void stopLockTaskModeByToken(IBinder token) {
3004 synchronized (mGlobalLock) {
3005 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3006 if (r == null) {
3007 return;
3008 }
Louis Changcdec0802019-11-11 11:45:07 +08003009 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003010 }
3011 }
3012
3013 /**
3014 * This API should be called by SystemUI only when user perform certain action to dismiss
3015 * lock task mode. We should only dismiss pinned lock task mode in this case.
3016 */
3017 @Override
3018 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003019 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003020 stopLockTaskModeInternal(null, true /* isSystemCaller */);
3021 }
3022
Louis Changcdec0802019-11-11 11:45:07 +08003023 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003024 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
3025 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
3026 return;
3027 }
3028
Louis Chang149d5c82019-12-30 09:47:39 +08003029 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09003030 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003031 throw new IllegalArgumentException("Invalid task, not in foreground");
3032 }
3033
3034 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
3035 // system or a specific app.
3036 // * System-initiated requests will only start the pinned mode (screen pinning)
3037 // * App-initiated requests
3038 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
3039 // - will start the pinned mode, otherwise
3040 final int callingUid = Binder.getCallingUid();
3041 long ident = Binder.clearCallingIdentity();
3042 try {
3043 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08003044 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003045
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003046 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003047 } finally {
3048 Binder.restoreCallingIdentity(ident);
3049 }
3050 }
3051
Louis Changcdec0802019-11-11 11:45:07 +08003052 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003053 final int callingUid = Binder.getCallingUid();
3054 long ident = Binder.clearCallingIdentity();
3055 try {
3056 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003057 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003058 }
3059 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
3060 // task and jumping straight into a call in the case of emergency call back.
3061 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
3062 if (tm != null) {
3063 tm.showInCallScreen(false);
3064 }
3065 } finally {
3066 Binder.restoreCallingIdentity(ident);
3067 }
3068 }
3069
3070 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003071 public void updateLockTaskPackages(int userId, String[] packages) {
3072 final int callingUid = Binder.getCallingUid();
3073 if (callingUid != 0 && callingUid != SYSTEM_UID) {
3074 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
3075 "updateLockTaskPackages()");
3076 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08003077 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003078 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
3079 + Arrays.toString(packages));
3080 getLockTaskController().updateLockTaskPackages(userId, packages);
3081 }
3082 }
3083
3084 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003085 public boolean isInLockTaskMode() {
3086 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3087 }
3088
3089 @Override
3090 public int getLockTaskModeState() {
3091 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003092 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003093 }
3094 }
3095
3096 @Override
3097 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3098 synchronized (mGlobalLock) {
3099 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3100 if (r != null) {
3101 r.setTaskDescription(td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003102 }
3103 }
3104 }
3105
3106 @Override
3107 public Bundle getActivityOptions(IBinder token) {
3108 final long origId = Binder.clearCallingIdentity();
3109 try {
3110 synchronized (mGlobalLock) {
3111 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3112 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003113 final ActivityOptions activityOptions = r.takeOptionsLocked(
3114 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003115 return activityOptions == null ? null : activityOptions.toBundle();
3116 }
3117 return null;
3118 }
3119 } finally {
3120 Binder.restoreCallingIdentity(origId);
3121 }
3122 }
3123
3124 @Override
3125 public List<IBinder> getAppTasks(String callingPackage) {
3126 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003127 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003128 long ident = Binder.clearCallingIdentity();
3129 try {
3130 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003131 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003132 }
3133 } finally {
3134 Binder.restoreCallingIdentity(ident);
3135 }
3136 }
3137
3138 @Override
3139 public void finishVoiceTask(IVoiceInteractionSession session) {
3140 synchronized (mGlobalLock) {
3141 final long origId = Binder.clearCallingIdentity();
3142 try {
3143 // TODO: VI Consider treating local voice interactions and voice tasks
3144 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003145 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003146 } finally {
3147 Binder.restoreCallingIdentity(origId);
3148 }
3149 }
3150
3151 }
3152
3153 @Override
3154 public boolean isTopOfTask(IBinder token) {
3155 synchronized (mGlobalLock) {
3156 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003157 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003158 }
3159 }
3160
3161 @Override
3162 public void notifyLaunchTaskBehindComplete(IBinder token) {
3163 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3164 }
3165
3166 @Override
3167 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003168 mH.post(() -> {
3169 synchronized (mGlobalLock) {
3170 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003171 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003172 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003173 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003174 } catch (RemoteException e) {
3175 }
3176 }
3177 }
3178
3179 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003180 }
3181
3182 /** Called from an app when assist data is ready. */
3183 @Override
3184 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3185 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003186 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003187 synchronized (pae) {
3188 pae.result = extras;
3189 pae.structure = structure;
3190 pae.content = content;
3191 if (referrer != null) {
3192 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3193 }
3194 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003195 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003196 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003197 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003198 structure.setHomeActivity(pae.isHome);
3199 }
3200 pae.haveResult = true;
3201 pae.notifyAll();
3202 if (pae.intent == null && pae.receiver == null) {
3203 // Caller is just waiting for the result.
3204 return;
3205 }
3206 }
3207 // We are now ready to launch the assist activity.
3208 IAssistDataReceiver sendReceiver = null;
3209 Bundle sendBundle = null;
3210 synchronized (mGlobalLock) {
3211 buildAssistBundleLocked(pae, extras);
3212 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003213 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003214 if (!exists) {
3215 // Timed out.
3216 return;
3217 }
3218
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003219 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003220 // Caller wants result sent back to them.
3221 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003222 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003223 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003224 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3225 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003226 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3227 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3228 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3229 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3230 }
3231 }
3232 if (sendReceiver != null) {
3233 try {
3234 sendReceiver.onHandleAssistData(sendBundle);
3235 } catch (RemoteException e) {
3236 }
3237 return;
3238 }
3239
3240 final long ident = Binder.clearCallingIdentity();
3241 try {
3242 if (TextUtils.equals(pae.intent.getAction(),
3243 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003244 // Start voice interaction through VoiceInteractionManagerService.
Galia Peycheva969f9952020-05-11 20:26:45 +02003245 mAssistUtils.showSessionForActiveService(pae.extras, SHOW_SOURCE_APPLICATION,
Galia Peychevabffbfc32019-06-18 10:11:35 +02003246 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003247 } else {
3248 pae.intent.replaceExtras(pae.extras);
3249 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3250 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3251 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003252 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003253
3254 try {
3255 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3256 } catch (ActivityNotFoundException e) {
3257 Slog.w(TAG, "No activity to handle assist action.", e);
3258 }
3259 }
3260 } finally {
3261 Binder.restoreCallingIdentity(ident);
3262 }
3263 }
3264
3265 @Override
3266 public int addAppTask(IBinder activityToken, Intent intent,
3267 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3268 final int callingUid = Binder.getCallingUid();
3269 final long callingIdent = Binder.clearCallingIdentity();
3270
3271 try {
3272 synchronized (mGlobalLock) {
3273 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3274 if (r == null) {
3275 throw new IllegalArgumentException("Activity does not exist; token="
3276 + activityToken);
3277 }
3278 ComponentName comp = intent.getComponent();
3279 if (comp == null) {
3280 throw new IllegalArgumentException("Intent " + intent
3281 + " must specify explicit component");
3282 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003283 if (thumbnail.getWidth() != mThumbnailWidth
3284 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003285 throw new IllegalArgumentException("Bad thumbnail size: got "
3286 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003287 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003288 }
3289 if (intent.getSelector() != null) {
3290 intent.setSelector(null);
3291 }
3292 if (intent.getSourceBounds() != null) {
3293 intent.setSourceBounds(null);
3294 }
3295 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3296 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3297 // The caller has added this as an auto-remove task... that makes no
3298 // sense, so turn off auto-remove.
3299 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3300 }
3301 }
3302 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3303 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3304 if (ainfo.applicationInfo.uid != callingUid) {
3305 throw new SecurityException(
3306 "Can't add task for another application: target uid="
3307 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3308 }
3309
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003310 final ActivityStack stack = r.getRootTask();
Andrii Kulian86d676c2020-03-27 19:34:54 -07003311 final Task task = stack.getDisplayArea().createStack(stack.getWindowingMode(),
3312 stack.getActivityType(), !ON_TOP, ainfo, intent,
Louis Changa009c762020-02-26 11:21:31 +08003313 false /* createdByOrganizer */);
Wale Ogunwale0d465192020-01-23 19:14:44 -08003314
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003315 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003316 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003317 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003318 return INVALID_TASK_ID;
3319 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003320 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003321
3322 // TODO: Send the thumbnail to WM to store it.
3323
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003324 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003325 }
3326 } finally {
3327 Binder.restoreCallingIdentity(callingIdent);
3328 }
3329 }
3330
3331 @Override
3332 public Point getAppTaskThumbnailSize() {
3333 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003334 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003335 }
3336 }
3337
3338 @Override
3339 public void setTaskResizeable(int taskId, int resizeableMode) {
3340 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003341 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003342 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3343 if (task == null) {
3344 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3345 return;
3346 }
3347 task.setResizeMode(resizeableMode);
3348 }
3349 }
3350
3351 @Override
Daichi Hironofa23f602020-05-14 06:15:59 +00003352 public boolean resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003353 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003354 long ident = Binder.clearCallingIdentity();
3355 try {
3356 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003357 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003358 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003359 if (task == null) {
3360 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
Daichi Hironofa23f602020-05-14 06:15:59 +00003361 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003362 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003363 if (!task.getWindowConfiguration().canResizeTask()) {
Daichi Hironofa23f602020-05-14 06:15:59 +00003364 Slog.w(TAG, "resizeTask not allowed on task=" + task);
3365 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003366 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003367
3368 // Reparent the task to the right stack if necessary
3369 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370
3371 // After reparenting (which only resizes the task to the stack bounds), resize the
3372 // task to the actual bounds provided
Daichi Hironofa23f602020-05-14 06:15:59 +00003373 return task.resize(bounds, resizeMode, preserveWindow);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003374 }
3375 } finally {
3376 Binder.restoreCallingIdentity(ident);
3377 }
3378 }
3379
3380 @Override
3381 public boolean releaseActivityInstance(IBinder token) {
3382 synchronized (mGlobalLock) {
3383 final long origId = Binder.clearCallingIdentity();
3384 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003385 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3386 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003387 return false;
3388 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003389 r.destroyImmediately(true /* removeFromApp */, "app-req");
3390 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003391 } finally {
3392 Binder.restoreCallingIdentity(origId);
3393 }
3394 }
3395 }
3396
3397 @Override
3398 public void releaseSomeActivities(IApplicationThread appInt) {
3399 synchronized (mGlobalLock) {
3400 final long origId = Binder.clearCallingIdentity();
3401 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003402 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003403 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 } finally {
3405 Binder.restoreCallingIdentity(origId);
3406 }
3407 }
3408 }
3409
3410 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003411 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003412 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003413 != PackageManager.PERMISSION_GRANTED) {
3414 throw new SecurityException("Requires permission "
3415 + android.Manifest.permission.DEVICE_POWER);
3416 }
3417
3418 synchronized (mGlobalLock) {
3419 long ident = Binder.clearCallingIdentity();
3420 if (mKeyguardShown != keyguardShowing) {
3421 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003422 final Message msg = PooledLambda.obtainMessage(
3423 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3424 keyguardShowing);
3425 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003426 }
3427 try {
wilsonshih177261f2019-02-22 12:02:18 +08003428 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003429 } finally {
3430 Binder.restoreCallingIdentity(ident);
3431 }
3432 }
3433
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003434 mH.post(() -> {
3435 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3436 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3437 }
3438 });
3439 }
3440
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003441 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003442 mH.post(() -> {
3443 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3444 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3445 }
3446 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003447 }
3448
3449 @Override
3450 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003451 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3452 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003453
3454 final File passedIconFile = new File(filePath);
3455 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3456 passedIconFile.getName());
3457 if (!legitIconFile.getPath().equals(filePath)
3458 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3459 throw new IllegalArgumentException("Bad file path: " + filePath
3460 + " passed for userId " + userId);
3461 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003462 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003463 }
3464
3465 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003466 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003467 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003468 synchronized (mGlobalLock) {
3469 final long ident = Binder.clearCallingIdentity();
3470 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003471 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003472 if (stack == null) {
3473 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3474 return;
3475 }
3476 if (!stack.isActivityTypeStandardOrUndefined()) {
3477 throw new IllegalArgumentException(
3478 "Removing non-standard stack is not allowed.");
3479 }
3480 mStackSupervisor.removeStack(stack);
3481 } finally {
3482 Binder.restoreCallingIdentity(ident);
3483 }
3484 }
3485 }
3486
3487 @Override
3488 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003489 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003490
3491 synchronized (mGlobalLock) {
3492 final long ident = Binder.clearCallingIdentity();
3493 try {
3494 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3495 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003496 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003497 } finally {
3498 Binder.restoreCallingIdentity(ident);
3499 }
3500 }
3501 }
3502
3503 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003504 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003505 synchronized (mGlobalLock) {
3506 long ident = Binder.clearCallingIdentity();
3507 try {
3508 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3509 if (r == null) {
3510 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003511 "toggleFreeformWindowingMode: No activity record matching token="
3512 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003513 }
3514
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003515 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003516 if (stack == null) {
3517 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3518 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003519 }
3520
Yunfan Chend967af82019-01-17 18:30:18 +09003521 if (!stack.inFreeformWindowingMode()
3522 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3523 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3524 + "toggle between fullscreen and freeform.");
3525 }
3526
3527 if (stack.inFreeformWindowingMode()) {
3528 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003529 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003530 throw new IllegalStateException("Size-compat windows are currently not"
3531 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003532 } else if (stack.getParent().inFreeformWindowingMode()) {
3533 // If the window is on a freeform display, set it to undefined. It will be
3534 // resolved to freeform and it can adjust windowing mode when the display mode
3535 // changes in runtime.
3536 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003537 } else {
3538 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3539 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003540 } finally {
3541 Binder.restoreCallingIdentity(ident);
3542 }
3543 }
3544 }
3545
3546 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3547 @Override
3548 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003549 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003550 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003551 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003552 }
3553
3554 /** Unregister a task stack listener so that it stops receiving callbacks. */
3555 @Override
3556 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003557 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003558 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003559 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003560 }
3561
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003562 @Override
3563 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3564 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3565 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3566 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3567 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3568 }
3569
3570 @Override
3571 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3572 IBinder activityToken, int flags) {
3573 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3574 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3575 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3576 }
3577
3578 @Override
3579 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3580 Bundle args) {
3581 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3582 true /* focused */, true /* newSessionId */, userHandle, args,
3583 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3584 }
3585
3586 @Override
3587 public Bundle getAssistContextExtras(int requestType) {
3588 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3589 null, null, true /* focused */, true /* newSessionId */,
3590 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3591 if (pae == null) {
3592 return null;
3593 }
3594 synchronized (pae) {
3595 while (!pae.haveResult) {
3596 try {
3597 pae.wait();
3598 } catch (InterruptedException e) {
3599 }
3600 }
3601 }
3602 synchronized (mGlobalLock) {
3603 buildAssistBundleLocked(pae, pae.result);
3604 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003605 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003606 }
3607 return pae.extras;
3608 }
3609
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003610 /**
3611 * Binder IPC calls go through the public entry point.
3612 * This can be called with or without the global lock held.
3613 */
3614 private static int checkCallingPermission(String permission) {
3615 return checkPermission(
3616 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3617 }
3618
3619 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003620 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003621 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3622 mAmInternal.enforceCallingPermission(permission, func);
3623 }
3624 }
3625
3626 @VisibleForTesting
3627 int checkGetTasksPermission(String permission, int pid, int uid) {
3628 return checkPermission(permission, pid, uid);
3629 }
3630
3631 static int checkPermission(String permission, int pid, int uid) {
3632 if (permission == null) {
3633 return PackageManager.PERMISSION_DENIED;
3634 }
3635 return checkComponentPermission(permission, pid, uid, -1, true);
3636 }
3637
Wale Ogunwale214f3482018-10-04 11:00:47 -07003638 public static int checkComponentPermission(String permission, int pid, int uid,
3639 int owningUid, boolean exported) {
3640 return ActivityManagerService.checkComponentPermission(
3641 permission, pid, uid, owningUid, exported);
3642 }
3643
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003644 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3645 if (getRecentTasks().isCallerRecents(callingUid)) {
3646 // Always allow the recents component to get tasks
3647 return true;
3648 }
3649
3650 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3651 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3652 if (!allowed) {
3653 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3654 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3655 // Temporary compatibility: some existing apps on the system image may
3656 // still be requesting the old permission and not switched to the new
3657 // one; if so, we'll still allow them full access. This means we need
3658 // to see if they are holding the old permission and are a system app.
3659 try {
3660 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3661 allowed = true;
3662 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3663 + " is using old GET_TASKS but privileged; allowing");
3664 }
3665 } catch (RemoteException e) {
3666 }
3667 }
3668 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3669 + " does not hold REAL_GET_TASKS; limiting output");
3670 }
3671 return allowed;
3672 }
3673
Nicholas Sauer0259e532019-08-30 08:24:55 -07003674 boolean isCrossUserAllowed(int pid, int uid) {
3675 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3676 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3677 }
3678
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003679 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3680 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3681 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3682 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003683 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003684 "enqueueAssistContext()");
3685
3686 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08003687 final ActivityStack stack = getTopDisplayFocusedStack();
3688 ActivityRecord activity = stack != null ? stack.getTopNonFinishingActivity() : null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003689 if (activity == null) {
3690 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3691 return null;
3692 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003693 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003694 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3695 return null;
3696 }
3697 if (focused) {
3698 if (activityToken != null) {
3699 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3700 if (activity != caller) {
3701 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3702 + " is not current top " + activity);
3703 return null;
3704 }
3705 }
3706 } else {
3707 activity = ActivityRecord.forTokenLocked(activityToken);
3708 if (activity == null) {
3709 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3710 + " couldn't be found");
3711 return null;
3712 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003713 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003714 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3715 return null;
3716 }
3717 }
3718
3719 PendingAssistExtras pae;
3720 Bundle extras = new Bundle();
3721 if (args != null) {
3722 extras.putAll(args);
3723 }
3724 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003725 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003726
3727 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3728 userHandle);
3729 pae.isHome = activity.isActivityTypeHome();
3730
3731 // Increment the sessionId if necessary
3732 if (newSessionId) {
3733 mViSessionId++;
3734 }
3735 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003736 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3737 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003738 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003739 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003740 } catch (RemoteException e) {
3741 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3742 return null;
3743 }
3744 return pae;
3745 }
3746 }
3747
3748 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3749 if (result != null) {
3750 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3751 }
3752 if (pae.hint != null) {
3753 pae.extras.putBoolean(pae.hint, true);
3754 }
3755 }
3756
3757 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3758 IAssistDataReceiver receiver;
3759 synchronized (mGlobalLock) {
3760 mPendingAssistExtras.remove(pae);
3761 receiver = pae.receiver;
3762 }
3763 if (receiver != null) {
3764 // Caller wants result sent back to them.
3765 Bundle sendBundle = new Bundle();
3766 // At least return the receiver extras
3767 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3768 try {
3769 pae.receiver.onHandleAssistData(sendBundle);
3770 } catch (RemoteException e) {
3771 }
3772 }
3773 }
3774
3775 public class PendingAssistExtras extends Binder implements Runnable {
3776 public final ActivityRecord activity;
3777 public boolean isHome;
3778 public final Bundle extras;
3779 public final Intent intent;
3780 public final String hint;
3781 public final IAssistDataReceiver receiver;
3782 public final int userHandle;
3783 public boolean haveResult = false;
3784 public Bundle result = null;
3785 public AssistStructure structure = null;
3786 public AssistContent content = null;
3787 public Bundle receiverExtras;
3788
3789 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3790 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3791 int _userHandle) {
3792 activity = _activity;
3793 extras = _extras;
3794 intent = _intent;
3795 hint = _hint;
3796 receiver = _receiver;
3797 receiverExtras = _receiverExtras;
3798 userHandle = _userHandle;
3799 }
3800
3801 @Override
3802 public void run() {
3803 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3804 synchronized (this) {
3805 haveResult = true;
3806 notifyAll();
3807 }
3808 pendingAssistExtrasTimedOut(this);
3809 }
3810 }
3811
3812 @Override
3813 public boolean isAssistDataAllowedOnCurrentActivity() {
3814 int userId;
3815 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003816 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003817 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3818 return false;
3819 }
3820
Wale Ogunwale21e06482019-11-18 05:14:15 -08003821 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003822 if (activity == null) {
3823 return false;
3824 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003825 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003826 }
3827 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3828 }
3829
3830 @Override
3831 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3832 long ident = Binder.clearCallingIdentity();
3833 try {
3834 synchronized (mGlobalLock) {
3835 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003836 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003837 if (top != caller) {
3838 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3839 + " is not current top " + top);
3840 return false;
3841 }
3842 if (!top.nowVisible) {
3843 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3844 + " is not visible");
3845 return false;
3846 }
3847 }
3848 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3849 token);
3850 } finally {
3851 Binder.restoreCallingIdentity(ident);
3852 }
3853 }
3854
3855 @Override
3856 public boolean isRootVoiceInteraction(IBinder token) {
3857 synchronized (mGlobalLock) {
3858 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3859 if (r == null) {
3860 return false;
3861 }
3862 return r.rootVoiceInteraction;
3863 }
3864 }
3865
Wale Ogunwalef6733932018-06-27 05:14:34 -07003866 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3867 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3868 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3869 if (activityToCallback == null) return;
3870 activityToCallback.setVoiceSessionLocked(voiceSession);
3871
3872 // Inform the activity
3873 try {
3874 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3875 voiceInteractor);
3876 long token = Binder.clearCallingIdentity();
3877 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003878 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003879 } finally {
3880 Binder.restoreCallingIdentity(token);
3881 }
3882 // TODO: VI Should we cache the activity so that it's easier to find later
3883 // rather than scan through all the stacks and activities?
3884 } catch (RemoteException re) {
3885 activityToCallback.clearVoiceSessionLocked();
3886 // TODO: VI Should this terminate the voice session?
3887 }
3888 }
3889
3890 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3891 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3892 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3893 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3894 boolean wasRunningVoice = mRunningVoice != null;
3895 mRunningVoice = session;
3896 if (!wasRunningVoice) {
3897 mVoiceWakeLock.acquire();
3898 updateSleepIfNeededLocked();
3899 }
3900 }
3901 }
3902
3903 void finishRunningVoiceLocked() {
3904 if (mRunningVoice != null) {
3905 mRunningVoice = null;
3906 mVoiceWakeLock.release();
3907 updateSleepIfNeededLocked();
3908 }
3909 }
3910
3911 @Override
3912 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3913 synchronized (mGlobalLock) {
3914 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3915 if (keepAwake) {
3916 mVoiceWakeLock.acquire();
3917 } else {
3918 mVoiceWakeLock.release();
3919 }
3920 }
3921 }
3922 }
3923
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003924 @Override
3925 public ComponentName getActivityClassForToken(IBinder token) {
3926 synchronized (mGlobalLock) {
3927 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3928 if (r == null) {
3929 return null;
3930 }
3931 return r.intent.getComponent();
3932 }
3933 }
3934
3935 @Override
3936 public String getPackageForToken(IBinder token) {
3937 synchronized (mGlobalLock) {
3938 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3939 if (r == null) {
3940 return null;
3941 }
3942 return r.packageName;
3943 }
3944 }
3945
3946 @Override
3947 public void showLockTaskEscapeMessage(IBinder token) {
3948 synchronized (mGlobalLock) {
3949 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3950 if (r == null) {
3951 return;
3952 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003953 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003954 }
3955 }
3956
3957 @Override
3958 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003959 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003960 final long token = Binder.clearCallingIdentity();
3961 try {
3962 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003963 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003964 }
3965 } finally {
3966 Binder.restoreCallingIdentity(token);
3967 }
3968 }
3969
3970 /**
3971 * Try to place task to provided position. The final position might be different depending on
3972 * current user and stacks state. The task will be moved to target stack if it's currently in
3973 * different stack.
3974 */
3975 @Override
3976 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003977 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003978 synchronized (mGlobalLock) {
3979 long ident = Binder.clearCallingIdentity();
3980 try {
3981 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3982 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003983 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003984 if (task == null) {
3985 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3986 + taskId);
3987 }
3988
Louis Chang149d5c82019-12-30 09:47:39 +08003989 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003990
3991 if (stack == null) {
3992 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3993 + stackId);
3994 }
3995 if (!stack.isActivityTypeStandardOrUndefined()) {
3996 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3997 + " the position of task " + taskId + " in/to non-standard stack");
3998 }
3999
4000 // TODO: Have the callers of this API call a separate reparent method if that is
4001 // what they intended to do vs. having this method also do reparenting.
4002 if (task.getStack() == stack) {
4003 // Change position in current stack.
4004 stack.positionChildAt(task, position);
4005 } else {
4006 // Reparent to new stack.
4007 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
4008 !DEFER_RESUME, "positionTaskInStack");
4009 }
4010 } finally {
4011 Binder.restoreCallingIdentity(ident);
4012 }
4013 }
4014 }
4015
4016 @Override
4017 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
4018 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
4019 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09004020 + Arrays.toString(horizontalSizeConfiguration) + " "
4021 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004022 synchronized (mGlobalLock) {
4023 ActivityRecord record = ActivityRecord.isInStackLocked(token);
4024 if (record == null) {
4025 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
4026 + "found for: " + token);
4027 }
4028 record.setSizeConfigurations(horizontalSizeConfiguration,
4029 verticalSizeConfigurations, smallestSizeConfigurations);
4030 }
4031 }
4032
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004033 @Override
4034 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004035 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004036 synchronized (mGlobalLock) {
4037 mSuppressResizeConfigChanges = suppress;
4038 }
4039 }
4040
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004041 /**
4042 * Moves the top activity in the input stackId to the pinned stack.
4043 *
4044 * @param stackId Id of stack to move the top activity to pinned stack.
4045 * @param bounds Bounds to use for pinned stack.
4046 *
4047 * @return True if the top activity of the input stack was successfully moved to the pinned
4048 * stack.
4049 */
4050 @Override
4051 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004052 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004053 "moveTopActivityToPinnedStack()");
4054 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004055 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004056 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4057 + "Device doesn't support picture-in-picture mode");
4058 }
4059
4060 long ident = Binder.clearCallingIdentity();
4061 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004062 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004063 } finally {
4064 Binder.restoreCallingIdentity(ident);
4065 }
4066 }
4067 }
4068
Hongwei Wang5711b8f2019-11-15 15:44:12 -08004069 @VisibleForTesting
4070 boolean isInPictureInPictureMode(ActivityRecord r) {
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004071 return r != null
4072 && r.getRootTask() != null
4073 && r.inPinnedWindowingMode()
Wale Ogunwale0db64ac2020-04-11 10:00:42 -07004074 && r.getRootTask().isInTask(r) != null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004075 }
4076
4077 @Override
4078 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4079 final long origId = Binder.clearCallingIdentity();
4080 try {
4081 synchronized (mGlobalLock) {
4082 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4083 "enterPictureInPictureMode", token, params);
4084
4085 // If the activity is already in picture in picture mode, then just return early
4086 if (isInPictureInPictureMode(r)) {
4087 return true;
4088 }
4089
4090 // Activity supports picture-in-picture, now check that we can enter PiP at this
4091 // point, if it is
4092 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4093 false /* beforeStopping */)) {
4094 return false;
4095 }
4096
4097 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004098 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004099 if (r.getParent() == null) {
4100 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4101 return;
4102 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004103 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004104 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004105 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4106 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
Louis Chang149d5c82019-12-30 09:47:39 +08004107 mRootWindowContainer.moveActivityToPinnedStack(
Hongwei Wange8e32862020-04-08 13:23:45 -07004108 r, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004109 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004110 stack.setPictureInPictureAspectRatio(aspectRatio);
4111 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004112 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4113 r.info.applicationInfo.uid, r.shortComponentName,
4114 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004115 logPictureInPictureArgs(params);
4116 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004117 };
4118
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004119 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004120 // If the keyguard is showing or occluded, then try and dismiss it before
4121 // entering picture-in-picture (this will prompt the user to authenticate if the
4122 // device is currently locked).
4123 dismissKeyguard(token, new KeyguardDismissCallback() {
4124 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004125 public void onDismissSucceeded() {
4126 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004127 }
4128 }, null /* message */);
4129 } else {
4130 // Enter picture in picture immediately otherwise
4131 enterPipRunnable.run();
4132 }
4133 return true;
4134 }
4135 } finally {
4136 Binder.restoreCallingIdentity(origId);
4137 }
4138 }
4139
4140 @Override
4141 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4142 final long origId = Binder.clearCallingIdentity();
4143 try {
4144 synchronized (mGlobalLock) {
4145 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4146 "setPictureInPictureParams", token, params);
4147
4148 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004149 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004150 if (r.inPinnedWindowingMode()) {
4151 // If the activity is already in picture-in-picture, update the pinned stack now
4152 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4153 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004154 final ActivityStack stack = r.getRootTask();
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004155 stack.setPictureInPictureAspectRatio(
4156 r.pictureInPictureArgs.getAspectRatio());
4157 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004158 }
4159 logPictureInPictureArgs(params);
4160 }
4161 } finally {
4162 Binder.restoreCallingIdentity(origId);
4163 }
4164 }
4165
4166 @Override
4167 public int getMaxNumPictureInPictureActions(IBinder token) {
4168 // Currently, this is a static constant, but later, we may change this to be dependent on
4169 // the context of the activity
4170 return 3;
4171 }
4172
4173 private void logPictureInPictureArgs(PictureInPictureParams params) {
4174 if (params.hasSetActions()) {
4175 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4176 params.getActions().size());
4177 }
4178 if (params.hasSetAspectRatio()) {
4179 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4180 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4181 MetricsLogger.action(lm);
4182 }
4183 }
4184
4185 /**
4186 * Checks the state of the system and the activity associated with the given {@param token} to
4187 * verify that picture-in-picture is supported for that activity.
4188 *
4189 * @return the activity record for the given {@param token} if all the checks pass.
4190 */
4191 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4192 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004193 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004194 throw new IllegalStateException(caller
4195 + ": Device doesn't support picture-in-picture mode.");
4196 }
4197
4198 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4199 if (r == null) {
4200 throw new IllegalStateException(caller
4201 + ": Can't find activity for token=" + token);
4202 }
4203
4204 if (!r.supportsPictureInPicture()) {
4205 throw new IllegalStateException(caller
4206 + ": Current activity does not support picture-in-picture.");
4207 }
4208
4209 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004210 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004211 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004212 final float minAspectRatio = mContext.getResources().getFloat(
4213 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4214 final float maxAspectRatio = mContext.getResources().getFloat(
4215 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4216 throw new IllegalArgumentException(String.format(caller
4217 + ": Aspect ratio is too extreme (must be between %f and %f).",
4218 minAspectRatio, maxAspectRatio));
4219 }
4220
4221 // Truncate the number of actions if necessary
4222 params.truncateActions(getMaxNumPictureInPictureActions(token));
4223
4224 return r;
4225 }
4226
4227 @Override
4228 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004229 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004230 synchronized (mGlobalLock) {
4231 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4232 if (r == null) {
4233 throw new IllegalArgumentException("Activity does not exist; token="
4234 + activityToken);
4235 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004236 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004237 }
4238 }
4239
Evan Rosky73a7fe92019-11-18 18:28:01 -08004240 // TODO(b/149338177): remove when CTS no-longer requires it
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004241 @Override
4242 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4243 Rect tempDockedTaskInsetBounds,
4244 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004245 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004246 long ident = Binder.clearCallingIdentity();
4247 try {
4248 synchronized (mGlobalLock) {
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -07004249 final TaskDisplayArea tc = mRootWindowContainer.getDefaultTaskDisplayArea();
4250 final Task primary = tc.getRootSplitScreenPrimaryTask();
4251 final Task secondary = tc.getTask(t -> t.mCreatedByOrganizer && t.isRootTask()
Louis Changa009c762020-02-26 11:21:31 +08004252 && t.inSplitScreenSecondaryWindowingMode());
Evan Rosky73a7fe92019-11-18 18:28:01 -08004253 if (primary == null || secondary == null) {
4254 return;
4255 }
4256 final WindowContainerTransaction wct = new WindowContainerTransaction();
4257 final Rect primaryRect =
4258 tempDockedTaskInsetBounds != null ? tempDockedTaskInsetBounds
4259 : (tempDockedTaskBounds != null ? tempDockedTaskBounds
4260 : dockedBounds);
Wale Ogunwaleadf116e2020-03-27 16:36:01 -07004261 wct.setBounds(primary.mRemoteToken.toWindowContainerToken(), primaryRect);
Evan Rosky73a7fe92019-11-18 18:28:01 -08004262 Rect otherRect = tempOtherTaskInsetBounds != null ? tempOtherTaskInsetBounds
4263 : tempOtherTaskBounds;
4264 if (otherRect == null) {
4265 // Temporary estimation... again this is just for tests.
4266 otherRect = new Rect(secondary.getBounds());
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -07004267 if (tc.getBounds().width() > tc.getBounds().height()) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08004268 otherRect.left = primaryRect.right + 6;
4269 } else {
4270 otherRect.top = primaryRect.bottom + 6;
4271 }
4272 }
Wale Ogunwaleadf116e2020-03-27 16:36:01 -07004273 wct.setBounds(secondary.mRemoteToken.toWindowContainerToken(), otherRect);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004274 mWindowOrganizerController.applyTransaction(wct);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004275 }
4276 } finally {
4277 Binder.restoreCallingIdentity(ident);
4278 }
4279 }
4280
4281 @Override
4282 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004283 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004284 final long ident = Binder.clearCallingIdentity();
4285 try {
4286 synchronized (mGlobalLock) {
4287 mStackSupervisor.setSplitScreenResizing(resizing);
4288 }
4289 } finally {
4290 Binder.restoreCallingIdentity(ident);
4291 }
4292 }
4293
Evan Rosky0037e5f2019-11-05 10:26:24 -08004294 @Override
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004295 public IWindowOrganizerController getWindowOrganizerController() {
Evan Rosky0037e5f2019-11-05 10:26:24 -08004296 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004297 "getWindowOrganizerController()");
4298 return mWindowOrganizerController;
Evan Rosky0037e5f2019-11-05 10:26:24 -08004299 }
4300
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004301 /**
4302 * Check that we have the features required for VR-related API calls, and throw an exception if
4303 * not.
4304 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004305 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004306 if (!mContext.getPackageManager().hasSystemFeature(
4307 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4308 throw new UnsupportedOperationException("VR mode not supported on this device!");
4309 }
4310 }
4311
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004312 @Override
4313 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004314 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004315
4316 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4317
4318 ActivityRecord r;
4319 synchronized (mGlobalLock) {
4320 r = ActivityRecord.isInStackLocked(token);
4321 }
4322
4323 if (r == null) {
4324 throw new IllegalArgumentException();
4325 }
4326
4327 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004328 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004329 VrManagerInternal.NO_ERROR) {
4330 return err;
4331 }
4332
4333 // Clear the binder calling uid since this path may call moveToTask().
4334 final long callingId = Binder.clearCallingIdentity();
4335 try {
4336 synchronized (mGlobalLock) {
4337 r.requestedVrComponent = (enabled) ? packageName : null;
4338
4339 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004340 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004341 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004342 }
4343 return 0;
4344 }
4345 } finally {
4346 Binder.restoreCallingIdentity(callingId);
4347 }
4348 }
4349
4350 @Override
4351 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4352 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4353 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004354 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004355 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4356 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4357 }
Louis Changcdec0802019-11-11 11:45:07 +08004358 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004359 || activity.voiceSession != null) {
4360 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4361 return;
4362 }
4363 if (activity.pendingVoiceInteractionStart) {
4364 Slog.w(TAG, "Pending start of voice interaction already.");
4365 return;
4366 }
4367 activity.pendingVoiceInteractionStart = true;
4368 }
4369 LocalServices.getService(VoiceInteractionManagerInternal.class)
4370 .startLocalVoiceInteraction(callingActivity, options);
4371 }
4372
4373 @Override
4374 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4375 LocalServices.getService(VoiceInteractionManagerInternal.class)
4376 .stopLocalVoiceInteraction(callingActivity);
4377 }
4378
4379 @Override
4380 public boolean supportsLocalVoiceInteraction() {
4381 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4382 .supportsLocalVoiceInteraction();
4383 }
4384
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004385 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004387 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004388
4389 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004390 if (mWindowManager == null) {
4391 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4392 return false;
4393 }
4394
4395 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004396 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004397 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004398 }
4399
Riddle Hsua0022cd2019-09-09 21:12:41 +08004400 mH.sendMessage(PooledLambda.obtainMessage(
4401 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4402 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004403
4404 final long origId = Binder.clearCallingIdentity();
4405 try {
4406 if (values != null) {
4407 Settings.System.clearConfiguration(values);
4408 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004409 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004410 UserHandle.USER_NULL, false /* deferResume */,
4411 mTmpUpdateConfigurationResult);
4412 return mTmpUpdateConfigurationResult.changes != 0;
4413 } finally {
4414 Binder.restoreCallingIdentity(origId);
4415 }
4416 }
4417 }
4418
4419 @Override
4420 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4421 CharSequence message) {
4422 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004423 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004424 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4425 }
4426 final long callingId = Binder.clearCallingIdentity();
4427 try {
4428 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004429 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004430 }
4431 } finally {
4432 Binder.restoreCallingIdentity(callingId);
4433 }
4434 }
4435
4436 @Override
4437 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004438 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004439 "cancelTaskWindowTransition()");
4440 final long ident = Binder.clearCallingIdentity();
4441 try {
4442 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004443 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444 MATCH_TASK_IN_STACKS_ONLY);
4445 if (task == null) {
4446 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4447 return;
4448 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004449 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004450 }
4451 } finally {
4452 Binder.restoreCallingIdentity(ident);
4453 }
4454 }
4455
4456 @Override
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004457 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004458 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004459 final long ident = Binder.clearCallingIdentity();
4460 try {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004461 return getTaskSnapshot(taskId, isLowResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004462 } finally {
4463 Binder.restoreCallingIdentity(ident);
4464 }
4465 }
4466
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004467 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004468 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004469 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004470 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004471 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004472 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4473 if (task == null) {
4474 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4475 return null;
4476 }
4477 }
4478 // Don't call this while holding the lock as this operation might hit the disk.
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004479 return task.getSnapshot(isLowResolution, restoreFromDisk);
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004480 }
4481
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004482 @Override
4483 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4484 synchronized (mGlobalLock) {
4485 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4486 if (r == null) {
4487 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4488 + token);
4489 return;
4490 }
4491 final long origId = Binder.clearCallingIdentity();
4492 try {
4493 r.setDisablePreviewScreenshots(disable);
4494 } finally {
4495 Binder.restoreCallingIdentity(origId);
4496 }
4497 }
4498 }
4499
Riddle Hsu440f88b2019-11-06 22:17:35 +08004500 @Override
4501 public void invalidateHomeTaskSnapshot(IBinder token) {
4502 synchronized (mGlobalLock) {
4503 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4504 if (r == null || !r.isActivityTypeHome()) {
4505 return;
4506 }
4507 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4508 }
4509 }
4510
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004511 /** Return the user id of the last resumed activity. */
4512 @Override
4513 public @UserIdInt
4514 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004515 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004516 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4517 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004518 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004519 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004520 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004521 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004522 }
4523 }
4524
4525 @Override
4526 public void updateLockTaskFeatures(int userId, int flags) {
4527 final int callingUid = Binder.getCallingUid();
4528 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004529 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004530 "updateLockTaskFeatures()");
4531 }
4532 synchronized (mGlobalLock) {
4533 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4534 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004535 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004536 }
4537 }
4538
4539 @Override
4540 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4541 synchronized (mGlobalLock) {
4542 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4543 if (r == null) {
4544 return;
4545 }
4546 final long origId = Binder.clearCallingIdentity();
4547 try {
4548 r.setShowWhenLocked(showWhenLocked);
4549 } finally {
4550 Binder.restoreCallingIdentity(origId);
4551 }
4552 }
4553 }
4554
4555 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004556 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4557 synchronized (mGlobalLock) {
4558 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4559 if (r == null) {
4560 return;
4561 }
4562 final long origId = Binder.clearCallingIdentity();
4563 try {
4564 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4565 } finally {
4566 Binder.restoreCallingIdentity(origId);
4567 }
4568 }
4569 }
4570
4571 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004572 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4573 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.setTurnScreenOn(turnScreenOn);
4581 } finally {
4582 Binder.restoreCallingIdentity(origId);
4583 }
4584 }
4585 }
4586
4587 @Override
4588 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004589 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004590 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004591 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004592 synchronized (mGlobalLock) {
4593 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4594 if (r == null) {
4595 return;
4596 }
4597 final long origId = Binder.clearCallingIdentity();
4598 try {
4599 r.registerRemoteAnimations(definition);
4600 } finally {
4601 Binder.restoreCallingIdentity(origId);
4602 }
4603 }
4604 }
4605
4606 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004607 public void unregisterRemoteAnimations(IBinder token) {
4608 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4609 "unregisterRemoteAnimations");
4610 synchronized (mGlobalLock) {
4611 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4612 if (r == null) {
4613 return;
4614 }
4615 final long origId = Binder.clearCallingIdentity();
4616 try {
4617 r.unregisterRemoteAnimations();
4618 } finally {
4619 Binder.restoreCallingIdentity(origId);
4620 }
4621 }
4622 }
4623
4624 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004625 public void registerRemoteAnimationForNextActivityStart(String packageName,
4626 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004627 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004628 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004629 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004630 synchronized (mGlobalLock) {
4631 final long origId = Binder.clearCallingIdentity();
4632 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004633 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004634 packageName, adapter);
4635 } finally {
4636 Binder.restoreCallingIdentity(origId);
4637 }
4638 }
4639 }
4640
Evan Rosky966759f2019-01-15 10:33:58 -08004641 @Override
4642 public void registerRemoteAnimationsForDisplay(int displayId,
4643 RemoteAnimationDefinition definition) {
4644 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4645 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004646 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004647 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004648 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004649 if (display == null) {
4650 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4651 return;
4652 }
4653 final long origId = Binder.clearCallingIdentity();
4654 try {
4655 display.mDisplayContent.registerRemoteAnimations(definition);
4656 } finally {
4657 Binder.restoreCallingIdentity(origId);
4658 }
4659 }
4660 }
4661
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004662 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4663 @Override
4664 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4665 synchronized (mGlobalLock) {
4666 final long origId = Binder.clearCallingIdentity();
4667 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004668 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004669 } finally {
4670 Binder.restoreCallingIdentity(origId);
4671 }
4672 }
4673 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004674
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004675 @Override
4676 public void setVrThread(int tid) {
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 wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004681 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004682 }
4683 }
4684
4685 @Override
4686 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004687 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004688 != PERMISSION_GRANTED) {
4689 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4690 + Binder.getCallingPid()
4691 + ", uid=" + Binder.getCallingUid()
4692 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4693 Slog.w(TAG, msg);
4694 throw new SecurityException(msg);
4695 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004696 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004697 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004698 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004699 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004700 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004701 }
4702 }
4703
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004704 @Override
4705 public void stopAppSwitches() {
4706 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4707 synchronized (mGlobalLock) {
4708 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004709 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004710 mDidAppSwitch = false;
4711 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4712 }
4713 }
4714
4715 @Override
4716 public void resumeAppSwitches() {
4717 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4718 synchronized (mGlobalLock) {
4719 // Note that we don't execute any pending app switches... we will
4720 // let those wait until either the timeout, or the next start
4721 // activity request.
4722 mAppSwitchesAllowedTime = 0;
4723 }
4724 }
4725
Ricky Wai906af482019-06-03 17:25:28 +01004726 long getLastStopAppSwitchesTime() {
4727 return mLastStopAppSwitchesTime;
4728 }
4729
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004730 void onStartActivitySetDidAppSwitch() {
4731 if (mDidAppSwitch) {
4732 // This is the second allowed switch since we stopped switches, so now just generally
4733 // allow switches. Use case:
4734 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4735 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4736 // anyone to switch again).
4737 mAppSwitchesAllowedTime = 0;
4738 } else {
4739 mDidAppSwitch = true;
4740 }
4741 }
4742
4743 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004744 boolean shouldDisableNonVrUiLocked() {
4745 return mVrController.shouldDisableNonVrUiLocked();
4746 }
4747
Wale Ogunwale53783742018-09-16 10:21:51 -07004748 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004749 // 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 +00004750 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004751 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004752 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4753 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004754 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004755 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004756 }
4757 mH.post(() -> {
4758 if (!mVrController.onVrModeChanged(r)) {
4759 return;
4760 }
4761 synchronized (mGlobalLock) {
4762 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4763 mWindowManager.disableNonVrUi(disableNonVrUi);
4764 if (disableNonVrUi) {
4765 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4766 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004767 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004768 }
4769 }
4770 });
4771 }
4772
Wale Ogunwale53783742018-09-16 10:21:51 -07004773 @Override
4774 public int getPackageScreenCompatMode(String packageName) {
4775 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4776 synchronized (mGlobalLock) {
4777 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4778 }
4779 }
4780
4781 @Override
4782 public void setPackageScreenCompatMode(String packageName, int mode) {
4783 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4784 "setPackageScreenCompatMode");
4785 synchronized (mGlobalLock) {
4786 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4787 }
4788 }
4789
4790 @Override
4791 public boolean getPackageAskScreenCompat(String packageName) {
4792 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4793 synchronized (mGlobalLock) {
4794 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4795 }
4796 }
4797
4798 @Override
4799 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4800 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4801 "setPackageAskScreenCompat");
4802 synchronized (mGlobalLock) {
4803 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4804 }
4805 }
4806
Wale Ogunwale64258362018-10-16 15:13:37 -07004807 public static String relaunchReasonToString(int relaunchReason) {
4808 switch (relaunchReason) {
4809 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4810 return "window_resize";
4811 case RELAUNCH_REASON_FREE_RESIZE:
4812 return "free_resize";
4813 default:
4814 return null;
4815 }
4816 }
4817
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004818 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004819 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004820 }
4821
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004822 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004823 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004824 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4825 }
4826
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004827 boolean isKeyguardLocked() {
4828 return mKeyguardController.isKeyguardLocked();
4829 }
4830
Garfield Tan01548632018-11-27 10:15:48 -08004831 /**
4832 * Clears launch params for the given package.
4833 * @param packageNames the names of the packages of which the launch params are to be cleared
4834 */
4835 @Override
4836 public void clearLaunchParamsForPackages(List<String> packageNames) {
4837 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4838 "clearLaunchParamsForPackages");
4839 synchronized (mGlobalLock) {
4840 for (int i = 0; i < packageNames.size(); ++i) {
4841 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4842 }
4843 }
4844 }
4845
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004846 /**
4847 * Makes the display with the given id a single task instance display. I.e the display can only
4848 * contain one task.
4849 */
4850 @Override
4851 public void setDisplayToSingleTaskInstance(int displayId) {
4852 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4853 "setDisplayToSingleTaskInstance");
4854 final long origId = Binder.clearCallingIdentity();
4855 try {
Louis Chang677921f2019-12-06 16:44:24 +08004856 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004857 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004858 if (display != null) {
4859 display.setDisplayToSingleTaskInstance();
4860 }
4861 } finally {
4862 Binder.restoreCallingIdentity(origId);
4863 }
4864 }
4865
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004866 /**
4867 * Requests that an activity should enter picture-in-picture mode if possible.
4868 */
4869 @Override
4870 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4871 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4872 "requestPictureInPictureMode");
4873 final long origId = Binder.clearCallingIdentity();
4874 try {
4875 synchronized (mGlobalLock) {
4876 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4877 if (activity == null) {
4878 return;
4879 }
4880
jorgegil@google.com2e9cf022020-06-04 14:58:24 -07004881 if (isInPictureInPictureMode(activity)) {
4882 throw new IllegalStateException("Activity is already in PIP mode");
4883 }
4884
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004885 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4886 "requestPictureInPictureMode", /* beforeStopping */ false);
4887 if (!canEnterPictureInPicture) {
4888 throw new IllegalStateException(
4889 "Requested PIP on an activity that doesn't support it");
4890 }
4891
4892 try {
4893 final ClientTransaction transaction = ClientTransaction.obtain(
4894 activity.app.getThread(),
4895 activity.token);
4896 transaction.addCallback(EnterPipRequestedItem.obtain());
4897 getLifecycleManager().scheduleTransaction(transaction);
4898 } catch (Exception e) {
4899 Slog.w(TAG, "Failed to send enter pip requested item: "
4900 + activity.intent.getComponent(), e);
4901 }
4902 }
4903 } finally {
4904 Binder.restoreCallingIdentity(origId);
4905 }
4906 }
4907
Wale Ogunwale31913b52018-10-13 08:29:31 -07004908 void dumpLastANRLocked(PrintWriter pw) {
4909 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4910 if (mLastANRState == null) {
4911 pw.println(" <no ANR has occurred since boot>");
4912 } else {
4913 pw.println(mLastANRState);
4914 }
4915 }
4916
4917 void dumpLastANRTracesLocked(PrintWriter pw) {
4918 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4919
4920 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4921 if (ArrayUtils.isEmpty(files)) {
4922 pw.println(" <no ANR has occurred since boot>");
4923 return;
4924 }
4925 // Find the latest file.
4926 File latest = null;
4927 for (File f : files) {
4928 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4929 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004930 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004931 }
4932 pw.print("File: ");
4933 pw.print(latest.getName());
4934 pw.println();
4935 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4936 String line;
4937 while ((line = in.readLine()) != null) {
4938 pw.println(line);
4939 }
4940 } catch (IOException e) {
4941 pw.print("Unable to read: ");
4942 pw.print(e);
4943 pw.println();
4944 }
4945 }
4946
4947 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4948 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4949 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4950 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4951 }
4952
4953 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4954 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4955 pw.println(header);
4956
Louis Chang149d5c82019-12-30 09:47:39 +08004957 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004958 dumpPackage);
4959 boolean needSep = printedAnything;
4960
4961 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08004962 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Dianne Hackborn9106f2a2020-04-30 16:23:20 -07004963 " ResumedActivity: ", null);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004964 if (printed) {
4965 printedAnything = true;
4966 needSep = false;
4967 }
4968
4969 if (dumpPackage == null) {
4970 if (needSep) {
4971 pw.println();
4972 }
4973 printedAnything = true;
4974 mStackSupervisor.dump(pw, " ");
Winson Chung268eccb2020-03-26 13:43:44 -07004975 mTaskOrganizerController.dump(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004976 }
4977
4978 if (!printedAnything) {
4979 pw.println(" (nothing)");
4980 }
4981 }
4982
4983 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004984 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08004985 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004986 pw.println(" ");
4987 }
4988
4989 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4990 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4991 getActivityStartController().dump(pw, "", dumpPackage);
4992 }
4993
4994 /**
4995 * There are three things that cmd can be:
4996 * - a flattened component name that matches an existing activity
4997 * - the cmd arg isn't the flattened component name of an existing activity:
4998 * dump all activity whose component contains the cmd as a substring
4999 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005000 * <p>
5001 * The caller should not hold lock when calling this method because it will wait for the
5002 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005003 *
5004 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5005 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5006 */
5007 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5008 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5009 ArrayList<ActivityRecord> activities;
5010
5011 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005012 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005013 dumpFocusedStackOnly);
5014 }
5015
5016 if (activities.size() <= 0) {
5017 return false;
5018 }
5019
5020 String[] newArgs = new String[args.length - opti];
5021 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5022
Louis Changcdec0802019-11-11 11:45:07 +08005023 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005024 boolean needSep = false;
5025 for (int i = activities.size() - 1; i >= 0; i--) {
5026 ActivityRecord r = activities.get(i);
5027 if (needSep) {
5028 pw.println();
5029 }
5030 needSep = true;
5031 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005032 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005033 if (lastTask != task) {
5034 lastTask = task;
5035 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005036 pw.print(" id="); pw.print(lastTask.mTaskId);
5037 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005038 if (dumpAll) {
5039 lastTask.dump(pw, " ");
5040 }
5041 }
5042 }
5043 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5044 }
5045 return true;
5046 }
5047
5048 /**
5049 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5050 * there is a thread associated with the activity.
5051 */
5052 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5053 final ActivityRecord r, String[] args, boolean dumpAll) {
5054 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005055 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005056 synchronized (mGlobalLock) {
5057 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5058 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5059 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005060 if (r.hasProcess()) {
5061 pw.println(r.app.getPid());
5062 appThread = r.app.getThread();
5063 } else {
5064 pw.println("(not running)");
5065 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005066 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005067 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005068 }
5069 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005070 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005071 // flush anything that is already in the PrintWriter since the thread is going
5072 // to write to the file descriptor directly
5073 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005074 try (TransferPipe tp = new TransferPipe()) {
5075 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5076 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005077 } catch (IOException e) {
5078 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5079 } catch (RemoteException e) {
5080 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5081 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005082 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005083 }
5084
sanryhuang498e77e2018-12-06 14:57:01 +08005085 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5086 boolean testPssMode) {
5087 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5088 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5089 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005090 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005091 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5092 st.toString());
5093 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005094 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5095 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5096 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005097 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5098 testPssMode);
5099 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005100 }
5101
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005102 int getCurrentUserId() {
5103 return mAmInternal.getCurrentUserId();
5104 }
5105
5106 private void enforceNotIsolatedCaller(String caller) {
5107 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5108 throw new SecurityException("Isolated process not allowed to call " + caller);
5109 }
5110 }
5111
Wale Ogunwalef6733932018-06-27 05:14:34 -07005112 public Configuration getConfiguration() {
5113 Configuration ci;
5114 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005115 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005116 ci.userSetLocale = false;
5117 }
5118 return ci;
5119 }
5120
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005121 /**
5122 * Current global configuration information. Contains general settings for the entire system,
5123 * also corresponds to the merged configuration of the default display.
5124 */
5125 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005126 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005127 // while initializing process record for system, see {@link
5128 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005129 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005130 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005131 }
5132
5133 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5134 boolean initLocale) {
5135 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5136 }
5137
5138 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5139 boolean initLocale, boolean deferResume) {
5140 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5141 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5142 UserHandle.USER_NULL, deferResume);
5143 }
5144
Wale Ogunwale59507092018-10-29 09:00:30 -07005145 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005146 final long origId = Binder.clearCallingIdentity();
5147 try {
5148 synchronized (mGlobalLock) {
5149 updateConfigurationLocked(values, null, false, true, userId,
5150 false /* deferResume */);
5151 }
5152 } finally {
5153 Binder.restoreCallingIdentity(origId);
5154 }
5155 }
5156
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005157 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5158 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5159 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5160 deferResume, null /* result */);
5161 }
5162
5163 /**
5164 * Do either or both things: (1) change the current configuration, and (2)
5165 * make sure the given activity is running with the (now) current
5166 * configuration. Returns true if the activity has been left running, or
5167 * false if <var>starting</var> is being destroyed to match the new
5168 * configuration.
5169 *
5170 * @param userId is only used when persistent parameter is set to true to persist configuration
5171 * for that particular user
5172 */
5173 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5174 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5175 ActivityTaskManagerService.UpdateConfigurationResult result) {
5176 int changes = 0;
5177 boolean kept = true;
5178
Riddle Hsua0022cd2019-09-09 21:12:41 +08005179 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005180 try {
5181 if (values != null) {
5182 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5183 deferResume);
5184 }
5185
5186 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5187 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005188 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005189 }
5190
5191 if (result != null) {
5192 result.changes = changes;
5193 result.activityRelaunched = !kept;
5194 }
5195 return kept;
5196 }
5197
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005198 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005199 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005200 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005201
Louis Chang677921f2019-12-06 16:44:24 +08005202 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005203 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005204
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005205 mTempConfig.setTo(getGlobalConfiguration());
5206 final int changes = mTempConfig.updateFrom(values);
5207 if (changes == 0) {
5208 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5209 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5210 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5211 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005212 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005213 return 0;
5214 }
5215
5216 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5217 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005218 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005219 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005220 values.colorMode,
5221 values.densityDpi,
5222 values.fontScale,
5223 values.hardKeyboardHidden,
5224 values.keyboard,
5225 values.keyboardHidden,
5226 values.mcc,
5227 values.mnc,
5228 values.navigation,
5229 values.navigationHidden,
5230 values.orientation,
5231 values.screenHeightDp,
5232 values.screenLayout,
5233 values.screenWidthDp,
5234 values.smallestScreenWidthDp,
5235 values.touchscreen,
5236 values.uiMode);
5237
5238
5239 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5240 final LocaleList locales = values.getLocales();
5241 int bestLocaleIndex = 0;
5242 if (locales.size() > 1) {
5243 if (mSupportedSystemLocales == null) {
5244 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5245 }
5246 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5247 }
5248 SystemProperties.set("persist.sys.locale",
5249 locales.get(bestLocaleIndex).toLanguageTag());
5250 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005251
5252 final Message m = PooledLambda.obtainMessage(
5253 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5254 locales.get(bestLocaleIndex));
5255 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005256 }
5257
Yunfan Chen75157d72018-07-27 14:47:21 +09005258 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005259
5260 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005261 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005262
5263 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5264 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005265 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005266
5267 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005268 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005269
5270 AttributeCache ac = AttributeCache.instance();
5271 if (ac != null) {
5272 ac.updateConfiguration(mTempConfig);
5273 }
5274
5275 // Make sure all resources in our process are updated right now, so that anyone who is going
5276 // to retrieve resource values after we return will be sure to get the new ones. This is
5277 // especially important during boot, where the first config change needs to guarantee all
5278 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005279 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005280
5281 // We need another copy of global config because we're scheduling some calls instead of
5282 // running them in place. We need to be sure that object we send will be handled unchanged.
5283 final Configuration configCopy = new Configuration(mTempConfig);
5284 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005285 final Message msg = PooledLambda.obtainMessage(
5286 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5287 this, userId, configCopy);
5288 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005289 }
5290
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005291 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5292 for (int i = pidMap.size() - 1; i >= 0; i--) {
5293 final int pid = pidMap.keyAt(i);
5294 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005295 if (DEBUG_CONFIGURATION) {
5296 Slog.v(TAG_CONFIGURATION, "Update process config of "
5297 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005298 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005299 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005300 }
5301
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005302 final Message msg = PooledLambda.obtainMessage(
5303 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5304 mAmInternal, changes, initLocale);
5305 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005306
5307 // Override configuration of the default display duplicates global config, so we need to
5308 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005309 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005310 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005311
5312 return changes;
5313 }
5314
Riddle Hsua0022cd2019-09-09 21:12:41 +08005315 /** @see WindowSurfacePlacer#deferLayout */
5316 void deferWindowLayout() {
5317 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5318 // Reset the reasons at the first entrance because we only care about the changes in the
5319 // deferred scope.
5320 mLayoutReasons = 0;
5321 }
5322
5323 mWindowManager.mWindowPlacerLocked.deferLayout();
5324 }
5325
5326 /** @see WindowSurfacePlacer#continueLayout */
5327 void continueWindowLayout() {
5328 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5329 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5330 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5331 }
5332 }
5333
5334 /**
5335 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5336 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5337 * defer count is gone.
5338 */
5339 void addWindowLayoutReasons(@LayoutReason int reasons) {
5340 mLayoutReasons |= reasons;
5341 }
5342
Wale Ogunwalef6733932018-06-27 05:14:34 -07005343 private void updateEventDispatchingLocked(boolean booted) {
5344 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5345 }
5346
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005347 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5348 final ContentResolver resolver = mContext.getContentResolver();
5349 Settings.System.putConfigurationForUser(resolver, config, userId);
5350 }
5351
5352 private void sendLocaleToMountDaemonMsg(Locale l) {
5353 try {
5354 IBinder service = ServiceManager.getService("mount");
5355 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5356 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5357 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5358 } catch (RemoteException e) {
5359 Log.e(TAG, "Error storing locale for decryption UI", e);
5360 }
5361 }
5362
Alison Cichowlas3e340502018-08-07 17:15:01 -04005363 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5364 mStartActivitySources.remove(permissionToken);
5365 mExpiredStartAsCallerTokens.add(permissionToken);
5366 }
5367
5368 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5369 mExpiredStartAsCallerTokens.remove(permissionToken);
5370 }
5371
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005372 boolean isActivityStartsLoggingEnabled() {
5373 return mAmInternal.isActivityStartsLoggingEnabled();
5374 }
5375
Michal Karpinski8596ded2018-11-14 14:43:48 +00005376 boolean isBackgroundActivityStartsEnabled() {
5377 return mAmInternal.isBackgroundActivityStartsEnabled();
5378 }
5379
Wale Ogunwalef6733932018-06-27 05:14:34 -07005380 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005381 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005382 mWindowManager.enableScreenAfterBoot();
5383
5384 synchronized (mGlobalLock) {
5385 updateEventDispatchingLocked(booted);
5386 }
5387 }
5388
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005389 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5390 if (r == null || !r.hasProcess()) {
5391 return KEY_DISPATCHING_TIMEOUT_MS;
5392 }
5393 return getInputDispatchingTimeoutLocked(r.app);
5394 }
5395
5396 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005397 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005398 }
5399
Wale Ogunwalef6733932018-06-27 05:14:34 -07005400 /**
5401 * Decide based on the configuration whether we should show the ANR,
5402 * crash, etc dialogs. The idea is that if there is no affordance to
5403 * press the on-screen buttons, or the user experience would be more
5404 * greatly impacted than the crash itself, we shouldn't show the dialog.
5405 *
5406 * A thought: SystemUI might also want to get told about this, the Power
5407 * dialog / global actions also might want different behaviors.
5408 */
5409 private void updateShouldShowDialogsLocked(Configuration config) {
5410 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5411 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5412 && config.navigation == Configuration.NAVIGATION_NONAV);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005413 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5414 HIDE_ERROR_DIALOGS, 0) != 0;
Yuncheol Heo5d9b2712020-04-16 17:31:32 -07005415 mShowDialogs = inputMethodExists
5416 && ActivityTaskManager.currentUiModeSupportsErrorDialogs(mContext)
5417 && !hideDialogsSet;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005418 }
5419
5420 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5421 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5422 FONT_SCALE, 1.0f, userId);
5423
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005424 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005425 if (getGlobalConfiguration().fontScale == scaleFactor) {
5426 return;
5427 }
5428
5429 final Configuration configuration
5430 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5431 configuration.fontScale = scaleFactor;
5432 updatePersistentConfiguration(configuration, userId);
5433 }
5434 }
5435
5436 // Actually is sleeping or shutting down or whatever else in the future
5437 // is an inactive state.
5438 boolean isSleepingOrShuttingDownLocked() {
5439 return isSleepingLocked() || mShuttingDown;
5440 }
5441
5442 boolean isSleepingLocked() {
5443 return mSleeping;
5444 }
5445
Riddle Hsu16567132018-08-16 21:37:47 +08005446 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005447 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005448 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005449 if (task.isActivityTypeStandard()) {
5450 if (mCurAppTimeTracker != r.appTimeTracker) {
5451 // We are switching app tracking. Complete the current one.
5452 if (mCurAppTimeTracker != null) {
5453 mCurAppTimeTracker.stop();
5454 mH.obtainMessage(
5455 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005456 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005457 mCurAppTimeTracker = null;
5458 }
5459 if (r.appTimeTracker != null) {
5460 mCurAppTimeTracker = r.appTimeTracker;
5461 startTimeTrackingFocusedActivityLocked();
5462 }
5463 } else {
5464 startTimeTrackingFocusedActivityLocked();
5465 }
5466 } else {
5467 r.appTimeTracker = null;
5468 }
5469 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5470 // TODO: Probably not, because we don't want to resume voice on switching
5471 // back to this activity
5472 if (task.voiceInteractor != null) {
5473 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5474 } else {
5475 finishRunningVoiceLocked();
5476
5477 if (mLastResumedActivity != null) {
5478 final IVoiceInteractionSession session;
5479
Louis Changcdec0802019-11-11 11:45:07 +08005480 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005481 if (lastResumedActivityTask != null
5482 && lastResumedActivityTask.voiceSession != null) {
5483 session = lastResumedActivityTask.voiceSession;
5484 } else {
5485 session = mLastResumedActivity.voiceSession;
5486 }
5487
5488 if (session != null) {
5489 // We had been in a voice interaction session, but now focused has
5490 // move to something different. Just finish the session, we can't
5491 // return to it and retain the proper state and synchronization with
5492 // the voice interaction service.
5493 finishVoiceTask(session);
5494 }
5495 }
5496 }
5497
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005498 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5499 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005500 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005501 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5502
Wale Ogunwalef6733932018-06-27 05:14:34 -07005503 updateResumedAppTrace(r);
5504 mLastResumedActivity = r;
5505
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005506 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005507
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005508 if (prevTask == null || task != prevTask) {
5509 if (prevTask != null) {
5510 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5511 }
5512 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5513 }
5514
Wale Ogunwalef6733932018-06-27 05:14:34 -07005515 applyUpdateLockStateLocked(r);
5516 applyUpdateVrModeLocked(r);
5517
Jeff Changd136e772019-11-05 20:33:52 +08005518 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005519 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005520 r == null ? "NULL" : r.shortComponentName,
5521 reason);
5522 }
5523
5524 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5525 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005526 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005527 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005528 updateSleepIfNeededLocked();
5529 return token;
5530 }
5531 }
5532
5533 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005534 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005535 final boolean wasSleeping = mSleeping;
5536 boolean updateOomAdj = false;
5537
5538 if (!shouldSleep) {
5539 // If wasSleeping is true, we need to wake up activity manager state from when
5540 // we started sleeping. In either case, we need to apply the sleep tokens, which
5541 // will wake up stacks or put them to sleep as appropriate.
5542 if (wasSleeping) {
5543 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005544 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5545 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005546 startTimeTrackingFocusedActivityLocked();
5547 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005548 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005549 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5550 }
Louis Chang149d5c82019-12-30 09:47:39 +08005551 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005552 if (wasSleeping) {
5553 updateOomAdj = true;
5554 }
5555 } else if (!mSleeping && shouldSleep) {
5556 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005557 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5558 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005559 if (mCurAppTimeTracker != null) {
5560 mCurAppTimeTracker.stop();
5561 }
5562 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005563 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005564 mStackSupervisor.goingToSleepLocked();
5565 updateResumedAppTrace(null /* resumed */);
5566 updateOomAdj = true;
5567 }
5568 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005569 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005570 }
5571 }
5572
5573 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005574 mH.removeCallbacks(mUpdateOomAdjRunnable);
5575 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005576 }
5577
Wale Ogunwale53783742018-09-16 10:21:51 -07005578 void updateCpuStats() {
5579 mH.post(mAmInternal::updateCpuStats);
5580 }
5581
Hui Yu03d12402018-12-06 18:00:37 -08005582 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5583 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005584 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5585 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005586 mH.sendMessage(m);
5587 }
5588
Hui Yu03d12402018-12-06 18:00:37 -08005589 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005590 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005591 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005592 if (task != null) {
5593 final ActivityRecord rootActivity = task.getRootActivity();
5594 if (rootActivity != null) {
5595 taskRoot = rootActivity.mActivityComponent;
5596 }
5597 }
5598
Hui Yu03d12402018-12-06 18:00:37 -08005599 final Message m = PooledLambda.obtainMessage(
5600 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005601 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005602 mH.sendMessage(m);
5603 }
5604
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005605 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5606 String hostingType) {
5607 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005608 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5609 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005610 + activity.processName);
5611 }
5612 // Post message to start process to avoid possible deadlock of calling into AMS with the
5613 // ATMS lock held.
5614 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5615 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5616 isTop, hostingType, activity.intent.getComponent());
5617 mH.sendMessage(m);
5618 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005619 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005620 }
5621 }
5622
Wale Ogunwale53783742018-09-16 10:21:51 -07005623 void setBooting(boolean booting) {
5624 mAmInternal.setBooting(booting);
5625 }
5626
5627 boolean isBooting() {
5628 return mAmInternal.isBooting();
5629 }
5630
5631 void setBooted(boolean booted) {
5632 mAmInternal.setBooted(booted);
5633 }
5634
5635 boolean isBooted() {
5636 return mAmInternal.isBooted();
5637 }
5638
5639 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5640 mH.post(() -> {
5641 if (finishBooting) {
5642 mAmInternal.finishBooting();
5643 }
5644 if (enableScreen) {
5645 mInternal.enableScreenAfterBoot(isBooted());
5646 }
5647 });
5648 }
5649
5650 void setHeavyWeightProcess(ActivityRecord root) {
5651 mHeavyWeightProcess = root.app;
5652 final Message m = PooledLambda.obtainMessage(
5653 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005654 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005655 mH.sendMessage(m);
5656 }
5657
5658 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5659 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5660 return;
5661 }
5662
5663 mHeavyWeightProcess = null;
5664 final Message m = PooledLambda.obtainMessage(
5665 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5666 proc.mUserId);
5667 mH.sendMessage(m);
5668 }
5669
5670 private void cancelHeavyWeightProcessNotification(int userId) {
5671 final INotificationManager inm = NotificationManager.getService();
5672 if (inm == null) {
5673 return;
5674 }
5675 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005676 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005677 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5678 } catch (RuntimeException e) {
5679 Slog.w(TAG, "Error canceling notification for service", e);
5680 } catch (RemoteException e) {
5681 }
5682
5683 }
5684
5685 private void postHeavyWeightProcessNotification(
5686 WindowProcessController proc, Intent intent, int userId) {
5687 if (proc == null) {
5688 return;
5689 }
5690
5691 final INotificationManager inm = NotificationManager.getService();
5692 if (inm == null) {
5693 return;
5694 }
5695
5696 try {
5697 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5698 String text = mContext.getString(R.string.heavy_weight_notification,
5699 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5700 Notification notification =
5701 new Notification.Builder(context,
5702 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5703 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5704 .setWhen(0)
5705 .setOngoing(true)
5706 .setTicker(text)
5707 .setColor(mContext.getColor(
5708 com.android.internal.R.color.system_notification_accent_color))
5709 .setContentTitle(text)
5710 .setContentText(
5711 mContext.getText(R.string.heavy_weight_notification_detail))
5712 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5713 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5714 new UserHandle(userId)))
5715 .build();
5716 try {
5717 inm.enqueueNotificationWithTag("android", "android", null,
5718 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5719 } catch (RuntimeException e) {
5720 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5721 } catch (RemoteException e) {
5722 }
5723 } catch (PackageManager.NameNotFoundException e) {
5724 Slog.w(TAG, "Unable to create context for heavy notification", e);
5725 }
5726
5727 }
5728
Philip P. Moltmannee295092020-02-10 08:46:26 -08005729 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5730 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5731 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005732
5733 ActivityRecord activity = null;
5734 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5735 activity = ActivityRecord.isInStackLocked(token);
5736 if (activity == null) {
5737 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5738 return null;
5739 }
5740 if (activity.finishing) {
5741 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5742 return null;
5743 }
5744 }
5745
5746 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005747 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5748 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005749 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5750 if (noCreate) {
5751 return rec;
5752 }
5753 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5754 if (activity.pendingResults == null) {
5755 activity.pendingResults = new HashSet<>();
5756 }
5757 activity.pendingResults.add(rec.ref);
5758 }
5759 return rec;
5760 }
5761
Andrii Kulian52d255c2018-07-13 11:32:19 -07005762 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005763 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005764 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005765 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5766 mCurAppTimeTracker.start(resumedActivity.packageName);
5767 }
5768 }
5769
5770 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5771 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005772 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005773 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5774 }
5775 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005776 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005777 constructResumedTraceName(resumed.packageName), 0);
5778 }
5779 mTracedResumedActivity = resumed;
5780 }
5781
5782 private String constructResumedTraceName(String packageName) {
5783 return "focused app: " + packageName;
5784 }
5785
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005786 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005787 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005788 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005789 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005790 // mainStack is null during startup.
5791 if (mainStack != null) {
5792 if (changes != 0 && starting == null) {
5793 // If the configuration changed, and the caller is not already
5794 // in the process of starting an activity, then find the top
5795 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005796 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005797 }
5798
5799 if (starting != null) {
5800 kept = starting.ensureActivityConfiguration(changes,
5801 false /* preserveWindow */);
5802 // And we need to make sure at this point that all other activities
5803 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005804 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005805 !PRESERVE_WINDOWS);
5806 }
5807 }
5808
5809 return kept;
5810 }
5811
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005812 void scheduleAppGcsLocked() {
5813 mH.post(() -> mAmInternal.scheduleAppGcs());
5814 }
5815
Wale Ogunwale53783742018-09-16 10:21:51 -07005816 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5817 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5818 }
5819
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005820 /**
5821 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5822 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5823 * on demand.
5824 */
5825 IPackageManager getPackageManager() {
5826 return AppGlobals.getPackageManager();
5827 }
5828
5829 PackageManagerInternal getPackageManagerInternalLocked() {
5830 if (mPmInternal == null) {
5831 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5832 }
5833 return mPmInternal;
5834 }
5835
Darryl L Johnsona0982222020-02-18 18:21:51 -08005836 ComponentName getSysUiServiceComponentLocked() {
5837 if (mSysUiServiceComponent == null) {
5838 final PackageManagerInternal pm = getPackageManagerInternalLocked();
5839 mSysUiServiceComponent = pm.getSystemUiServiceComponent();
5840 }
5841 return mSysUiServiceComponent;
5842 }
5843
Hai Zhangf4da9be2019-05-01 13:46:06 +08005844 PermissionPolicyInternal getPermissionPolicyInternal() {
5845 if (mPermissionPolicyInternal == null) {
5846 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5847 }
5848 return mPermissionPolicyInternal;
5849 }
5850
Wale Ogunwale008163e2018-07-23 23:11:08 -07005851 AppWarnings getAppWarningsLocked() {
5852 return mAppWarnings;
5853 }
5854
Wale Ogunwale214f3482018-10-04 11:00:47 -07005855 Intent getHomeIntent() {
5856 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5857 intent.setComponent(mTopComponent);
5858 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5859 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5860 intent.addCategory(Intent.CATEGORY_HOME);
5861 }
5862 return intent;
5863 }
5864
Chilun2ef71f72018-11-16 17:57:15 +08005865 /**
5866 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5867 * activities.
5868 *
Chilun939b05c2020-02-19 14:50:59 +08005869 * @param preferredPackage Specify a preferred package name, otherwise use the package name
5870 * defined in config_secondaryHomePackage.
Chilun2ef71f72018-11-16 17:57:15 +08005871 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5872 */
5873 Intent getSecondaryHomeIntent(String preferredPackage) {
5874 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005875 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5876 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5877 if (preferredPackage == null || useSystemProvidedLauncher) {
Chilun939b05c2020-02-19 14:50:59 +08005878 // Using the package name stored in config if no preferred package name or forced.
5879 final String secondaryHomePackage = mContext.getResources().getString(
5880 com.android.internal.R.string.config_secondaryHomePackage);
5881 intent.setPackage(secondaryHomePackage);
Chilun2ef71f72018-11-16 17:57:15 +08005882 } else {
5883 intent.setPackage(preferredPackage);
5884 }
5885 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5886 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5887 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5888 }
5889 return intent;
5890 }
5891
Wale Ogunwale214f3482018-10-04 11:00:47 -07005892 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5893 if (info == null) return null;
5894 ApplicationInfo newInfo = new ApplicationInfo(info);
5895 newInfo.initForUser(userId);
5896 return newInfo;
5897 }
5898
Wale Ogunwale9c103022018-10-18 07:44:54 -07005899 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005900 if (uid == SYSTEM_UID) {
5901 // The system gets to run in any process. If there are multiple processes with the same
5902 // uid, just pick the first (this should never happen).
5903 final SparseArray<WindowProcessController> procs =
5904 mProcessNames.getMap().get(processName);
5905 if (procs == null) return null;
5906 final int procCount = procs.size();
5907 for (int i = 0; i < procCount; i++) {
5908 final int procUid = procs.keyAt(i);
5909 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5910 // Don't use an app process or different user process for system component.
5911 continue;
5912 }
5913 return procs.valueAt(i);
5914 }
5915 }
5916
5917 return mProcessNames.get(processName, uid);
5918 }
5919
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005920 WindowProcessController getProcessController(IApplicationThread thread) {
5921 if (thread == null) {
5922 return null;
5923 }
5924
5925 final IBinder threadBinder = thread.asBinder();
5926 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5927 for (int i = pmap.size()-1; i >= 0; i--) {
5928 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5929 for (int j = procs.size() - 1; j >= 0; j--) {
5930 final WindowProcessController proc = procs.valueAt(j);
5931 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5932 return proc;
5933 }
5934 }
5935 }
5936
5937 return null;
5938 }
5939
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005940 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005941 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005942 if (proc == null) return null;
5943 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5944 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005945 }
5946 return null;
5947 }
5948
Riddle Hsua0536432019-02-16 00:38:59 +08005949 int getUidState(int uid) {
5950 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005951 }
5952
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005953 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005954 // A uid is considered to be foreground if it has a visible non-toast window.
5955 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005956 }
5957
Ricky Wai96f5c352019-04-10 18:40:17 +01005958 boolean isDeviceOwner(int uid) {
5959 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005960 }
5961
Ricky Wai96f5c352019-04-10 18:40:17 +01005962 void setDeviceOwnerUid(int uid) {
5963 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005964 }
5965
Wale Ogunwale9de19442018-10-18 19:05:03 -07005966 /**
5967 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5968 * the whitelist
5969 */
5970 String getPendingTempWhitelistTagForUidLocked(int uid) {
5971 return mPendingTempWhitelist.get(uid);
5972 }
5973
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005974 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5975 if (true || Build.IS_USER) {
5976 return;
5977 }
5978
5979 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5980 StrictMode.allowThreadDiskWrites();
5981 try {
5982 File tracesDir = new File("/data/anr");
5983 File tracesFile = null;
5984 try {
5985 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5986
5987 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005988 String timeString =
5989 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5990 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005991 sb.append(": ");
5992 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5993 sb.append(" since ");
5994 sb.append(msg);
5995 FileOutputStream fos = new FileOutputStream(tracesFile);
5996 fos.write(sb.toString().getBytes());
5997 if (app == null) {
5998 fos.write("\n*** No application process!".getBytes());
5999 }
6000 fos.close();
6001 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6002 } catch (IOException e) {
6003 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6004 return;
6005 }
6006
6007 if (app != null && app.getPid() > 0) {
6008 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6009 firstPids.add(app.getPid());
6010 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6011 }
6012
6013 File lastTracesFile = null;
6014 File curTracesFile = null;
6015 for (int i=9; i>=0; i--) {
6016 String name = String.format(Locale.US, "slow%02d.txt", i);
6017 curTracesFile = new File(tracesDir, name);
6018 if (curTracesFile.exists()) {
6019 if (lastTracesFile != null) {
6020 curTracesFile.renameTo(lastTracesFile);
6021 } else {
6022 curTracesFile.delete();
6023 }
6024 }
6025 lastTracesFile = curTracesFile;
6026 }
6027 tracesFile.renameTo(curTracesFile);
6028 } finally {
6029 StrictMode.setThreadPolicy(oldPolicy);
6030 }
6031 }
6032
Michal Karpinskida34cd42019-04-02 19:46:52 +01006033 boolean isAssociatedCompanionApp(int userId, int uid) {
6034 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6035 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006036 return false;
6037 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006038 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006039 }
6040
Issei Suzuki734bc942019-06-05 13:59:52 +02006041 void notifySingleTaskDisplayEmpty(int displayId) {
6042 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6043 }
6044
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006045 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006046 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006047
6048
Wale Ogunwale98875612018-10-12 07:53:02 -07006049 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6050 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006051
Riddle Hsud93a6c42018-11-29 21:50:06 +08006052 H(Looper looper) {
6053 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006054 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006055
6056 @Override
6057 public void handleMessage(Message msg) {
6058 switch (msg.what) {
6059 case REPORT_TIME_TRACKER_MSG: {
6060 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6061 tracker.deliverResult(mContext);
6062 } break;
6063 }
6064 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006065 }
6066
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006067 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006068 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006069
6070 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006071 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006072 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006073
6074 @Override
6075 public void handleMessage(Message msg) {
6076 switch (msg.what) {
6077 case DISMISS_DIALOG_UI_MSG: {
6078 final Dialog d = (Dialog) msg.obj;
6079 d.dismiss();
6080 break;
6081 }
6082 }
6083 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006084 }
6085
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006086 final class LocalService extends ActivityTaskManagerInternal {
6087 @Override
6088 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006089 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006090 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006091 }
6092
6093 @Override
6094 public ComponentName getHomeActivityForUser(int userId) {
6095 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006096 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006097 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006098 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006099 }
6100 }
6101
6102 @Override
6103 public void onLocalVoiceInteractionStarted(IBinder activity,
6104 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6105 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006106 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006107 }
6108 }
6109
6110 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006111 public void notifySingleTaskDisplayDrawn(int displayId) {
6112 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6113 }
6114
6115 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006116 public List<IBinder> getTopVisibleActivities() {
6117 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006118 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006119 }
6120 }
6121
6122 @Override
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00006123 public boolean hasResumedActivity(int uid) {
6124 synchronized (mGlobalLock) {
6125 final ArraySet<WindowProcessController> processes = mProcessMap.getProcesses(uid);
6126 for (int i = 0, n = processes.size(); i < n; i++) {
6127 final WindowProcessController process = processes.valueAt(i);
6128 if (process.hasResumedActivity()) {
6129 return true;
6130 }
6131 }
6132 }
6133 return false;
6134 }
6135
6136 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006137 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6138 int userId, Intent[] intents, Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006139 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006140 final String[] resolvedTypes = new String[intents.length];
6141
6142 // UID of the package on user userId.
6143 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6144 // packageUid may not be initialized.
6145 int packageUid = 0;
6146 final long ident = Binder.clearCallingIdentity();
6147
6148 try {
6149 for (int i = 0; i < intents.length; i++) {
6150 resolvedTypes[i] =
6151 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6152 }
6153
6154 packageUid = AppGlobals.getPackageManager().getPackageUid(
6155 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6156 } catch (RemoteException e) {
6157 // Shouldn't happen.
6158 } finally {
6159 Binder.restoreCallingIdentity(ident);
6160 }
6161
Riddle Hsu591bf612019-02-14 17:55:31 +08006162 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006163 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006164 intents, resolvedTypes, null /* resultTo */,
6165 SafeActivityOptions.fromBundle(bOptions), userId,
6166 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6167 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006168 }
6169
6170 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006171 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006172 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6173 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6174 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006175 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006176 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006177 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006178 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006179 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6180 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006181 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006182 }
6183 }
6184
6185 @Override
6186 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006187 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6188 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6189 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6190 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006191 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006192 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006193 synchronized (mGlobalLock) {
6194 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006195 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6196 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6197 reason, validateIncomingUser, originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006198 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006199 }
6200 }
6201
6202 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006203 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006204 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6205 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006206 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006207 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006208 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006209 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006210 false /*validateIncomingUser*/);
6211 }
6212
6213 @Override
lumark588a3e82018-07-20 18:53:54 +08006214 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006215 synchronized (mGlobalLock) {
6216
6217 // We might change the visibilities here, so prepare an empty app transition which
6218 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006219 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006220 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006221 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006222 return;
6223 }
Louis Chang677921f2019-12-06 16:44:24 +08006224 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006225 final boolean wasTransitionSet =
6226 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006227 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006228 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006229 }
Louis Chang149d5c82019-12-30 09:47:39 +08006230 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006231
6232 // If there was a transition set already we don't want to interfere with it as we
6233 // might be starting it too early.
6234 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006235 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006236 }
6237 }
6238 if (callback != null) {
6239 callback.run();
6240 }
6241 }
6242
6243 @Override
6244 public void notifyKeyguardTrustedChanged() {
6245 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006246 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006247 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006248 }
6249 }
6250 }
6251
6252 /**
6253 * Called after virtual display Id is updated by
6254 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6255 * {@param vrVr2dDisplayId}.
6256 */
6257 @Override
6258 public void setVr2dDisplayId(int vr2dDisplayId) {
6259 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6260 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006261 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006262 }
6263 }
6264
6265 @Override
6266 public void setFocusedActivity(IBinder token) {
6267 synchronized (mGlobalLock) {
6268 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6269 if (r == null) {
6270 throw new IllegalArgumentException(
6271 "setFocusedActivity: No activity record matching token=" + token);
6272 }
Louis Chang19443452018-10-09 12:10:21 +08006273 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006274 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006275 }
6276 }
6277 }
6278
6279 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006280 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006281 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006282 }
6283
6284 @Override
6285 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006286 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006287 }
6288
6289 @Override
6290 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006291 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006292 }
6293
6294 @Override
6295 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6296 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6297 }
6298
6299 @Override
6300 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006301 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006302 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006303
6304 @Override
6305 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6306 synchronized (mGlobalLock) {
6307 mActiveVoiceInteractionServiceComponent = component;
6308 }
6309 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006310
6311 @Override
Galia Peycheva480275a2020-03-18 17:33:42 +01006312 public void notifyDreamStateChanged(boolean dreaming) {
6313 synchronized (mGlobalLock) {
6314 mDreaming = dreaming;
6315 }
6316 }
6317
6318 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006319 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6320 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6321 return;
6322 }
6323 synchronized (mGlobalLock) {
6324 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6325 if (types == null) {
6326 if (uid < 0) {
6327 return;
6328 }
6329 types = new ArrayMap<>();
6330 mAllowAppSwitchUids.put(userId, types);
6331 }
6332 if (uid < 0) {
6333 types.remove(type);
6334 } else {
6335 types.put(type, uid);
6336 }
6337 }
6338 }
6339
6340 @Override
6341 public void onUserStopped(int userId) {
6342 synchronized (mGlobalLock) {
6343 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6344 mAllowAppSwitchUids.remove(userId);
6345 }
6346 }
6347
6348 @Override
6349 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6350 synchronized (mGlobalLock) {
6351 return ActivityTaskManagerService.this.isGetTasksAllowed(
6352 caller, callingPid, callingUid);
6353 }
6354 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006355
Riddle Hsua0536432019-02-16 00:38:59 +08006356 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006357 @Override
6358 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006359 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006360 mProcessNames.put(proc.mName, proc.mUid, proc);
6361 }
6362 }
6363
Riddle Hsua0536432019-02-16 00:38:59 +08006364 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006365 @Override
6366 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006367 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006368 mProcessNames.remove(name, uid);
6369 }
6370 }
6371
Riddle Hsua0536432019-02-16 00:38:59 +08006372 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006373 @Override
6374 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006375 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006376 if (proc == mHomeProcess) {
6377 mHomeProcess = null;
6378 }
6379 if (proc == mPreviousProcess) {
6380 mPreviousProcess = null;
6381 }
6382 }
6383 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006384
Riddle Hsua0536432019-02-16 00:38:59 +08006385 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006386 @Override
6387 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006388 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006389 return mTopProcessState;
6390 }
6391 }
6392
Riddle Hsua0536432019-02-16 00:38:59 +08006393 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006394 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006395 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006396 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006397 return proc == mHeavyWeightProcess;
6398 }
6399 }
6400
Riddle Hsua0536432019-02-16 00:38:59 +08006401 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006402 @Override
6403 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006404 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006405 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6406 }
6407 }
6408
6409 @Override
6410 public void finishHeavyWeightApp() {
6411 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006412 if (mHeavyWeightProcess != null) {
6413 mHeavyWeightProcess.finishActivities();
6414 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006415 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6416 mHeavyWeightProcess);
6417 }
6418 }
6419
Galia Peycheva480275a2020-03-18 17:33:42 +01006420 @Override
6421 public boolean isDreaming() {
6422 synchronized (mGlobalLock) {
6423 return mDreaming;
6424 }
6425 }
6426
Riddle Hsua0536432019-02-16 00:38:59 +08006427 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006428 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006429 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006430 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006431 return isSleepingLocked();
6432 }
6433 }
6434
6435 @Override
6436 public boolean isShuttingDown() {
6437 synchronized (mGlobalLock) {
6438 return mShuttingDown;
6439 }
6440 }
6441
6442 @Override
6443 public boolean shuttingDown(boolean booted, int timeout) {
6444 synchronized (mGlobalLock) {
6445 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006446 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006447 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006448 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006449 return mStackSupervisor.shutdownLocked(timeout);
6450 }
6451 }
6452
6453 @Override
6454 public void enableScreenAfterBoot(boolean booted) {
6455 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006456 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006457 mWindowManager.enableScreenAfterBoot();
6458 updateEventDispatchingLocked(booted);
6459 }
6460 }
6461
6462 @Override
6463 public boolean showStrictModeViolationDialog() {
6464 synchronized (mGlobalLock) {
6465 return mShowDialogs && !mSleeping && !mShuttingDown;
6466 }
6467 }
6468
6469 @Override
6470 public void showSystemReadyErrorDialogsIfNeeded() {
6471 synchronized (mGlobalLock) {
6472 try {
6473 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6474 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6475 + " data partition or your device will be unstable.");
6476 mUiHandler.post(() -> {
6477 if (mShowDialogs) {
6478 AlertDialog d = new BaseErrorDialog(mUiContext);
6479 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6480 d.setCancelable(false);
6481 d.setTitle(mUiContext.getText(R.string.android_system_label));
6482 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6483 d.setButton(DialogInterface.BUTTON_POSITIVE,
6484 mUiContext.getText(R.string.ok),
6485 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6486 d.show();
6487 }
6488 });
6489 }
6490 } catch (RemoteException e) {
6491 }
6492
6493 if (!Build.isBuildConsistent()) {
6494 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6495 mUiHandler.post(() -> {
6496 if (mShowDialogs) {
6497 AlertDialog d = new BaseErrorDialog(mUiContext);
6498 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6499 d.setCancelable(false);
6500 d.setTitle(mUiContext.getText(R.string.android_system_label));
6501 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6502 d.setButton(DialogInterface.BUTTON_POSITIVE,
6503 mUiContext.getText(R.string.ok),
6504 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6505 d.show();
6506 }
6507 });
6508 }
6509 }
6510 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006511
6512 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006513 public void onProcessMapped(int pid, WindowProcessController proc) {
6514 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006515 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006516 }
6517 }
6518
6519 @Override
6520 public void onProcessUnMapped(int pid) {
6521 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006522 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006523 }
6524 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006525
6526 @Override
6527 public void onPackageDataCleared(String name) {
6528 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006529 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006530 mAppWarnings.onPackageDataCleared(name);
6531 }
6532 }
6533
6534 @Override
6535 public void onPackageUninstalled(String name) {
6536 synchronized (mGlobalLock) {
6537 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006538 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006539 }
6540 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006541
6542 @Override
6543 public void onPackageAdded(String name, boolean replacing) {
6544 synchronized (mGlobalLock) {
6545 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6546 }
6547 }
6548
6549 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006550 public void onPackageReplaced(ApplicationInfo aInfo) {
6551 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006552 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006553 }
6554 }
6555
6556 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006557 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6558 synchronized (mGlobalLock) {
6559 return compatibilityInfoForPackageLocked(ai);
6560 }
6561 }
6562
Yunfan Chen75157d72018-07-27 14:47:21 +09006563 /**
6564 * Set the corresponding display information for the process global configuration. To be
6565 * called when we need to show IME on a different display.
6566 *
6567 * @param pid The process id associated with the IME window.
6568 * @param displayId The ID of the display showing the IME.
6569 */
6570 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006571 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006572 // Don't update process-level configuration for Multi-Client IME process since other
6573 // IMEs on other displays will also receive this configuration change due to IME
6574 // services use the same application config/context.
6575 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006576
Yunfan Chen75157d72018-07-27 14:47:21 +09006577 if (pid == MY_PID || pid < 0) {
6578 if (DEBUG_CONFIGURATION) {
6579 Slog.w(TAG,
6580 "Trying to update display configuration for system/invalid process.");
6581 }
6582 return;
6583 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006584 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006585 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006586 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006587 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006588 // Call might come when display is not yet added or has been removed.
6589 if (DEBUG_CONFIGURATION) {
6590 Slog.w(TAG, "Trying to update display configuration for non-existing "
6591 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006592 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006593 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006594 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006595 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006596 if (process == null) {
6597 if (DEBUG_CONFIGURATION) {
6598 Slog.w(TAG, "Trying to update display configuration for invalid "
6599 + "process, pid=" + pid);
6600 }
6601 return;
6602 }
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006603 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006604 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006605 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006606
6607 @Override
6608 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006609 int requestCode, int resultCode, Intent data) {
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06006610 final ActivityRecord r;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006611 synchronized (mGlobalLock) {
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06006612 r = ActivityRecord.isInStackLocked(activityToken);
6613 if (r == null || r.getRootTask() == null) {
6614 return;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006615 }
6616 }
Jeff Sharkey307ea7a2020-04-13 10:24:49 -06006617
6618 // Carefully collect grants without holding lock
6619 final NeededUriGrants dataGrants = collectGrants(data, r);
6620
6621 synchronized (mGlobalLock) {
6622 r.sendResult(callingUid, resultWho, requestCode, resultCode, data, dataGrants);
6623 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006624 }
6625
6626 @Override
6627 public void clearPendingResultForActivity(IBinder activityToken,
6628 WeakReference<PendingIntentRecord> pir) {
6629 synchronized (mGlobalLock) {
6630 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6631 if (r != null && r.pendingResults != null) {
6632 r.pendingResults.remove(pir);
6633 }
6634 }
6635 }
6636
6637 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006638 public ActivityTokens getTopActivityForTask(int taskId) {
6639 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006640 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006641 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006642 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6643 + " Requested task not found");
6644 return null;
6645 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006646 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006647 if (activity == null) {
6648 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6649 + " Requested activity not found");
6650 return null;
6651 }
6652 if (!activity.attachedToProcess()) {
6653 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6654 + activity);
6655 return null;
6656 }
6657 return new ActivityTokens(activity.appToken, activity.assistToken,
6658 activity.app.getThread());
6659 }
6660 }
6661
6662 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006663 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006664 @Nullable String featureId, int callingUid, int userId, IBinder token,
6665 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6666 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006667 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006668 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6669 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006670 }
6671 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006672
6673 @Override
6674 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6675 synchronized (mGlobalLock) {
6676 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6677 if (r == null) {
6678 return null;
6679 }
6680 if (r.mServiceConnectionsHolder == null) {
6681 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6682 ActivityTaskManagerService.this, r);
6683 }
6684
6685 return r.mServiceConnectionsHolder;
6686 }
6687 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006688
6689 @Override
6690 public Intent getHomeIntent() {
6691 synchronized (mGlobalLock) {
6692 return ActivityTaskManagerService.this.getHomeIntent();
6693 }
6694 }
6695
6696 @Override
6697 public boolean startHomeActivity(int userId, String reason) {
6698 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006699 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006700 }
6701 }
6702
6703 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006704 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006705 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006706 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006707 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006708 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006709 }
Chilun8b1f1be2019-03-13 17:14:36 +08006710 }
6711
6712 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006713 public boolean startHomeOnAllDisplays(int userId, String reason) {
6714 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006715 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006716 }
6717 }
6718
Riddle Hsua0536432019-02-16 00:38:59 +08006719 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006720 @Override
6721 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006722 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006723 if (mFactoryTest == FACTORY_TEST_OFF) {
6724 return false;
6725 }
6726 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6727 && wpc.mName.equals(mTopComponent.getPackageName())) {
6728 return true;
6729 }
6730 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6731 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6732 }
6733 }
6734
6735 @Override
6736 public void updateTopComponentForFactoryTest() {
6737 synchronized (mGlobalLock) {
6738 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6739 return;
6740 }
6741 final ResolveInfo ri = mContext.getPackageManager()
6742 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6743 final CharSequence errorMsg;
6744 if (ri != null) {
6745 final ActivityInfo ai = ri.activityInfo;
6746 final ApplicationInfo app = ai.applicationInfo;
6747 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6748 mTopAction = Intent.ACTION_FACTORY_TEST;
6749 mTopData = null;
6750 mTopComponent = new ComponentName(app.packageName, ai.name);
6751 errorMsg = null;
6752 } else {
6753 errorMsg = mContext.getResources().getText(
6754 com.android.internal.R.string.factorytest_not_system);
6755 }
6756 } else {
6757 errorMsg = mContext.getResources().getText(
6758 com.android.internal.R.string.factorytest_no_action);
6759 }
6760 if (errorMsg == null) {
6761 return;
6762 }
6763
6764 mTopAction = null;
6765 mTopData = null;
6766 mTopComponent = null;
6767 mUiHandler.post(() -> {
6768 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6769 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006770 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006771 });
6772 }
6773 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006774
Riddle Hsua0536432019-02-16 00:38:59 +08006775 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006776 @Override
6777 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6778 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006779 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006780 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006781 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006782
6783 wpc.clearRecentTasks();
6784 wpc.clearActivities();
6785
6786 if (wpc.isInstrumenting()) {
6787 finishInstrumentationCallback.run();
6788 }
6789
Jorim Jaggid0752812018-10-16 16:07:20 +02006790 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006791 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006792 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006793 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006794 // If there was nothing to resume, and we are not already restarting
6795 // this process, but there is a visible activity that is hosted by the
6796 // process...then make sure all visible activities are running, taking
6797 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006798 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006799 !PRESERVE_WINDOWS);
6800 }
6801 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006802 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006803 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006804 }
6805 }
6806 }
6807
6808 @Override
6809 public void closeSystemDialogs(String reason) {
6810 enforceNotIsolatedCaller("closeSystemDialogs");
6811
6812 final int pid = Binder.getCallingPid();
6813 final int uid = Binder.getCallingUid();
6814 final long origId = Binder.clearCallingIdentity();
6815 try {
6816 synchronized (mGlobalLock) {
6817 // Only allow this from foreground processes, so that background
6818 // applications can't abuse it to prevent system UI from being shown.
6819 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006820 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006821 if (!proc.isPerceptible()) {
6822 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6823 + " from background process " + proc);
6824 return;
6825 }
6826 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006827 mWindowManager.closeSystemDialogs(reason);
6828
Galia Peycheva72d581e2020-06-12 10:06:40 +02006829 mRootWindowContainer.closeSystemDialogActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006830 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006831 // Call into AM outside the synchronized block.
6832 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006833 } finally {
6834 Binder.restoreCallingIdentity(origId);
6835 }
6836 }
6837
6838 @Override
6839 public void cleanupDisabledPackageComponents(
6840 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6841 synchronized (mGlobalLock) {
6842 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006843 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006844 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006845 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006846 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006847 }
6848
6849 // Clean-up disabled tasks
6850 getRecentTasks().cleanupDisabledPackageTasksLocked(
6851 packageName, disabledClasses, userId);
6852 }
6853 }
6854
6855 @Override
6856 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6857 int userId) {
6858 synchronized (mGlobalLock) {
6859
6860 boolean didSomething =
6861 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006862 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006863 null, doit, evenPersistent, userId);
6864 return didSomething;
6865 }
6866 }
6867
6868 @Override
6869 public void resumeTopActivities(boolean scheduleIdle) {
6870 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006871 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006872 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006873 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006874 }
6875 }
6876 }
6877
Riddle Hsua0536432019-02-16 00:38:59 +08006878 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 @Override
6880 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006881 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006882 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6883 }
6884 }
6885
Riddle Hsua0536432019-02-16 00:38:59 +08006886 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006887 @Override
6888 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006889 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006890 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6891 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6892 }
6893 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006894 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006895 } finally {
6896 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6897 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006898 }
6899 }
6900
6901 @Override
6902 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6903 try {
6904 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6905 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6906 }
6907 } catch (RemoteException ex) {
6908 throw new SecurityException("Fail to check is caller a privileged app", ex);
6909 }
6910
6911 synchronized (mGlobalLock) {
6912 final long ident = Binder.clearCallingIdentity();
6913 try {
6914 if (mAmInternal.shouldConfirmCredentials(userId)) {
6915 if (mKeyguardController.isKeyguardLocked()) {
6916 // Showing launcher to avoid user entering credential twice.
6917 startHomeActivity(currentUserId, "notifyLockedProfile");
6918 }
Louis Chang149d5c82019-12-30 09:47:39 +08006919 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006920 }
6921 } finally {
6922 Binder.restoreCallingIdentity(ident);
6923 }
6924 }
6925 }
6926
6927 @Override
6928 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6929 mAmInternal.enforceCallingPermission(
6930 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6931
6932 synchronized (mGlobalLock) {
6933 final long ident = Binder.clearCallingIdentity();
6934 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006935 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6936 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006937 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006938 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6939 UserHandle.CURRENT);
6940 } finally {
6941 Binder.restoreCallingIdentity(ident);
6942 }
6943 }
6944 }
6945
6946 @Override
6947 public void writeActivitiesToProto(ProtoOutputStream proto) {
6948 synchronized (mGlobalLock) {
6949 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006950 mRootWindowContainer.dumpDebug(
6951 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006952 }
6953 }
6954
6955 @Override
6956 public void saveANRState(String reason) {
6957 synchronized (mGlobalLock) {
6958 final StringWriter sw = new StringWriter();
6959 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6960 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6961 if (reason != null) {
6962 pw.println(" Reason: " + reason);
6963 }
6964 pw.println();
6965 getActivityStartController().dump(pw, " ", null);
6966 pw.println();
6967 pw.println("-------------------------------------------------------------------------------");
6968 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6969 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6970 "" /* header */);
6971 pw.println();
6972 pw.close();
6973
6974 mLastANRState = sw.toString();
6975 }
6976 }
6977
6978 @Override
6979 public void clearSavedANRState() {
6980 synchronized (mGlobalLock) {
6981 mLastANRState = null;
6982 }
6983 }
6984
6985 @Override
6986 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6987 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6988 synchronized (mGlobalLock) {
6989 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6990 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6991 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6992 dumpLastANRLocked(pw);
6993 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6994 dumpLastANRTracesLocked(pw);
6995 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6996 dumpActivityStarterLocked(pw, dumpPackage);
6997 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6998 dumpActivityContainersLocked(pw);
6999 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7000 if (getRecentTasks() != null) {
7001 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7002 }
7003 }
7004 }
7005 }
7006
7007 @Override
7008 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7009 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7010 int wakefulness) {
7011 synchronized (mGlobalLock) {
7012 if (mHomeProcess != null && (dumpPackage == null
7013 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7014 if (needSep) {
7015 pw.println();
7016 needSep = false;
7017 }
7018 pw.println(" mHomeProcess: " + mHomeProcess);
7019 }
7020 if (mPreviousProcess != null && (dumpPackage == null
7021 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7022 if (needSep) {
7023 pw.println();
7024 needSep = false;
7025 }
7026 pw.println(" mPreviousProcess: " + mPreviousProcess);
7027 }
7028 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7029 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7030 StringBuilder sb = new StringBuilder(128);
7031 sb.append(" mPreviousProcessVisibleTime: ");
7032 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7033 pw.println(sb);
7034 }
7035 if (mHeavyWeightProcess != null && (dumpPackage == null
7036 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7037 if (needSep) {
7038 pw.println();
7039 needSep = false;
7040 }
7041 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7042 }
7043 if (dumpPackage == null) {
7044 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007045 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007046 }
7047 if (dumpAll) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007048 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7049 if (dumpPackage == null && topFocusedStack != null) {
7050 pw.println(" mConfigWillChange: " + topFocusedStack.mConfigWillChange);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007051 }
7052 if (mCompatModePackages.getPackages().size() > 0) {
7053 boolean printed = false;
7054 for (Map.Entry<String, Integer> entry
7055 : mCompatModePackages.getPackages().entrySet()) {
7056 String pkg = entry.getKey();
7057 int mode = entry.getValue();
7058 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7059 continue;
7060 }
7061 if (!printed) {
7062 pw.println(" mScreenCompatPackages:");
7063 printed = true;
7064 }
7065 pw.println(" " + pkg + ": " + mode);
7066 }
7067 }
7068 }
7069
7070 if (dumpPackage == null) {
7071 pw.println(" mWakefulness="
7072 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007073 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007074 if (mRunningVoice != null) {
7075 pw.println(" mRunningVoice=" + mRunningVoice);
7076 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7077 }
7078 pw.println(" mSleeping=" + mSleeping);
7079 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7080 pw.println(" mVrController=" + mVrController);
7081 }
7082 if (mCurAppTimeTracker != null) {
7083 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7084 }
7085 if (mAllowAppSwitchUids.size() > 0) {
7086 boolean printed = false;
7087 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7088 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7089 for (int j = 0; j < types.size(); j++) {
7090 if (dumpPackage == null ||
7091 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7092 if (needSep) {
7093 pw.println();
7094 needSep = false;
7095 }
7096 if (!printed) {
7097 pw.println(" mAllowAppSwitchUids:");
7098 printed = true;
7099 }
7100 pw.print(" User ");
7101 pw.print(mAllowAppSwitchUids.keyAt(i));
7102 pw.print(": Type ");
7103 pw.print(types.keyAt(j));
7104 pw.print(" = ");
7105 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7106 pw.println();
7107 }
7108 }
7109 }
7110 }
7111 if (dumpPackage == null) {
7112 if (mController != null) {
7113 pw.println(" mController=" + mController
7114 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7115 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007116 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7117 pw.println(" mLaunchingActivityWakeLock="
7118 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007119 }
7120
7121 return needSep;
7122 }
7123 }
7124
7125 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007126 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7127 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007128 synchronized (mGlobalLock) {
7129 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007130 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007131 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7132 if (topFocusedStack != null) {
7133 proto.write(CONFIG_WILL_CHANGE, topFocusedStack.mConfigWillChange);
7134 }
sanryhuang498e77e2018-12-06 14:57:01 +08007135 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7136 if (mRunningVoice != null) {
7137 final long vrToken = proto.start(
7138 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7139 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7140 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007141 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007142 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7143 proto.end(vrToken);
7144 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007145 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007146 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007147 if (mController != null) {
7148 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007149 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7150 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007151 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7152 proto.end(token);
7153 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007154 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7155 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007156 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007157 }
7158
7159 if (mHomeProcess != null && (dumpPackage == null
7160 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007161 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007162 }
7163
7164 if (mPreviousProcess != null && (dumpPackage == null
7165 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007166 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007167 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7168 }
7169
7170 if (mHeavyWeightProcess != null && (dumpPackage == null
7171 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007172 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007173 }
7174
7175 for (Map.Entry<String, Integer> entry
7176 : mCompatModePackages.getPackages().entrySet()) {
7177 String pkg = entry.getKey();
7178 int mode = entry.getValue();
7179 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7180 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7181 proto.write(PACKAGE, pkg);
7182 proto.write(MODE, mode);
7183 proto.end(compatToken);
7184 }
7185 }
7186
7187 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007188 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007189 }
7190
7191 }
7192 }
7193
7194 @Override
7195 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7196 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7197 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007198 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7199 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007200 }
7201
7202 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007203 public void dumpForOom(PrintWriter pw) {
7204 synchronized (mGlobalLock) {
7205 pw.println(" mHomeProcess: " + mHomeProcess);
7206 pw.println(" mPreviousProcess: " + mPreviousProcess);
7207 if (mHeavyWeightProcess != null) {
7208 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7209 }
7210 }
7211 }
7212
7213 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007214 public boolean canGcNow() {
7215 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007216 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007217 }
7218 }
7219
Riddle Hsua0536432019-02-16 00:38:59 +08007220 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007221 @Override
7222 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007223 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007224 if (mRootWindowContainer == null) {
7225 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007226 // oomadj after AMS created.
7227 return null;
7228 }
Louis Chang149d5c82019-12-30 09:47:39 +08007229 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007230 return top != null ? top.app : null;
7231 }
7232 }
7233
Riddle Hsua0536432019-02-16 00:38:59 +08007234 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007235 @Override
7236 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007237 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007238 if (mRootWindowContainer != null) {
7239 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007240 }
7241 }
7242 }
7243
7244 @Override
7245 public void scheduleDestroyAllActivities(String reason) {
7246 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007247 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007248 }
7249 }
7250
7251 @Override
7252 public void removeUser(int userId) {
7253 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007254 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007255 }
7256 }
7257
7258 @Override
7259 public boolean switchUser(int userId, UserState userState) {
7260 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007261 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007262 }
7263 }
7264
7265 @Override
7266 public void onHandleAppCrash(WindowProcessController wpc) {
7267 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007268 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007269 }
7270 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007271
7272 @Override
7273 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7274 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007275 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007276 }
7277 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007278
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 onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007282 mActiveUids.onUidActive(uid, procState);
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 onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007288 mActiveUids.onUidInactive(uid);
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 onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007294 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007295 }
7296
Riddle Hsua0536432019-02-16 00:38:59 +08007297 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007298 @Override
7299 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007300 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007301 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007302
7303 @Override
7304 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007305 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007306 mPendingTempWhitelist.put(uid, tag);
7307 }
7308 }
7309
7310 @Override
7311 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007312 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007313 mPendingTempWhitelist.remove(uid);
7314 }
7315 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007316
7317 @Override
7318 public boolean handleAppCrashInActivityController(String processName, int pid,
7319 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7320 Runnable killCrashingAppCallback) {
7321 synchronized (mGlobalLock) {
7322 if (mController == null) {
7323 return false;
7324 }
7325
7326 try {
7327 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7328 stackTrace)) {
7329 killCrashingAppCallback.run();
7330 return true;
7331 }
7332 } catch (RemoteException e) {
7333 mController = null;
7334 Watchdog.getInstance().setActivityController(null);
7335 }
7336 return false;
7337 }
7338 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007339
7340 @Override
7341 public void removeRecentTasksByPackageName(String packageName, int userId) {
7342 synchronized (mGlobalLock) {
7343 mRecentTasks.removeTasksByPackageName(packageName, userId);
7344 }
7345 }
7346
7347 @Override
7348 public void cleanupRecentTasksForUser(int userId) {
7349 synchronized (mGlobalLock) {
7350 mRecentTasks.cleanupLocked(userId);
7351 }
7352 }
7353
7354 @Override
7355 public void loadRecentTasksForUser(int userId) {
7356 synchronized (mGlobalLock) {
7357 mRecentTasks.loadUserRecentsLocked(userId);
7358 }
7359 }
7360
7361 @Override
7362 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7363 synchronized (mGlobalLock) {
7364 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7365 }
7366 }
7367
7368 @Override
7369 public void flushRecentTasks() {
7370 mRecentTasks.flush();
7371 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007372
7373 @Override
7374 public WindowProcessController getHomeProcess() {
7375 synchronized (mGlobalLock) {
7376 return mHomeProcess;
7377 }
7378 }
7379
7380 @Override
7381 public WindowProcessController getPreviousProcess() {
7382 synchronized (mGlobalLock) {
7383 return mPreviousProcess;
7384 }
7385 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007386
7387 @Override
7388 public void clearLockedTasks(String reason) {
7389 synchronized (mGlobalLock) {
7390 getLockTaskController().clearLockedTasks(reason);
7391 }
7392 }
7393
7394 @Override
7395 public void updateUserConfiguration() {
7396 synchronized (mGlobalLock) {
7397 final Configuration configuration = new Configuration(getGlobalConfiguration());
7398 final int currentUserId = mAmInternal.getCurrentUserId();
7399 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7400 configuration, currentUserId, Settings.System.canWrite(mContext));
7401 updateConfigurationLocked(configuration, null /* starting */,
7402 false /* initLocale */, false /* persistent */, currentUserId,
7403 false /* deferResume */);
7404 }
7405 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007406
7407 @Override
7408 public boolean canShowErrorDialogs() {
7409 synchronized (mGlobalLock) {
7410 return mShowDialogs && !mSleeping && !mShuttingDown
7411 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7412 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7413 mAmInternal.getCurrentUserId())
7414 && !(UserManager.isDeviceInDemoMode(mContext)
7415 && mAmInternal.getCurrentUser().isDemo());
7416 }
7417 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007418
7419 @Override
7420 public void setProfileApp(String profileApp) {
7421 synchronized (mGlobalLock) {
7422 mProfileApp = profileApp;
7423 }
7424 }
7425
7426 @Override
7427 public void setProfileProc(WindowProcessController wpc) {
7428 synchronized (mGlobalLock) {
7429 mProfileProc = wpc;
7430 }
7431 }
7432
7433 @Override
7434 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7435 synchronized (mGlobalLock) {
7436 mProfilerInfo = profilerInfo;
7437 }
7438 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007439
7440 @Override
7441 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7442 synchronized (mGlobalLock) {
7443 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7444 }
7445 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007446
7447 @Override
Zak Cohen84b43182020-03-09 14:36:01 -07007448 public ActivityManager.TaskSnapshot getTaskSnapshotBlocking(
7449 int taskId, boolean isLowResolution) {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08007450 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution,
Zak Cohen84b43182020-03-09 14:36:01 -07007451 true /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007452 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007453
7454 @Override
7455 public boolean isUidForeground(int uid) {
7456 synchronized (mGlobalLock) {
7457 return ActivityTaskManagerService.this.isUidForeground(uid);
7458 }
7459 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007460
7461 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007462 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007463 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007464 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007465 }
7466 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007467
7468 @Override
7469 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007470 // Translate package names into UIDs
7471 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007472 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007473 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7474 if (uid >= 0) {
7475 result.add(uid);
7476 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007477 }
7478 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007479 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007480 }
7481 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007482 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007483}