blob: 80036865c3770028c59cc5435851cfa1d45716ed [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;
Evan Rosky4505b352018-09-06 11:20:40 -0700273import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700275
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700277import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700279import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700280import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700281import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700282import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700283import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800284import java.lang.annotation.ElementType;
285import java.lang.annotation.Retention;
286import java.lang.annotation.RetentionPolicy;
287import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700288import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700291import java.util.Arrays;
Jeff Sharkey8b0cff72020-03-09 15:49:01 -0600292import java.util.Collection;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700293import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400294import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700295import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700296import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700297import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700298import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000299import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700300import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301
302/**
303 * System service for managing activities and their containers (task, stacks, displays,... ).
304 *
305 * {@hide}
306 */
307public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700308 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800309 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000310 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700311 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
312 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
313 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
314 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700315 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700316
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700318 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700319 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700320 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100321 // How long we permit background activity starts after an activity in the process
322 // started or finished.
323 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700324
Wale Ogunwale98875612018-10-12 07:53:02 -0700325 /** Used to indicate that an app transition should be animated. */
326 static final boolean ANIMATE = true;
327
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700328 /** Hardware-reported OpenGLES version. */
329 final int GL_ES_VERSION;
330
Wale Ogunwale31913b52018-10-13 08:29:31 -0700331 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
332 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
333 public static final String DUMP_LASTANR_CMD = "lastanr" ;
334 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
335 public static final String DUMP_STARTER_CMD = "starter" ;
336 public static final String DUMP_CONTAINERS_CMD = "containers" ;
337 public static final String DUMP_RECENTS_CMD = "recents" ;
338 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
339
Wale Ogunwale64258362018-10-16 15:13:37 -0700340 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
341 public static final int RELAUNCH_REASON_NONE = 0;
342 /** This activity is being relaunched due to windowing mode change. */
343 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
344 /** This activity is being relaunched due to a free-resize operation. */
345 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
346
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700347 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700348
Wale Ogunwalef6733932018-06-27 05:14:34 -0700349 /**
350 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
351 * change at runtime. Use mContext for non-UI purposes.
352 */
353 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700354 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700355 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700356 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700357 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700358 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700359 private PackageManagerInternal mPmInternal;
Darryl L Johnsona0982222020-02-18 18:21:51 -0800360 /** The cached sys ui service component name from package manager. */
361 private ComponentName mSysUiServiceComponent;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800362 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800363 @VisibleForTesting
364 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700365 PowerManagerInternal mPowerManagerInternal;
366 private UsageStatsManagerInternal mUsageStatsInternal;
367
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700368 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700369 IntentFirewall mIntentFirewall;
370
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700371 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800372 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800373 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700374 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800375 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
376 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
377 *
378 * @see WindowManagerThreadPriorityBooster
379 */
380 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700381 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800382 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700383 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700384 private UserManagerService mUserManager;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800385 private AppOpsManager mAppOpsManager;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700386 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800387 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700388 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700389 /** All processes currently running that might have a window organized by name. */
390 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100391 /** All processes we currently have running mapped by pid and uid */
392 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700393 /** This is the process holding what we currently consider to be the "home" activity. */
394 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700395 /** The currently running heavy-weight process, if any. */
396 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700397 boolean mHasHeavyWeightFeature;
Sergey Nikolaienkov30c947d2020-04-15 19:55:48 +0200398 boolean mHasLeanbackFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700399 /**
400 * This is the process holding the activity the user last visited that is in a different process
401 * from the one they are currently in.
402 */
403 WindowProcessController mPreviousProcess;
404 /** The time at which the previous process was last visible. */
405 long mPreviousProcessVisibleTime;
406
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700407 /** List of intents that were used to start the most recent tasks. */
408 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700409 /** State of external calls telling us if the device is awake or asleep. */
410 private boolean mKeyguardShown = false;
411
412 // Wrapper around VoiceInteractionServiceManager
413 private AssistUtils mAssistUtils;
414
415 // VoiceInteraction session ID that changes for each new request except when
416 // being called for multi-window assist in a single session.
417 private int mViSessionId = 1000;
418
419 // How long to wait in getAssistContextExtras for the activity and foreground services
420 // to respond with the result.
421 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
422
423 // How long top wait when going through the modern assist (which doesn't need to block
424 // on getting this result before starting to launch its UI).
425 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
426
427 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
428 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
429
Alison Cichowlas3e340502018-08-07 17:15:01 -0400430 // Permission tokens are used to temporarily granted a trusted app the ability to call
431 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
432 // showing any appropriate error messages to the user.
433 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
434 10 * MINUTE_IN_MILLIS;
435
436 // How long before the service actually expires a token. This is slightly longer than
437 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
438 // expiration exception.
439 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
440 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
441
442 // How long the service will remember expired tokens, for the purpose of providing error
443 // messaging when a client uses an expired token.
444 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
445 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
446
447 // Activity tokens of system activities that are delegating their call to
448 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
449 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
450
451 // Permission tokens that have expired, but we remember for error reporting.
452 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
453
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700454 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
455
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700456 // Keeps track of the active voice interaction service component, notified from
457 // VoiceInteractionManagerService
458 ComponentName mActiveVoiceInteractionServiceComponent;
459
Michal Karpinskida34cd42019-04-02 19:46:52 +0100460 // A map userId and all its companion app uids
461 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000462
Wale Ogunwalee2172292018-10-25 10:11:10 -0700463 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700464 KeyguardController mKeyguardController;
465 private final ClientLifecycleManager mLifecycleManager;
466 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700467 /** The controller for all operations related to locktask. */
468 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700469 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700470
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700471 boolean mSuppressResizeConfigChanges;
472
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700473 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700474 new UpdateConfigurationResult();
475
476 static final class UpdateConfigurationResult {
477 // Configuration changes that were updated.
478 int changes;
479 // If the activity was relaunched to match the new configuration.
480 boolean activityRelaunched;
481
482 void reset() {
483 changes = 0;
484 activityRelaunched = false;
485 }
486 }
487
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700488 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700489 private int mConfigurationSeq;
490 // To cache the list of supported system locales
491 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700492
493 /**
494 * Temp object used when global and/or display override configuration is updated. It is also
495 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
496 * anyone...
497 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700498 private Configuration mTempConfig = new Configuration();
499
Wale Ogunwalef6733932018-06-27 05:14:34 -0700500 /** Temporary to avoid allocations. */
501 final StringBuilder mStringBuilder = new StringBuilder(256);
502
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700503 // Amount of time after a call to stopAppSwitches() during which we will
504 // prevent further untrusted switches from happening.
505 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
506
507 /**
508 * The time at which we will allow normal application switches again,
509 * after a call to {@link #stopAppSwitches()}.
510 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700511 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700512 /**
513 * This is set to true after the first switch after mAppSwitchesAllowedTime
514 * is set; any switches after that will clear the time.
515 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700516 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700517
Ricky Wai906af482019-06-03 17:25:28 +0100518 /**
519 * Last stop app switches time, apps finished before this time cannot start background activity
520 * even if they are in grace period.
521 */
522 private long mLastStopAppSwitchesTime;
523
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700524 IActivityController mController = null;
525 boolean mControllerIsAMonkey = false;
526
Wale Ogunwale214f3482018-10-04 11:00:47 -0700527 final int mFactoryTest;
528
529 /** Used to control how we initialize the service. */
530 ComponentName mTopComponent;
531 String mTopAction = Intent.ACTION_MAIN;
532 String mTopData;
533
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800534 /** Profiling app information. */
535 String mProfileApp = null;
536 WindowProcessController mProfileProc = null;
537 ProfilerInfo mProfilerInfo = null;
538
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700539 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700540 * Dump of the activity state at the time of the last ANR. Cleared after
541 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
542 */
543 String mLastANRState;
544
545 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700546 * Used to retain an update lock when the foreground activity is in
547 * immersive mode.
548 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700549 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700550
551 /**
552 * Packages that are being allowed to perform unrestricted app switches. Mapping is
553 * User -> Type -> uid.
554 */
555 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
556
557 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700558 private int mThumbnailWidth;
559 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700560
561 /**
562 * Flag that indicates if multi-window is enabled.
563 *
564 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
565 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
566 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
567 * At least one of the forms of multi-window must be enabled in order for this flag to be
568 * initialized to 'true'.
569 *
570 * @see #mSupportsSplitScreenMultiWindow
571 * @see #mSupportsFreeformWindowManagement
572 * @see #mSupportsPictureInPicture
573 * @see #mSupportsMultiDisplay
574 */
575 boolean mSupportsMultiWindow;
576 boolean mSupportsSplitScreenMultiWindow;
577 boolean mSupportsFreeformWindowManagement;
578 boolean mSupportsPictureInPicture;
579 boolean mSupportsMultiDisplay;
580 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700581 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700582
583 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
584
585 // VR Vr2d Display Id.
586 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700587
Wale Ogunwalef6733932018-06-27 05:14:34 -0700588 /**
589 * Set while we are wanting to sleep, to prevent any
590 * activities from being started/resumed.
591 *
592 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
593 *
594 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
595 * while in the sleep state until there is a pending transition out of sleep, in which case
596 * mSleeping is set to false, and remains false while awake.
597 *
598 * Whether mSleeping can quickly toggled between true/false without the device actually
599 * display changing states is undefined.
600 */
601 private boolean mSleeping = false;
602
603 /**
Galia Peycheva480275a2020-03-18 17:33:42 +0100604 * The mDreaming state is set by the {@link DreamManagerService} when it receives a request to
605 * start/stop the dream. It is set to true shortly before the {@link DreamService} is started.
606 * It is set to false after the {@link DreamService} is stopped.
607 */
608 private boolean mDreaming = false;
609
610 /**
Wale Ogunwalef6733932018-06-27 05:14:34 -0700611 * The process state used for processes that are running the top activities.
612 * This changes between TOP and TOP_SLEEPING to following mSleeping.
613 */
614 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
615
Riddle Hsua0022cd2019-09-09 21:12:41 +0800616 @Retention(RetentionPolicy.SOURCE)
617 @IntDef({
618 LAYOUT_REASON_CONFIG_CHANGED,
619 LAYOUT_REASON_VISIBILITY_CHANGED,
620 })
621 @interface LayoutReason {}
622 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
623 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
624
625 /** The reasons to perform surface placement. */
626 @LayoutReason
627 private int mLayoutReasons;
628
Wale Ogunwalef6733932018-06-27 05:14:34 -0700629 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
630 // automatically. Important for devices without direct input devices.
631 private boolean mShowDialogs = true;
632
633 /** Set if we are shutting down the system, similar to sleeping. */
634 boolean mShuttingDown = false;
635
636 /**
637 * We want to hold a wake lock while running a voice interaction session, since
638 * this may happen with the screen off and we need to keep the CPU running to
639 * be able to continue to interact with the user.
640 */
641 PowerManager.WakeLock mVoiceWakeLock;
642
643 /**
644 * Set while we are running a voice interaction. This overrides sleeping while it is active.
645 */
646 IVoiceInteractionSession mRunningVoice;
647
648 /**
649 * The last resumed activity. This is identical to the current resumed activity most
650 * of the time but could be different when we're pausing one activity before we resume
651 * another activity.
652 */
653 ActivityRecord mLastResumedActivity;
654
655 /**
656 * The activity that is currently being traced as the active resumed activity.
657 *
658 * @see #updateResumedAppTrace
659 */
660 private @Nullable ActivityRecord mTracedResumedActivity;
661
662 /** If non-null, we are tracking the time the user spends in the currently focused app. */
663 AppTimeTracker mCurAppTimeTracker;
664
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700665 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700666
Wale Ogunwale53783742018-09-16 10:21:51 -0700667 /**
668 * Packages that the user has asked to have run in screen size
669 * compatibility mode instead of filling the screen.
670 */
671 CompatModePackages mCompatModePackages;
672
Wale Ogunwalef6733932018-06-27 05:14:34 -0700673 private FontScaleSettingObserver mFontScaleSettingObserver;
674
Wale Ogunwale568f9f412020-03-21 22:27:35 -0700675 WindowOrganizerController mWindowOrganizerController;
676 TaskOrganizerController mTaskOrganizerController;
Robert Carr8a2f9132019-11-11 15:03:15 -0800677
Ricky Wai96f5c352019-04-10 18:40:17 +0100678 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000679
Wale Ogunwalef6733932018-06-27 05:14:34 -0700680 private final class FontScaleSettingObserver extends ContentObserver {
681 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
682 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
683
684 public FontScaleSettingObserver() {
685 super(mH);
686 final ContentResolver resolver = mContext.getContentResolver();
687 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
688 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
689 UserHandle.USER_ALL);
690 }
691
692 @Override
Jeff Sharkey8b0cff72020-03-09 15:49:01 -0600693 public void onChange(boolean selfChange, Collection<Uri> uris, int flags,
Riddle Hsu9c024d12020-03-09 16:10:07 +0800694 @UserIdInt int userId) {
695 for (Uri uri : uris) {
696 if (mFontScaleUri.equals(uri)) {
697 updateFontScaleIfNeeded(userId);
698 } else if (mHideErrorDialogsUri.equals(uri)) {
699 synchronized (mGlobalLock) {
700 updateShouldShowDialogsLocked(getGlobalConfiguration());
701 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700702 }
703 }
704 }
705 }
706
Riddle Hsua0536432019-02-16 00:38:59 +0800707 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
708 @Target(ElementType.METHOD)
709 @Retention(RetentionPolicy.SOURCE)
710 @interface HotPath {
711 int NONE = 0;
712 int OOM_ADJUSTMENT = 1;
713 int LRU_UPDATE = 2;
714 int PROCESS_CHANGE = 3;
715 int caller() default NONE;
716 }
717
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800718 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
719 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900720 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800721 mAmInternal.updateOomAdj();
722 }
723 };
724
Charles Chen8d98dd22018-12-26 17:36:54 +0800725 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
726 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700727 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700728 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700729 mSystemThread = ActivityThread.currentActivityThread();
730 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700731 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800732 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700733 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale568f9f412020-03-21 22:27:35 -0700734 mWindowOrganizerController = new WindowOrganizerController(this);
735 mTaskOrganizerController = mWindowOrganizerController.mTaskOrganizerController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700736 }
737
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700738 public void onSystemReady() {
739 synchronized (mGlobalLock) {
Sergey Nikolaienkov30c947d2020-04-15 19:55:48 +0200740 final PackageManager pm = mContext.getPackageManager();
741 mHasHeavyWeightFeature = pm.hasSystemFeature(FEATURE_CANT_SAVE_STATE);
742 mHasLeanbackFeature = pm.hasSystemFeature(FEATURE_LEANBACK);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700743 mAssistUtils = new AssistUtils(mContext);
744 mVrController.onSystemReady();
745 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700746 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700747 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700748 }
749
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700750 public void onInitPowerManagement() {
751 synchronized (mGlobalLock) {
752 mStackSupervisor.initPowerManagement();
753 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
754 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
755 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
756 mVoiceWakeLock.setReferenceCounted(false);
757 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700758 }
759
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700760 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700761 mFontScaleSettingObserver = new FontScaleSettingObserver();
762 }
763
Wale Ogunwale59507092018-10-29 09:00:30 -0700764 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700765 final boolean freeformWindowManagement =
766 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
767 || Settings.Global.getInt(
768 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
769
770 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
771 final boolean supportsPictureInPicture = supportsMultiWindow &&
772 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
773 final boolean supportsSplitScreenMultiWindow =
774 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
775 final boolean supportsMultiDisplay = mContext.getPackageManager()
776 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700777 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
778 final boolean forceResizable = Settings.Global.getInt(
779 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700780 final boolean sizeCompatFreeform = Settings.Global.getInt(
781 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700782
783 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900784 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700785
786 final Configuration configuration = new Configuration();
787 Settings.System.getConfiguration(resolver, configuration);
788 if (forceRtl) {
789 // This will take care of setting the correct layout direction flags
790 configuration.setLayoutDirection(configuration.locale);
791 }
792
793 synchronized (mGlobalLock) {
794 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700795 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700796 final boolean multiWindowFormEnabled = freeformWindowManagement
797 || supportsSplitScreenMultiWindow
798 || supportsPictureInPicture
799 || supportsMultiDisplay;
800 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
801 mSupportsMultiWindow = true;
802 mSupportsFreeformWindowManagement = freeformWindowManagement;
803 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
804 mSupportsPictureInPicture = supportsPictureInPicture;
805 mSupportsMultiDisplay = supportsMultiDisplay;
806 } else {
807 mSupportsMultiWindow = false;
808 mSupportsFreeformWindowManagement = false;
809 mSupportsSplitScreenMultiWindow = false;
810 mSupportsPictureInPicture = false;
811 mSupportsMultiDisplay = false;
812 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700813 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700814 // This happens before any activities are started, so we can change global configuration
815 // in-place.
816 updateConfigurationLocked(configuration, null, true);
817 final Configuration globalConfig = getGlobalConfiguration();
818 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
819
820 // Load resources only after the current configuration has been set.
821 final Resources res = mContext.getResources();
822 mThumbnailWidth = res.getDimensionPixelSize(
823 com.android.internal.R.dimen.thumbnail_width);
824 mThumbnailHeight = res.getDimensionPixelSize(
825 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700826 }
827 }
828
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800829 public WindowManagerGlobalLock getGlobalLock() {
830 return mGlobalLock;
831 }
832
Yunfan Chen585f2932019-01-29 16:04:45 +0900833 /** For test purpose only. */
834 @VisibleForTesting
835 public ActivityTaskManagerInternal getAtmInternal() {
836 return mInternal;
837 }
838
Riddle Hsud93a6c42018-11-29 21:50:06 +0800839 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
840 Looper looper) {
841 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700842 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700843 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700844 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800845 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700846 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700847 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700848 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700849
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700850 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700851 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700852 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700853 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700854 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700855 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700856 mKeyguardController = mStackSupervisor.getKeyguardController();
857 }
858
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700859 public void onActivityManagerInternalAdded() {
860 synchronized (mGlobalLock) {
861 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
862 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
863 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700864 }
865
Yunfan Chen75157d72018-07-27 14:47:21 +0900866 int increaseConfigurationSeqLocked() {
867 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
868 return mConfigurationSeq;
869 }
870
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700871 protected ActivityStackSupervisor createStackSupervisor() {
872 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
873 supervisor.initialize();
874 return supervisor;
875 }
876
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800877 protected AppWarnings createAppWarnings(
878 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
879 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
880 }
881
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700882 public void setWindowManager(WindowManagerService wm) {
883 synchronized (mGlobalLock) {
884 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800885 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800886 mTempConfig.setToDefaults();
887 mTempConfig.setLocales(LocaleList.getDefault());
888 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800889 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700890 mLockTaskController.setWindowManager(wm);
891 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800892 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700893 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700894 }
895
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700896 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
897 synchronized (mGlobalLock) {
898 mUsageStatsInternal = usageStatsManager;
899 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700900 }
901
Wale Ogunwalef6733932018-06-27 05:14:34 -0700902 UserManagerService getUserManager() {
903 if (mUserManager == null) {
904 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
905 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
906 }
907 return mUserManager;
908 }
909
Philip P. Moltmannee295092020-02-10 08:46:26 -0800910 AppOpsManager getAppOpsManager() {
911 if (mAppOpsManager == null) {
912 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Wale Ogunwalef6733932018-06-27 05:14:34 -0700913 }
Philip P. Moltmannee295092020-02-10 08:46:26 -0800914 return mAppOpsManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700915 }
916
917 boolean hasUserRestriction(String restriction, int userId) {
918 return getUserManager().hasUserRestriction(restriction, userId);
919 }
920
Michal Karpinski15486842019-04-25 17:33:42 +0100921 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
Philip P. Moltmannee295092020-02-10 08:46:26 -0800922 final int mode = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
923 callingUid, callingPackage, /* featureId */ null, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100924 if (mode == AppOpsManager.MODE_DEFAULT) {
925 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
926 == PERMISSION_GRANTED;
927 }
928 return mode == AppOpsManager.MODE_ALLOWED;
929 }
930
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700931 @VisibleForTesting
932 protected void setRecentTasks(RecentTasks recentTasks) {
933 mRecentTasks = recentTasks;
934 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700935 }
936
937 RecentTasks getRecentTasks() {
938 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700939 }
940
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700941 ClientLifecycleManager getLifecycleManager() {
942 return mLifecycleManager;
943 }
944
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700945 ActivityStartController getActivityStartController() {
946 return mActivityStartController;
947 }
948
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700949 TaskChangeNotificationController getTaskChangeNotificationController() {
950 return mTaskChangeNotificationController;
951 }
952
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700953 LockTaskController getLockTaskController() {
954 return mLockTaskController;
955 }
956
Yunfan Chen75157d72018-07-27 14:47:21 +0900957 /**
958 * Return the global configuration used by the process corresponding to the input pid. This is
959 * usually the global configuration with some overrides specific to that process.
960 */
961 Configuration getGlobalConfigurationForCallingPid() {
962 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800963 return getGlobalConfigurationForPid(pid);
964 }
965
966 /**
967 * Return the global configuration used by the process corresponding to the given pid.
968 */
969 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900970 if (pid == MY_PID || pid < 0) {
971 return getGlobalConfiguration();
972 }
973 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100974 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900975 return app != null ? app.getConfiguration() : getGlobalConfiguration();
976 }
977 }
978
979 /**
980 * Return the device configuration info used by the process corresponding to the input pid.
981 * The value is consistent with the global configuration for the process.
982 */
983 @Override
984 public ConfigurationInfo getDeviceConfigurationInfo() {
985 ConfigurationInfo config = new ConfigurationInfo();
986 synchronized (mGlobalLock) {
987 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
988 config.reqTouchScreen = globalConfig.touchscreen;
989 config.reqKeyboardType = globalConfig.keyboard;
990 config.reqNavigation = globalConfig.navigation;
991 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
992 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
993 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
994 }
995 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
996 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
997 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
998 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700999 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +09001000 }
1001 return config;
1002 }
1003
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001004 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -07001005 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001006 }
1007
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001008 public static final class Lifecycle extends SystemService {
1009 private final ActivityTaskManagerService mService;
1010
1011 public Lifecycle(Context context) {
1012 super(context);
1013 mService = new ActivityTaskManagerService(context);
1014 }
1015
1016 @Override
1017 public void onStart() {
1018 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001019 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001020 }
1021
Garfield Tan891146c2018-10-09 12:14:00 -07001022 @Override
1023 public void onUnlockUser(int userId) {
1024 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001025 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001026 }
1027 }
1028
1029 @Override
1030 public void onCleanupUser(int userId) {
1031 synchronized (mService.getGlobalLock()) {
1032 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1033 }
1034 }
1035
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001036 public ActivityTaskManagerService getService() {
1037 return mService;
1038 }
1039 }
1040
1041 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001042 public final int startActivity(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001043 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1044 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1045 Bundle bOptions) {
1046 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1047 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001048 UserHandle.getCallingUserId());
1049 }
1050
1051 @Override
1052 public final int startActivities(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001053 String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
1054 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001055 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001056 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001057 enforceNotIsolatedCaller(reason);
1058 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001059 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001060 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001061 callingFeatureId, intents, resolvedTypes, resultTo,
1062 SafeActivityOptions.fromBundle(bOptions), userId, reason,
1063 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001064 }
1065
1066 @Override
1067 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001068 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1069 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1070 Bundle bOptions, int userId) {
1071 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1072 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001073 true /*validateIncomingUser*/);
1074 }
1075
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001076 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001077 @Nullable String callingFeatureId, Intent intent, String resolvedType,
1078 IBinder resultTo, String resultWho, int requestCode, int startFlags,
1079 ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001080 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001081 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001082
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001083 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001084 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1085
1086 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001087 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001088 .setCaller(caller)
1089 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001090 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001091 .setResolvedType(resolvedType)
1092 .setResultTo(resultTo)
1093 .setResultWho(resultWho)
1094 .setRequestCode(requestCode)
1095 .setStartFlags(startFlags)
1096 .setProfilerInfo(profilerInfo)
1097 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001098 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001099 .execute();
1100
1101 }
1102
1103 @Override
1104 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1105 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001106 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1107 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001108 // Refuse possible leaked file descriptors
1109 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1110 throw new IllegalArgumentException("File descriptors passed in Intent");
1111 }
1112
1113 if (!(target instanceof PendingIntentRecord)) {
1114 throw new IllegalArgumentException("Bad PendingIntent object");
1115 }
1116
1117 PendingIntentRecord pir = (PendingIntentRecord)target;
1118
1119 synchronized (mGlobalLock) {
1120 // If this is coming from the currently resumed activity, it is
1121 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001122 final ActivityStack stack = getTopDisplayFocusedStack();
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001123 if (stack != null && stack.mResumedActivity != null
1124 && stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001125 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001126 }
1127 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001128 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001129 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001130 }
1131
1132 @Override
1133 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1134 Bundle bOptions) {
1135 // Refuse possible leaked file descriptors
1136 if (intent != null && intent.hasFileDescriptors()) {
1137 throw new IllegalArgumentException("File descriptors passed in Intent");
1138 }
1139 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1140
1141 synchronized (mGlobalLock) {
1142 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1143 if (r == null) {
1144 SafeActivityOptions.abort(options);
1145 return false;
1146 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001147 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001148 // The caller is not running... d'oh!
1149 SafeActivityOptions.abort(options);
1150 return false;
1151 }
1152 intent = new Intent(intent);
1153 // The caller is not allowed to change the data.
1154 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1155 // And we are resetting to find the next component...
1156 intent.setComponent(null);
1157
1158 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1159
1160 ActivityInfo aInfo = null;
1161 try {
1162 List<ResolveInfo> resolves =
1163 AppGlobals.getPackageManager().queryIntentActivities(
1164 intent, r.resolvedType,
1165 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1166 UserHandle.getCallingUserId()).getList();
1167
1168 // Look for the original activity in the list...
1169 final int N = resolves != null ? resolves.size() : 0;
1170 for (int i=0; i<N; i++) {
1171 ResolveInfo rInfo = resolves.get(i);
1172 if (rInfo.activityInfo.packageName.equals(r.packageName)
1173 && rInfo.activityInfo.name.equals(r.info.name)) {
1174 // We found the current one... the next matching is
1175 // after it.
1176 i++;
1177 if (i<N) {
1178 aInfo = resolves.get(i).activityInfo;
1179 }
1180 if (debug) {
1181 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1182 + "/" + r.info.name);
1183 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1184 ? "null" : aInfo.packageName + "/" + aInfo.name));
1185 }
1186 break;
1187 }
1188 }
1189 } catch (RemoteException e) {
1190 }
1191
1192 if (aInfo == null) {
1193 // Nobody who is next!
1194 SafeActivityOptions.abort(options);
1195 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1196 return false;
1197 }
1198
1199 intent.setComponent(new ComponentName(
1200 aInfo.applicationInfo.packageName, aInfo.name));
1201 intent.setFlags(intent.getFlags()&~(
1202 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1203 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1204 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1205 FLAG_ACTIVITY_NEW_TASK));
1206
1207 // Okay now we need to start the new activity, replacing the currently running activity.
1208 // This is a little tricky because we want to start the new one as if the current one is
1209 // finished, but not finish the current one first so that there is no flicker.
1210 // And thus...
1211 final boolean wasFinishing = r.finishing;
1212 r.finishing = true;
1213
1214 // Propagate reply information over to the new activity.
1215 final ActivityRecord resultTo = r.resultTo;
1216 final String resultWho = r.resultWho;
1217 final int requestCode = r.requestCode;
1218 r.resultTo = null;
1219 if (resultTo != null) {
1220 resultTo.removeResultsLocked(r, resultWho, requestCode);
1221 }
1222
1223 final long origId = Binder.clearCallingIdentity();
1224 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001225 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001226 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001227 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001228 .setResolvedType(r.resolvedType)
1229 .setActivityInfo(aInfo)
1230 .setResultTo(resultTo != null ? resultTo.appToken : null)
1231 .setResultWho(resultWho)
1232 .setRequestCode(requestCode)
1233 .setCallingPid(-1)
1234 .setCallingUid(r.launchedFromUid)
1235 .setCallingPackage(r.launchedFromPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001236 .setCallingFeatureId(r.launchedFromFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 .setRealCallingPid(-1)
1238 .setRealCallingUid(r.launchedFromUid)
1239 .setActivityOptions(options)
1240 .execute();
1241 Binder.restoreCallingIdentity(origId);
1242
1243 r.finishing = wasFinishing;
1244 if (res != ActivityManager.START_SUCCESS) {
1245 return false;
1246 }
1247 return true;
1248 }
1249 }
1250
Galia Peychevaed401cc2020-03-19 20:28:09 +01001251 private void enforceCallerIsDream(String callerPackageName) {
Galia Peycheva52e89222020-02-18 23:41:43 +01001252 final long origId = Binder.clearCallingIdentity();
Galia Peychevaed401cc2020-03-19 20:28:09 +01001253 try {
1254 if (!ActivityRecord.canLaunchDreamActivity(callerPackageName)) {
1255 throw new SecurityException("The dream activity can be started only when the device"
1256 + " is dreaming and only by the active dream package.");
1257 }
1258 } finally {
1259 Binder.restoreCallingIdentity(origId);
Galia Peycheva52e89222020-02-18 23:41:43 +01001260 }
Galia Peychevaed401cc2020-03-19 20:28:09 +01001261 }
1262
1263 @Override
1264 public boolean startDreamActivity(@NonNull Intent intent) {
1265 assertPackageMatchesCallingUid(intent.getPackage());
1266 enforceCallerIsDream(intent.getPackage());
Galia Peycheva52e89222020-02-18 23:41:43 +01001267
Galia Peycheva6861e912019-08-21 10:20:23 +02001268 final ActivityInfo a = new ActivityInfo();
1269 a.theme = com.android.internal.R.style.Theme_Dream;
1270 a.exported = true;
1271 a.name = DreamActivity.class.getName();
Galia Peycheva6861e912019-08-21 10:20:23 +02001272 a.enabled = true;
1273 a.launchMode = ActivityInfo.LAUNCH_SINGLE_INSTANCE;
Galia Peycheva6861e912019-08-21 10:20:23 +02001274 a.persistableMode = ActivityInfo.PERSIST_NEVER;
1275 a.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1276 a.colorMode = ActivityInfo.COLOR_MODE_DEFAULT;
1277 a.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1278
Galia Peycheva45f48d32020-02-20 15:39:10 +01001279 final ActivityOptions options = ActivityOptions.makeBasic();
1280 options.setLaunchActivityType(ACTIVITY_TYPE_DREAM);
1281
Galia Peychevaed401cc2020-03-19 20:28:09 +01001282 synchronized (mGlobalLock) {
1283 final WindowProcessController process = mProcessMap.getProcess(Binder.getCallingPid());
1284
1285 a.packageName = process.mInfo.packageName;
1286 a.applicationInfo = process.mInfo;
1287 a.processName = process.mInfo.processName;
1288 a.uiOptions = process.mInfo.uiOptions;
1289 a.taskAffinity = "android:" + a.packageName + "/dream";
1290
1291 final int callingUid = Binder.getCallingUid();
1292 final int callingPid = Binder.getCallingPid();
1293
1294 final long origId = Binder.clearCallingIdentity();
1295 try {
1296 getActivityStartController().obtainStarter(intent, "dream")
1297 .setCallingUid(callingUid)
1298 .setCallingPid(callingPid)
1299 .setActivityInfo(a)
1300 .setActivityOptions(options.toBundle())
1301 // To start the dream from background, we need to start it from a persistent
1302 // system process. Here we set the real calling uid to the system server uid
1303 .setRealCallingUid(Binder.getCallingUid())
1304 .setAllowBackgroundActivityStart(true)
1305 .execute();
1306 return true;
1307 } finally {
1308 Binder.restoreCallingIdentity(origId);
1309 }
Galia Peycheva6861e912019-08-21 10:20:23 +02001310 }
1311 }
1312
1313 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001314 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001315 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1316 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1317 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001318 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001319 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001320 enforceNotIsolatedCaller("startActivityAndWait");
1321 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1322 userId, "startActivityAndWait");
1323 // TODO: Switch to user app stacks here.
1324 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1325 .setCaller(caller)
1326 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001327 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001328 .setResolvedType(resolvedType)
1329 .setResultTo(resultTo)
1330 .setResultWho(resultWho)
1331 .setRequestCode(requestCode)
1332 .setStartFlags(startFlags)
1333 .setActivityOptions(bOptions)
1334 .setUserId(userId)
1335 .setProfilerInfo(profilerInfo)
1336 .setWaitResult(res)
1337 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001338 return res;
1339 }
1340
1341 @Override
1342 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001343 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1344 String resultWho, int requestCode, int startFlags, Configuration config,
1345 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001346 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001347 enforceNotIsolatedCaller("startActivityWithConfig");
1348 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1349 "startActivityWithConfig");
1350 // TODO: Switch to user app stacks here.
1351 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1352 .setCaller(caller)
1353 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001354 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001355 .setResolvedType(resolvedType)
1356 .setResultTo(resultTo)
1357 .setResultWho(resultWho)
1358 .setRequestCode(requestCode)
1359 .setStartFlags(startFlags)
1360 .setGlobalConfiguration(config)
1361 .setActivityOptions(bOptions)
1362 .setUserId(userId)
1363 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001364 }
1365
Robert Carr8a2f9132019-11-11 15:03:15 -08001366 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001367 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1368 int callingUid = Binder.getCallingUid();
1369 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1370 throw new SecurityException("Only the system process can request a permission token, "
1371 + "received request from uid: " + callingUid);
1372 }
1373 IBinder permissionToken = new Binder();
1374 synchronized (mGlobalLock) {
1375 mStartActivitySources.put(permissionToken, delegatorToken);
1376 }
1377
1378 Message expireMsg = PooledLambda.obtainMessage(
1379 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1380 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1381
1382 Message forgetMsg = PooledLambda.obtainMessage(
1383 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1384 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1385
1386 return permissionToken;
1387 }
1388
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001389 @Override
1390 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1391 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001392 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1393 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001395 // permission grants) as any app that may launch one of your own activities. So we only
1396 // allow this in two cases:
1397 // 1) The caller is an activity that is part of the core framework, and then only when it
1398 // is running as the system.
1399 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1400 // can only be requested by a system activity, which may then delegate this call to
1401 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001402 final ActivityRecord sourceRecord;
1403 final int targetUid;
1404 final String targetPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001405 final String targetFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001406 final boolean isResolver;
1407 synchronized (mGlobalLock) {
1408 if (resultTo == null) {
1409 throw new SecurityException("Must be called from an activity");
1410 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001411 final IBinder sourceToken;
1412 if (permissionToken != null) {
1413 // To even attempt to use a permissionToken, an app must also have this signature
1414 // permission.
1415 mAmInternal.enforceCallingPermission(
1416 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1417 "startActivityAsCaller");
1418 // If called with a permissionToken, we want the sourceRecord from the delegator
1419 // activity that requested this token.
1420 sourceToken = mStartActivitySources.remove(permissionToken);
1421 if (sourceToken == null) {
1422 // Invalid permissionToken, check if it recently expired.
1423 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1424 throw new SecurityException("Called with expired permission token: "
1425 + permissionToken);
1426 } else {
1427 throw new SecurityException("Called with invalid permission token: "
1428 + permissionToken);
1429 }
1430 }
1431 } else {
1432 // This method was called directly by the source.
1433 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001434 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001435
Louis Chang149d5c82019-12-30 09:47:39 +08001436 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001437 if (sourceRecord == null) {
1438 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001439 }
1440 if (sourceRecord.app == null) {
1441 throw new SecurityException("Called without a process attached to activity");
1442 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001443
1444 // Whether called directly or from a delegate, the source activity must be from the
1445 // android package.
1446 if (!sourceRecord.info.packageName.equals("android")) {
1447 throw new SecurityException("Must be called from an activity that is "
1448 + "declared in the android package");
1449 }
1450
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001451 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452 // This is still okay, as long as this activity is running under the
1453 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001454 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001456 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001457 + " must be system uid or original calling uid "
1458 + sourceRecord.launchedFromUid);
1459 }
1460 }
1461 if (ignoreTargetSecurity) {
1462 if (intent.getComponent() == null) {
1463 throw new SecurityException(
1464 "Component must be specified with ignoreTargetSecurity");
1465 }
1466 if (intent.getSelector() != null) {
1467 throw new SecurityException(
1468 "Selector not allowed with ignoreTargetSecurity");
1469 }
1470 }
1471 targetUid = sourceRecord.launchedFromUid;
1472 targetPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001473 targetFeatureId = sourceRecord.launchedFromFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001474 isResolver = sourceRecord.isResolverOrChildActivity();
1475 }
1476
1477 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001478 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001479 }
1480
1481 // TODO: Switch to user app stacks here.
1482 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001483 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001484 .setCallingUid(targetUid)
1485 .setCallingPackage(targetPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001486 .setCallingFeatureId(targetFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001487 .setResolvedType(resolvedType)
1488 .setResultTo(resultTo)
1489 .setResultWho(resultWho)
1490 .setRequestCode(requestCode)
1491 .setStartFlags(startFlags)
1492 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001493 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001494 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1495 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001496 // The target may well be in the background, which would normally prevent it
1497 // from starting an activity. Here we definitely want the start to succeed.
1498 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001499 .execute();
1500 } catch (SecurityException e) {
1501 // XXX need to figure out how to propagate to original app.
1502 // A SecurityException here is generally actually a fault of the original
1503 // calling activity (such as a fairly granting permissions), so propagate it
1504 // back to them.
1505 /*
1506 StringBuilder msg = new StringBuilder();
1507 msg.append("While launching");
1508 msg.append(intent.toString());
1509 msg.append(": ");
1510 msg.append(e.getMessage());
1511 */
1512 throw e;
1513 }
1514 }
1515
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001516 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1517 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001518 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001519 }
1520
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001521 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001522 public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1523 int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001524 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1525 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001526 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001527 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001528 if (session == null || interactor == null) {
1529 throw new NullPointerException("null session or interactor");
1530 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001531 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001532 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001533 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001534 .setCallingUid(callingUid)
1535 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001536 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001537 .setResolvedType(resolvedType)
1538 .setVoiceSession(session)
1539 .setVoiceInteractor(interactor)
1540 .setStartFlags(startFlags)
1541 .setProfilerInfo(profilerInfo)
1542 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001543 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001544 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001545 .execute();
1546 }
1547
1548 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001549 public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1550 int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1551 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001552 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001553 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1554 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001555
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001556 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001557 .setCallingUid(callingUid)
1558 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001559 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001560 .setResolvedType(resolvedType)
1561 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001562 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001563 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001564 .execute();
1565 }
1566
Riddle Hsu609a8e22019-06-27 16:46:29 -06001567 /**
1568 * Start the recents activity to perform the recents animation.
1569 *
1570 * @param intent The intent to start the recents activity.
1571 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1572 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001573 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001574 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1575 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001576 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001577 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001578 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001579 final long origId = Binder.clearCallingIdentity();
1580 try {
1581 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001582 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
Philip P. Moltmannee295092020-02-10 08:46:26 -08001583 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001584 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001585 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001586
1587 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001588 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001589 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001590 recentsFeatureId, recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001591 if (recentsAnimationRunner == null) {
1592 anim.preloadRecentsActivity();
1593 } else {
1594 anim.startRecentsActivity(recentsAnimationRunner);
1595 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001596 }
1597 } finally {
1598 Binder.restoreCallingIdentity(origId);
1599 }
1600 }
1601
1602 @Override
1603 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001604 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001605 "startActivityFromRecents()");
1606
1607 final int callingPid = Binder.getCallingPid();
1608 final int callingUid = Binder.getCallingUid();
1609 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1610 final long origId = Binder.clearCallingIdentity();
1611 try {
1612 synchronized (mGlobalLock) {
1613 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1614 safeOptions);
1615 }
1616 } finally {
1617 Binder.restoreCallingIdentity(origId);
1618 }
1619 }
1620
1621 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001622 * Public API to check if the client is allowed to start an activity on specified display.
1623 *
1624 * If the target display is private or virtual, some restrictions will apply.
1625 *
1626 * @param displayId Target display id.
1627 * @param intent Intent used to launch the activity.
1628 * @param resolvedType The MIME type of the intent.
1629 * @param userId The id of the user for whom the call is made.
1630 * @return {@code true} if a call to start an activity on the target display should succeed and
1631 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1632 */
1633 @Override
1634 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1635 String resolvedType, int userId) {
1636 final int callingUid = Binder.getCallingUid();
1637 final int callingPid = Binder.getCallingPid();
1638 final long origId = Binder.clearCallingIdentity();
1639
1640 try {
1641 // Collect information about the target of the Intent.
1642 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1643 0 /* startFlags */, null /* profilerInfo */, userId,
1644 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1645 UserHandle.USER_NULL));
1646 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1647
1648 synchronized (mGlobalLock) {
1649 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1650 aInfo);
1651 }
1652 } finally {
1653 Binder.restoreCallingIdentity(origId);
1654 }
1655 }
1656
1657 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001658 * This is the internal entry point for handling Activity.finish().
1659 *
1660 * @param token The Binder token referencing the Activity we want to finish.
1661 * @param resultCode Result code, if any, from this Activity.
1662 * @param resultData Result data (Intent), if any, from this Activity.
1663 * @param finishTask Whether to finish the task associated with this Activity.
1664 *
1665 * @return Returns true if the activity successfully finished, or false if it is still running.
1666 */
1667 @Override
1668 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1669 int finishTask) {
1670 // Refuse possible leaked file descriptors
1671 if (resultData != null && resultData.hasFileDescriptors()) {
1672 throw new IllegalArgumentException("File descriptors passed in Intent");
1673 }
1674
1675 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001676 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001677 if (r == null) {
1678 return true;
1679 }
1680 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001681 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001682 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001683 if (rootR == null) {
1684 Slog.w(TAG, "Finishing task with all activities already finished");
1685 }
1686 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1687 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001688 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001689 return false;
1690 }
1691
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001692 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1693 // We should consolidate.
1694 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001695 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001696 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001697 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001698 if (next != null) {
1699 // ask watcher if this is allowed
1700 boolean resumeOK = true;
1701 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001702 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001703 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001704 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001705 Watchdog.getInstance().setActivityController(null);
1706 }
1707
1708 if (!resumeOK) {
1709 Slog.i(TAG, "Not finishing activity because controller resumed");
1710 return false;
1711 }
1712 }
1713 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001714
1715 // note down that the process has finished an activity and is in background activity
1716 // starts grace period
1717 if (r.app != null) {
1718 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1719 }
1720
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001721 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001722 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001723 try {
1724 boolean res;
1725 final boolean finishWithRootActivity =
1726 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1727 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1728 || (finishWithRootActivity && r == rootR)) {
1729 // If requested, remove the task that is associated to this activity only if it
1730 // was the root activity in the task. The result code and data is ignored
1731 // because we don't support returning them across task boundaries. Also, to
1732 // keep backwards compatibility we remove the task from recents when finishing
1733 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001734 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001735 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001736 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001737 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001738 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001739 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001740 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001741 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001742 if (!res) {
1743 Slog.i(TAG, "Failed to finish by app-request");
1744 }
1745 }
1746 return res;
1747 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001748 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001749 Binder.restoreCallingIdentity(origId);
1750 }
1751 }
1752 }
1753
1754 @Override
1755 public boolean finishActivityAffinity(IBinder token) {
1756 synchronized (mGlobalLock) {
1757 final long origId = Binder.clearCallingIdentity();
1758 try {
1759 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1760 if (r == null) {
1761 return false;
1762 }
1763
1764 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1765 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001766 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001767 return false;
1768 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001769
1770 final PooledFunction p = PooledLambda.obtainFunction(
1771 ActivityRecord::finishIfSameAffinity, r,
1772 PooledLambda.__(ActivityRecord.class));
1773 r.getTask().forAllActivities(
1774 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1775 p.recycle();
1776
Andrii Kuliande93eff2019-07-12 12:21:27 -07001777 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001778 } finally {
1779 Binder.restoreCallingIdentity(origId);
1780 }
1781 }
1782 }
1783
1784 @Override
1785 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1786 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001787 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001788 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001789 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001790 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1791 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001792 return;
1793 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001794 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1795 false /* processPausingActivities */, config);
1796 if (stopProfiling && r.hasProcess()) {
1797 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001798 }
1799 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001800 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001801 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001802 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001803 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001804 }
1805
1806 @Override
1807 public final void activityResumed(IBinder token) {
1808 final long origId = Binder.clearCallingIdentity();
1809 synchronized (mGlobalLock) {
1810 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001811 }
1812 Binder.restoreCallingIdentity(origId);
1813 }
1814
1815 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001816 public final void activityTopResumedStateLost() {
1817 final long origId = Binder.clearCallingIdentity();
1818 synchronized (mGlobalLock) {
1819 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1820 }
1821 Binder.restoreCallingIdentity(origId);
1822 }
1823
1824 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001825 public final void activityPaused(IBinder token) {
1826 final long origId = Binder.clearCallingIdentity();
1827 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001828 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001829 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1830 if (r != null) {
1831 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001832 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001833 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001834 }
1835 Binder.restoreCallingIdentity(origId);
1836 }
1837
1838 @Override
1839 public final void activityStopped(IBinder token, Bundle icicle,
1840 PersistableBundle persistentState, CharSequence description) {
1841 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1842
1843 // Refuse possible leaked file descriptors
1844 if (icicle != null && icicle.hasFileDescriptors()) {
1845 throw new IllegalArgumentException("File descriptors passed in Bundle");
1846 }
1847
1848 final long origId = Binder.clearCallingIdentity();
1849
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001850 String restartingName = null;
1851 int restartingUid = 0;
1852 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001853 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001854 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001855 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001856 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001857 if (r.attachedToProcess()
1858 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1859 // The activity was requested to restart from
1860 // {@link #restartActivityProcessIfVisible}.
1861 restartingName = r.app.mName;
1862 restartingUid = r.app.mUid;
1863 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001864 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001865 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001866 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001867 }
1868
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001869 if (restartingName != null) {
1870 // In order to let the foreground activity can be restarted with its saved state from
1871 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1872 // until the activity reports stopped with the state. And the activity record will be
1873 // kept because the record state is restarting, then the activity will be restarted
1874 // immediately if it is still the top one.
1875 mStackSupervisor.removeRestartTimeouts(r);
1876 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1877 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001878 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001879
1880 Binder.restoreCallingIdentity(origId);
1881 }
1882
1883 @Override
1884 public final void activityDestroyed(IBinder token) {
1885 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1886 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001887 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001888 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001889 try {
1890 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1891 if (activity != null) {
1892 activity.destroyed("activityDestroyed");
1893 }
1894 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001895 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001896 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001897 }
1898 }
1899 }
1900
1901 @Override
1902 public final void activityRelaunched(IBinder token) {
1903 final long origId = Binder.clearCallingIdentity();
1904 synchronized (mGlobalLock) {
1905 mStackSupervisor.activityRelaunchedLocked(token);
1906 }
1907 Binder.restoreCallingIdentity(origId);
1908 }
1909
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001910 @Override
1911 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1912 synchronized (mGlobalLock) {
1913 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1914 if (r == null) {
1915 return;
1916 }
1917 final long origId = Binder.clearCallingIdentity();
1918 try {
1919 r.setRequestedOrientation(requestedOrientation);
1920 } finally {
1921 Binder.restoreCallingIdentity(origId);
1922 }
1923 }
1924 }
1925
1926 @Override
1927 public int getRequestedOrientation(IBinder token) {
1928 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001929 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1930 return (r != null)
1931 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001932 }
1933 }
1934
1935 @Override
1936 public void setImmersive(IBinder token, boolean immersive) {
1937 synchronized (mGlobalLock) {
1938 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1939 if (r == null) {
1940 throw new IllegalArgumentException();
1941 }
1942 r.immersive = immersive;
1943
1944 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001945 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001946 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001947 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001948 }
1949 }
1950 }
1951
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001952 void applyUpdateLockStateLocked(ActivityRecord r) {
1953 // Modifications to the UpdateLock state are done on our handler, outside
1954 // the activity manager's locks. The new state is determined based on the
1955 // state *now* of the relevant activity record. The object is passed to
1956 // the handler solely for logging detail, not to be consulted/modified.
1957 final boolean nextState = r != null && r.immersive;
1958 mH.post(() -> {
1959 if (mUpdateLock.isHeld() != nextState) {
1960 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1961 "Applying new update lock state '" + nextState + "' for " + r);
1962 if (nextState) {
1963 mUpdateLock.acquire();
1964 } else {
1965 mUpdateLock.release();
1966 }
1967 }
1968 });
1969 }
1970
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001971 @Override
1972 public boolean isImmersive(IBinder token) {
1973 synchronized (mGlobalLock) {
1974 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1975 if (r == null) {
1976 throw new IllegalArgumentException();
1977 }
1978 return r.immersive;
1979 }
1980 }
1981
1982 @Override
1983 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001984 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001985 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001986 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
1987 if (topFocusedStack == null) {
1988 return false;
1989 }
1990
1991 final ActivityRecord r = topFocusedStack.topRunningActivity();
1992 return r != null && r.immersive;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001993 }
1994 }
1995
1996 @Override
1997 public void overridePendingTransition(IBinder token, String packageName,
1998 int enterAnim, int exitAnim) {
1999 synchronized (mGlobalLock) {
2000 ActivityRecord self = ActivityRecord.isInStackLocked(token);
2001 if (self == null) {
2002 return;
2003 }
2004
2005 final long origId = Binder.clearCallingIdentity();
2006
2007 if (self.isState(
2008 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08002009 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08002010 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002011 }
2012
2013 Binder.restoreCallingIdentity(origId);
2014 }
2015 }
2016
2017 @Override
2018 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002019 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002020 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002021 final ActivityStack stack = getTopDisplayFocusedStack();
2022 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002023 if (r == null) {
2024 return ActivityManager.COMPAT_MODE_UNKNOWN;
2025 }
Wale Ogunwale53783742018-09-16 10:21:51 -07002026 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002027 }
2028 }
2029
2030 @Override
2031 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002032 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002033 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002034 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002035 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002036 final ActivityStack stack = getTopDisplayFocusedStack();
2037 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002038 if (r == null) {
2039 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
2040 return;
2041 }
2042 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07002043 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002044 }
2045 }
2046
2047 @Override
2048 public int getLaunchedFromUid(IBinder activityToken) {
2049 ActivityRecord srec;
2050 synchronized (mGlobalLock) {
2051 srec = ActivityRecord.forTokenLocked(activityToken);
2052 }
2053 if (srec == null) {
2054 return -1;
2055 }
2056 return srec.launchedFromUid;
2057 }
2058
2059 @Override
2060 public String getLaunchedFromPackage(IBinder activityToken) {
2061 ActivityRecord srec;
2062 synchronized (mGlobalLock) {
2063 srec = ActivityRecord.forTokenLocked(activityToken);
2064 }
2065 if (srec == null) {
2066 return null;
2067 }
2068 return srec.launchedFromPackage;
2069 }
2070
2071 @Override
2072 public boolean convertFromTranslucent(IBinder token) {
2073 final long origId = Binder.clearCallingIdentity();
2074 try {
2075 synchronized (mGlobalLock) {
2076 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2077 if (r == null) {
2078 return false;
2079 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002080 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002081 }
2082 } finally {
2083 Binder.restoreCallingIdentity(origId);
2084 }
2085 }
2086
2087 @Override
2088 public boolean convertToTranslucent(IBinder token, Bundle options) {
2089 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2090 final long origId = Binder.clearCallingIdentity();
2091 try {
2092 synchronized (mGlobalLock) {
2093 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2094 if (r == null) {
2095 return false;
2096 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002097 final ActivityRecord under = r.getTask().getActivityBelow(r);
2098 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002099 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2100 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002101 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002102 }
2103 } finally {
2104 Binder.restoreCallingIdentity(origId);
2105 }
2106 }
2107
2108 @Override
2109 public void notifyActivityDrawn(IBinder token) {
2110 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2111 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002112 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002113 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002114 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002115 }
2116 }
2117 }
2118
2119 @Override
2120 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2121 synchronized (mGlobalLock) {
2122 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2123 if (r == null) {
2124 return;
2125 }
2126 r.reportFullyDrawnLocked(restoredFromBundle);
2127 }
2128 }
2129
2130 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002131 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002132 synchronized (mGlobalLock) {
2133 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002134 if (stack != null) {
2135 final int displayId = stack.getDisplayId();
2136 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002137 }
2138 return DEFAULT_DISPLAY;
2139 }
2140 }
2141
2142 @Override
2143 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002144 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002145 long ident = Binder.clearCallingIdentity();
2146 try {
2147 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002148 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002149 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002150 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002151 }
2152 return null;
2153 }
2154 } finally {
2155 Binder.restoreCallingIdentity(ident);
2156 }
2157 }
2158
2159 @Override
2160 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002161 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002162 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2163 final long callingId = Binder.clearCallingIdentity();
2164 try {
2165 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002166 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002167 if (stack == null) {
2168 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2169 return;
2170 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002171 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002172 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002173 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002174 }
2175 }
2176 } finally {
2177 Binder.restoreCallingIdentity(callingId);
2178 }
2179 }
2180
2181 @Override
2182 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002183 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002184 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2185 final long callingId = Binder.clearCallingIdentity();
2186 try {
2187 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002188 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002189 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002190 if (task == null) {
2191 return;
2192 }
2193 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002194 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002195 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002196 }
2197 }
2198 } finally {
2199 Binder.restoreCallingIdentity(callingId);
2200 }
2201 }
2202
2203 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002204 public void restartActivityProcessIfVisible(IBinder activityToken) {
2205 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2206 final long callingId = Binder.clearCallingIdentity();
2207 try {
2208 synchronized (mGlobalLock) {
2209 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2210 if (r == null) {
2211 return;
2212 }
2213 r.restartProcessIfVisible();
2214 }
2215 } finally {
2216 Binder.restoreCallingIdentity(callingId);
2217 }
2218 }
2219
2220 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002221 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002222 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002223 synchronized (mGlobalLock) {
2224 final long ident = Binder.clearCallingIdentity();
2225 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002226 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 "remove-task");
2228 } finally {
2229 Binder.restoreCallingIdentity(ident);
2230 }
2231 }
2232 }
2233
2234 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002235 public void removeAllVisibleRecentTasks() {
2236 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2237 synchronized (mGlobalLock) {
2238 final long ident = Binder.clearCallingIdentity();
2239 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002240 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002241 } finally {
2242 Binder.restoreCallingIdentity(ident);
2243 }
2244 }
2245 }
2246
2247 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002248 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2249 synchronized (mGlobalLock) {
2250 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2251 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002252 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002253 }
2254 }
2255 return false;
2256 }
2257
2258 @Override
2259 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2260 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002261
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002262 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002263 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2264 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002265 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002266 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002267 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002268 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002269 }
2270 }
2271
2272 /**
2273 * Attempts to move a task backwards in z-order (the order of activities within the task is
2274 * unchanged).
2275 *
2276 * There are several possible results of this call:
2277 * - if the task is locked, then we will show the lock toast
2278 * - if there is a task behind the provided task, then that task is made visible and resumed as
2279 * this task is moved to the back
2280 * - otherwise, if there are no other tasks in the stack:
2281 * - if this task is in the pinned stack, then we remove the stack completely, which will
2282 * have the effect of moving the task to the top or bottom of the fullscreen stack
2283 * (depending on whether it is visible)
2284 * - otherwise, we simply return home and hide this task
2285 *
2286 * @param token A reference to the activity we wish to move
2287 * @param nonRoot If false then this only works if the activity is the root
2288 * of a task; if true it will work for any activity in a task.
2289 * @return Returns true if the move completed, false if not.
2290 */
2291 @Override
2292 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002293 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002294 synchronized (mGlobalLock) {
2295 final long origId = Binder.clearCallingIdentity();
2296 try {
2297 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002298 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002299 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002300 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002301 }
2302 } finally {
2303 Binder.restoreCallingIdentity(origId);
2304 }
2305 }
2306 return false;
2307 }
2308
2309 @Override
2310 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002311 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002312 long ident = Binder.clearCallingIdentity();
2313 Rect rect = new Rect();
2314 try {
2315 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002316 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002317 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2318 if (task == null) {
2319 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2320 return rect;
2321 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002322 if (task.getParent() != null) {
2323 rect.set(task.getBounds());
2324 } else if (task.mLastNonFullscreenBounds != null) {
2325 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002326 }
2327 }
2328 } finally {
2329 Binder.restoreCallingIdentity(ident);
2330 }
2331 return rect;
2332 }
2333
2334 @Override
2335 public ActivityManager.TaskDescription getTaskDescription(int id) {
2336 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002337 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002338 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002339 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002340 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2341 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002342 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002343 }
2344 }
2345 return null;
2346 }
2347
2348 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002349 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002350 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08002351 return setTaskWindowingModeSplitScreenPrimary(taskId, toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002352 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002353 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002354 synchronized (mGlobalLock) {
2355 final long ident = Binder.clearCallingIdentity();
2356 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002357 if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2358 return setTaskWindowingModeSplitScreen(taskId, windowingMode, toTop);
2359 }
Louis Chang149d5c82019-12-30 09:47:39 +08002360 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002361 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002362 if (task == null) {
2363 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002364 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002365 }
2366
2367 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2368 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2369
2370 if (!task.isActivityTypeStandardOrUndefined()) {
2371 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2372 + " non-standard task " + taskId + " to windowing mode="
2373 + windowingMode);
2374 }
2375
2376 final ActivityStack stack = task.getStack();
2377 if (toTop) {
2378 stack.moveToFront("setTaskWindowingMode", task);
2379 }
Louis Changa009c762020-02-26 11:21:31 +08002380 // Convert some windowing-mode changes into root-task reparents for split-screen.
2381 if (stack.inSplitScreenWindowingMode()) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07002382 stack.getDisplayArea().onSplitScreenModeDismissed();
Louis Changa009c762020-02-26 11:21:31 +08002383
2384 } else {
2385 stack.setWindowingMode(windowingMode);
2386 stack.getDisplay().ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2387 true /* notifyClients */);
2388 }
Winson Chung7ccc6812020-01-23 16:15:10 -08002389 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002390 } finally {
2391 Binder.restoreCallingIdentity(ident);
2392 }
2393 }
2394 }
2395
2396 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002397 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002398 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002399 ActivityRecord r = getCallingRecordLocked(token);
2400 return r != null ? r.info.packageName : null;
2401 }
2402 }
2403
2404 @Override
2405 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002406 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002407 ActivityRecord r = getCallingRecordLocked(token);
2408 return r != null ? r.intent.getComponent() : null;
2409 }
2410 }
2411
2412 private ActivityRecord getCallingRecordLocked(IBinder token) {
2413 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2414 if (r == null) {
2415 return null;
2416 }
2417 return r.resultTo;
2418 }
2419
2420 @Override
2421 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002422 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002423
2424 synchronized (mGlobalLock) {
2425 final long origId = Binder.clearCallingIdentity();
2426 try {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002427 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
2428 if (topFocusedStack != null) {
2429 topFocusedStack.unhandledBackLocked();
2430 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002431 } finally {
2432 Binder.restoreCallingIdentity(origId);
2433 }
2434 }
2435 }
2436
Mark Renouf446251d2019-04-26 10:22:41 -04002437 @Override
2438 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2439 synchronized (mGlobalLock) {
2440 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2441 if (r == null) {
2442 return;
2443 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002444 ActivityStack stack = r.getRootTask();
Winson Chunga1f869d2020-03-21 23:02:48 -07002445 final TaskOrganizerController taskOrgController =
2446 mWindowOrganizerController.mTaskOrganizerController;
2447 if (taskOrgController.handleInterceptBackPressedOnTaskRoot(stack)) {
2448 // This task is handled by a task organizer that has requested the back pressed
2449 // callback
2450 } else if (stack != null && (stack.isSingleTaskInstance())) {
Mark Renouf446251d2019-04-26 10:22:41 -04002451 // Single-task stacks are used for activities which are presented in floating
2452 // windows above full screen activities. Instead of directly finishing the
2453 // task, a task change listener is used to notify SystemUI so the action can be
2454 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002455 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002456 mTaskChangeNotificationController
2457 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2458 } else {
2459 try {
2460 callback.requestFinish();
2461 } catch (RemoteException e) {
2462 Slog.e(TAG, "Failed to invoke request finish callback", e);
2463 }
2464 }
2465 }
2466 }
2467
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002468 /**
2469 * TODO: Add mController hook
2470 */
2471 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002472 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2473 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002474 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002475
2476 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2477 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002478 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2479 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002480 }
2481 }
2482
Ricky Waiaca8a772019-04-04 16:01:06 +01002483 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2484 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002485 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002486 final int callingPid = Binder.getCallingPid();
2487 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002488 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002489 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002490 SafeActivityOptions.abort(options);
2491 return;
2492 }
2493 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002494 WindowProcessController callerApp = null;
2495 if (appThread != null) {
2496 callerApp = getProcessController(appThread);
2497 }
2498 final ActivityStarter starter = getActivityStartController().obtainStarter(
2499 null /* intent */, "moveTaskToFront");
2500 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
Galia Peychevaed401cc2020-03-19 20:28:09 +01002501 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002502 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002503 return;
2504 }
2505 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002506 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002507 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002508 if (task == null) {
2509 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002510 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002511 return;
2512 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002513 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002514 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002515 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002516 return;
2517 }
2518 ActivityOptions realOptions = options != null
2519 ? options.getOptions(mStackSupervisor)
2520 : null;
2521 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2522 false /* forceNonResizable */);
2523
Wale Ogunwale21e06482019-11-18 05:14:15 -08002524 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002525 if (topActivity != null) {
2526
2527 // We are reshowing a task, use a starting window to hide the initial draw delay
2528 // so the transition can start earlier.
2529 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2530 true /* taskSwitch */, fromRecents);
2531 }
2532 } finally {
2533 Binder.restoreCallingIdentity(origId);
2534 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002535 }
2536
Ricky Waiaca8a772019-04-04 16:01:06 +01002537 /**
2538 * Return true if callingUid is system, or packageName belongs to that callingUid.
2539 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002540 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002541 try {
2542 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2543 if (packageName == null) {
2544 return false;
2545 }
2546 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2547 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2548 UserHandle.getUserId(callingUid));
2549 return UserHandle.isSameApp(callingUid, uid);
2550 }
2551 } catch (RemoteException e) {
2552 // Should not happen
2553 }
2554 return true;
2555 }
2556
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002557 /**
2558 * Checks that the provided package name matches the current calling UID, throws a security
2559 * exception if it doesn't.
2560 */
2561 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2562 final int callingUid = Binder.getCallingUid();
2563 if (isSameApp(callingUid, packageName)) {
2564 return;
2565 }
2566 final String msg = "Permission Denial: package=" + packageName
2567 + " does not belong to uid=" + callingUid;
2568 Slog.w(TAG, msg);
2569 throw new SecurityException(msg);
2570 }
2571
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002572 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2573 int callingPid, int callingUid, String name) {
2574 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2575 return true;
2576 }
2577
2578 if (getRecentTasks().isCallerRecents(sourceUid)) {
2579 return true;
2580 }
2581
2582 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2583 if (perm == PackageManager.PERMISSION_GRANTED) {
2584 return true;
2585 }
2586 if (checkAllowAppSwitchUid(sourceUid)) {
2587 return true;
2588 }
2589
2590 // If the actual IPC caller is different from the logical source, then
2591 // also see if they are allowed to control app switches.
2592 if (callingUid != -1 && callingUid != sourceUid) {
2593 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2594 if (perm == PackageManager.PERMISSION_GRANTED) {
2595 return true;
2596 }
2597 if (checkAllowAppSwitchUid(callingUid)) {
2598 return true;
2599 }
2600 }
2601
2602 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2603 return false;
2604 }
2605
2606 private boolean checkAllowAppSwitchUid(int uid) {
2607 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2608 if (types != null) {
2609 for (int i = types.size() - 1; i >= 0; i--) {
2610 if (types.valueAt(i).intValue() == uid) {
2611 return true;
2612 }
2613 }
2614 }
2615 return false;
2616 }
2617
2618 @Override
2619 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2620 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2621 "setActivityController()");
2622 synchronized (mGlobalLock) {
2623 mController = controller;
2624 mControllerIsAMonkey = imAMonkey;
2625 Watchdog.getInstance().setActivityController(controller);
2626 }
2627 }
2628
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002629 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002630 synchronized (mGlobalLock) {
2631 return mController != null && mControllerIsAMonkey;
2632 }
2633 }
2634
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002635 @Override
2636 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2637 synchronized (mGlobalLock) {
2638 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2639 }
2640 }
2641
2642 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002643 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
Winson Chunge5ab0172020-03-21 23:00:24 -07002644 return getFilteredTasks(maxNum, false /* filterForVisibleRecents */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002645 }
2646
Winson Chunge5ab0172020-03-21 23:00:24 -07002647 /**
2648 * @param filterOnlyVisibleRecents whether to filter the tasks based on whether they would ever
2649 * be visible in the recent task list in systemui
2650 */
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002651 @Override
2652 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
Winson Chunge5ab0172020-03-21 23:00:24 -07002653 boolean filterOnlyVisibleRecents) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002654 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002655 final int callingPid = Binder.getCallingPid();
2656 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002657 final int[] profileIds = getUserManager().getProfileIds(
2658 UserHandle.getUserId(callingUid), true);
2659 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2660 for (int i = 0; i < profileIds.length; i++) {
2661 callingProfileIds.add(profileIds[i]);
2662 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002663 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2664
2665 synchronized (mGlobalLock) {
2666 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2667
Nicholas Sauer0259e532019-08-30 08:24:55 -07002668 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Winson Chunge5ab0172020-03-21 23:00:24 -07002669 mRootWindowContainer.getRunningTasks(maxNum, list, filterOnlyVisibleRecents, callingUid,
2670 allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002671 }
2672
2673 return list;
2674 }
2675
2676 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002677 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2678 synchronized (mGlobalLock) {
2679 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002680 try {
2681 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2682 if (r == null) return;
2683
2684 final PooledConsumer c = PooledLambda.obtainConsumer(
2685 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2686 r, resultWho, requestCode);
2687 // TODO: This should probably only loop over the task since you need to be in the
2688 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002689 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002690 c.recycle();
2691
2692 updateOomAdj();
2693 } finally {
2694 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002695 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002696 }
2697 }
2698
2699 @Override
2700 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002701 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002702 ActivityStack stack = ActivityRecord.getStackLocked(token);
2703 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002704 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002705 }
2706 return false;
2707 }
2708 }
2709
2710 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002711 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002712 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002713 synchronized (mGlobalLock) {
2714 final long ident = Binder.clearCallingIdentity();
2715 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002716 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002717 if (task == null) {
2718 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2719 return;
2720 }
2721
2722 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2723 + " to stackId=" + stackId + " toTop=" + toTop);
2724
Louis Chang149d5c82019-12-30 09:47:39 +08002725 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002726 if (stack == null) {
2727 throw new IllegalStateException(
2728 "moveTaskToStack: No stack for stackId=" + stackId);
2729 }
2730 if (!stack.isActivityTypeStandardOrUndefined()) {
2731 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2732 + taskId + " to stack " + stackId);
2733 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002734 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2735 "moveTaskToStack");
2736 } finally {
2737 Binder.restoreCallingIdentity(ident);
2738 }
2739 }
2740 }
2741
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002742 /**
2743 * Moves the specified task to the primary-split-screen stack.
2744 *
2745 * @param taskId Id of task to move.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002746 * @param toTop If the task and stack should be moved to the top.
Winson Chung7ccc6812020-01-23 16:15:10 -08002747 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002748 */
2749 @Override
Evan Rosky73a7fe92019-11-18 18:28:01 -08002750 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002751 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002752 "setTaskWindowingModeSplitScreenPrimary()");
2753 synchronized (mGlobalLock) {
2754 final long ident = Binder.clearCallingIdentity();
2755 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002756 return setTaskWindowingModeSplitScreen(taskId, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY,
2757 toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002758 } finally {
2759 Binder.restoreCallingIdentity(ident);
2760 }
2761 }
2762 }
2763
2764 /**
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002765 * Moves the specified task into a split-screen tile.
2766 */
2767 private boolean setTaskWindowingModeSplitScreen(int taskId, int windowingMode, boolean toTop) {
2768 if (!WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2769 throw new IllegalArgumentException("Calling setTaskWindowingModeSplitScreen with non"
2770 + "split-screen mode: " + windowingMode);
2771 }
2772 if (isInLockTaskMode()) {
2773 Slog.w(TAG, "setTaskWindowingModeSplitScreen: Is in lock task mode="
2774 + getLockTaskModeState());
2775 return false;
2776 }
2777
2778 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2779 MATCH_TASK_IN_STACKS_ONLY);
2780 if (task == null) {
2781 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2782 return false;
2783 }
2784 if (!task.isActivityTypeStandardOrUndefined()) {
2785 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2786 + " non-standard task " + taskId + " to split-screen windowing mode");
2787 }
Wale Ogunwale0d465192020-01-23 19:14:44 -08002788 if (!task.supportsSplitScreenWindowingMode()) {
2789 return false;
2790 }
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002791
2792 final int prevMode = task.getWindowingMode();
Louis Changa009c762020-02-26 11:21:31 +08002793 moveTaskToSplitScreenPrimaryTask(task, toTop);
Wale Ogunwale0d465192020-01-23 19:14:44 -08002794 return prevMode != task.getWindowingMode();
2795 }
2796
Louis Changa009c762020-02-26 11:21:31 +08002797 void moveTaskToSplitScreenPrimaryTask(Task task, boolean toTop) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07002798 final TaskDisplayArea taskDisplayArea = task.getDisplayArea();
2799 final ActivityStack primarySplitTask = taskDisplayArea.getRootSplitScreenPrimaryTask();
Louis Changa009c762020-02-26 11:21:31 +08002800 if (primarySplitTask == null) {
2801 throw new IllegalStateException("Can't enter split without associated organized task");
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002802 }
Louis Changa009c762020-02-26 11:21:31 +08002803
2804 if (toTop) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07002805 taskDisplayArea.positionStackAt(POSITION_TOP, primarySplitTask,
Andrii Kulian9ea12da2020-03-27 17:16:38 -07002806 false /* includingParents */);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002807 }
2808 WindowContainerTransaction wct = new WindowContainerTransaction();
Wale Ogunwale465b1e12020-03-31 12:15:51 -07002809 // Clear out current windowing mode before reparenting to split taks.
2810 wct.setWindowingMode(
2811 task.getStack().mRemoteToken.toWindowContainerToken(), WINDOWING_MODE_UNDEFINED);
Wale Ogunwaleadf116e2020-03-27 16:36:01 -07002812 wct.reparent(task.getStack().mRemoteToken.toWindowContainerToken(),
2813 primarySplitTask.mRemoteToken.toWindowContainerToken(), toTop);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07002814 mWindowOrganizerController.applyTransaction(wct);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002815 }
2816
2817 /**
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002818 * Removes stacks in the input windowing modes from the system if they are of activity type
2819 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2820 */
2821 @Override
2822 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002823 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002824 "removeStacksInWindowingModes()");
2825
2826 synchronized (mGlobalLock) {
2827 final long ident = Binder.clearCallingIdentity();
2828 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002829 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002830 } finally {
2831 Binder.restoreCallingIdentity(ident);
2832 }
2833 }
2834 }
2835
2836 @Override
2837 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002838 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002839 "removeStacksWithActivityTypes()");
2840
2841 synchronized (mGlobalLock) {
2842 final long ident = Binder.clearCallingIdentity();
2843 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002844 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002845 } finally {
2846 Binder.restoreCallingIdentity(ident);
2847 }
2848 }
2849 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002850
2851 @Override
2852 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2853 int userId) {
2854 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002855 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2856 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002857 callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002858 synchronized (mGlobalLock) {
Winson Chung66b08f02020-03-03 14:32:35 -08002859 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, userId, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002860 }
2861 }
2862
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002863 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864 @Override
2865 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002866 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002867 long ident = Binder.clearCallingIdentity();
2868 try {
2869 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002870 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002871 }
2872 } finally {
2873 Binder.restoreCallingIdentity(ident);
2874 }
2875 }
2876
2877 @Override
2878 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002879 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880 long ident = Binder.clearCallingIdentity();
2881 try {
2882 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002883 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884 }
2885 } finally {
2886 Binder.restoreCallingIdentity(ident);
2887 }
2888 }
2889
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002890 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002891 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002892 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2893 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2894 long ident = Binder.clearCallingIdentity();
2895 try {
2896 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002897 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002898 }
2899 } finally {
2900 Binder.restoreCallingIdentity(ident);
2901 }
2902 }
2903
2904 @Override
2905 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2906 int displayId) {
2907 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2908 long ident = Binder.clearCallingIdentity();
2909 try {
2910 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002911 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002912 }
2913 } finally {
2914 Binder.restoreCallingIdentity(ident);
2915 }
2916 }
2917
2918 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002919 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002920 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002921 final long callingUid = Binder.getCallingUid();
2922 final long origId = Binder.clearCallingIdentity();
2923 try {
2924 synchronized (mGlobalLock) {
2925 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002926 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2928 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2929 }
2930 } finally {
2931 Binder.restoreCallingIdentity(origId);
2932 }
2933 }
2934
2935 @Override
2936 public void startLockTaskModeByToken(IBinder token) {
2937 synchronized (mGlobalLock) {
2938 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2939 if (r == null) {
2940 return;
2941 }
Louis Changcdec0802019-11-11 11:45:07 +08002942 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002943 }
2944 }
2945
2946 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002947 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002948 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002949 // This makes inner call to look as if it was initiated by system.
2950 long ident = Binder.clearCallingIdentity();
2951 try {
2952 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002953 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002954 MATCH_TASK_IN_STACKS_ONLY);
2955 if (task == null) {
2956 return;
2957 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002958
2959 // When starting lock task mode the stack must be in front and focused
2960 task.getStack().moveToFront("startSystemLockTaskMode");
2961 startLockTaskModeLocked(task, true /* isSystemCaller */);
2962 }
2963 } finally {
2964 Binder.restoreCallingIdentity(ident);
2965 }
2966 }
2967
2968 @Override
2969 public void stopLockTaskModeByToken(IBinder token) {
2970 synchronized (mGlobalLock) {
2971 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2972 if (r == null) {
2973 return;
2974 }
Louis Changcdec0802019-11-11 11:45:07 +08002975 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002976 }
2977 }
2978
2979 /**
2980 * This API should be called by SystemUI only when user perform certain action to dismiss
2981 * lock task mode. We should only dismiss pinned lock task mode in this case.
2982 */
2983 @Override
2984 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002985 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002986 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2987 }
2988
Louis Changcdec0802019-11-11 11:45:07 +08002989 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002990 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2991 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2992 return;
2993 }
2994
Louis Chang149d5c82019-12-30 09:47:39 +08002995 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002996 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002997 throw new IllegalArgumentException("Invalid task, not in foreground");
2998 }
2999
3000 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
3001 // system or a specific app.
3002 // * System-initiated requests will only start the pinned mode (screen pinning)
3003 // * App-initiated requests
3004 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
3005 // - will start the pinned mode, otherwise
3006 final int callingUid = Binder.getCallingUid();
3007 long ident = Binder.clearCallingIdentity();
3008 try {
3009 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08003010 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003011
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003012 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003013 } finally {
3014 Binder.restoreCallingIdentity(ident);
3015 }
3016 }
3017
Louis Changcdec0802019-11-11 11:45:07 +08003018 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003019 final int callingUid = Binder.getCallingUid();
3020 long ident = Binder.clearCallingIdentity();
3021 try {
3022 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003023 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003024 }
3025 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
3026 // task and jumping straight into a call in the case of emergency call back.
3027 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
3028 if (tm != null) {
3029 tm.showInCallScreen(false);
3030 }
3031 } finally {
3032 Binder.restoreCallingIdentity(ident);
3033 }
3034 }
3035
3036 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003037 public void updateLockTaskPackages(int userId, String[] packages) {
3038 final int callingUid = Binder.getCallingUid();
3039 if (callingUid != 0 && callingUid != SYSTEM_UID) {
3040 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
3041 "updateLockTaskPackages()");
3042 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08003043 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003044 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
3045 + Arrays.toString(packages));
3046 getLockTaskController().updateLockTaskPackages(userId, packages);
3047 }
3048 }
3049
3050 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003051 public boolean isInLockTaskMode() {
3052 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3053 }
3054
3055 @Override
3056 public int getLockTaskModeState() {
3057 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003058 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003059 }
3060 }
3061
3062 @Override
3063 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3064 synchronized (mGlobalLock) {
3065 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3066 if (r != null) {
3067 r.setTaskDescription(td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003068 }
3069 }
3070 }
3071
3072 @Override
3073 public Bundle getActivityOptions(IBinder token) {
3074 final long origId = Binder.clearCallingIdentity();
3075 try {
3076 synchronized (mGlobalLock) {
3077 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3078 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003079 final ActivityOptions activityOptions = r.takeOptionsLocked(
3080 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003081 return activityOptions == null ? null : activityOptions.toBundle();
3082 }
3083 return null;
3084 }
3085 } finally {
3086 Binder.restoreCallingIdentity(origId);
3087 }
3088 }
3089
3090 @Override
3091 public List<IBinder> getAppTasks(String callingPackage) {
3092 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003093 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003094 long ident = Binder.clearCallingIdentity();
3095 try {
3096 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003097 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003098 }
3099 } finally {
3100 Binder.restoreCallingIdentity(ident);
3101 }
3102 }
3103
3104 @Override
3105 public void finishVoiceTask(IVoiceInteractionSession session) {
3106 synchronized (mGlobalLock) {
3107 final long origId = Binder.clearCallingIdentity();
3108 try {
3109 // TODO: VI Consider treating local voice interactions and voice tasks
3110 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003111 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003112 } finally {
3113 Binder.restoreCallingIdentity(origId);
3114 }
3115 }
3116
3117 }
3118
3119 @Override
3120 public boolean isTopOfTask(IBinder token) {
3121 synchronized (mGlobalLock) {
3122 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003123 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003124 }
3125 }
3126
3127 @Override
3128 public void notifyLaunchTaskBehindComplete(IBinder token) {
3129 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3130 }
3131
3132 @Override
3133 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003134 mH.post(() -> {
3135 synchronized (mGlobalLock) {
3136 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003137 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003138 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003139 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003140 } catch (RemoteException e) {
3141 }
3142 }
3143 }
3144
3145 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003146 }
3147
3148 /** Called from an app when assist data is ready. */
3149 @Override
3150 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3151 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003152 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003153 synchronized (pae) {
3154 pae.result = extras;
3155 pae.structure = structure;
3156 pae.content = content;
3157 if (referrer != null) {
3158 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3159 }
3160 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003161 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003162 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003163 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003164 structure.setHomeActivity(pae.isHome);
3165 }
3166 pae.haveResult = true;
3167 pae.notifyAll();
3168 if (pae.intent == null && pae.receiver == null) {
3169 // Caller is just waiting for the result.
3170 return;
3171 }
3172 }
3173 // We are now ready to launch the assist activity.
3174 IAssistDataReceiver sendReceiver = null;
3175 Bundle sendBundle = null;
3176 synchronized (mGlobalLock) {
3177 buildAssistBundleLocked(pae, extras);
3178 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003179 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003180 if (!exists) {
3181 // Timed out.
3182 return;
3183 }
3184
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003185 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003186 // Caller wants result sent back to them.
3187 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003188 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003189 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003190 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3191 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003192 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3193 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3194 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3195 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3196 }
3197 }
3198 if (sendReceiver != null) {
3199 try {
3200 sendReceiver.onHandleAssistData(sendBundle);
3201 } catch (RemoteException e) {
3202 }
3203 return;
3204 }
3205
3206 final long ident = Binder.clearCallingIdentity();
3207 try {
3208 if (TextUtils.equals(pae.intent.getAction(),
3209 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003210 // Start voice interaction through VoiceInteractionManagerService.
3211 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3212 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003213 } else {
3214 pae.intent.replaceExtras(pae.extras);
3215 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3216 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3217 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003218 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003219
3220 try {
3221 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3222 } catch (ActivityNotFoundException e) {
3223 Slog.w(TAG, "No activity to handle assist action.", e);
3224 }
3225 }
3226 } finally {
3227 Binder.restoreCallingIdentity(ident);
3228 }
3229 }
3230
3231 @Override
3232 public int addAppTask(IBinder activityToken, Intent intent,
3233 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3234 final int callingUid = Binder.getCallingUid();
3235 final long callingIdent = Binder.clearCallingIdentity();
3236
3237 try {
3238 synchronized (mGlobalLock) {
3239 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3240 if (r == null) {
3241 throw new IllegalArgumentException("Activity does not exist; token="
3242 + activityToken);
3243 }
3244 ComponentName comp = intent.getComponent();
3245 if (comp == null) {
3246 throw new IllegalArgumentException("Intent " + intent
3247 + " must specify explicit component");
3248 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003249 if (thumbnail.getWidth() != mThumbnailWidth
3250 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003251 throw new IllegalArgumentException("Bad thumbnail size: got "
3252 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003253 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003254 }
3255 if (intent.getSelector() != null) {
3256 intent.setSelector(null);
3257 }
3258 if (intent.getSourceBounds() != null) {
3259 intent.setSourceBounds(null);
3260 }
3261 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3262 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3263 // The caller has added this as an auto-remove task... that makes no
3264 // sense, so turn off auto-remove.
3265 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3266 }
3267 }
3268 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3269 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3270 if (ainfo.applicationInfo.uid != callingUid) {
3271 throw new SecurityException(
3272 "Can't add task for another application: target uid="
3273 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3274 }
3275
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003276 final ActivityStack stack = r.getRootTask();
Andrii Kulian86d676c2020-03-27 19:34:54 -07003277 final Task task = stack.getDisplayArea().createStack(stack.getWindowingMode(),
3278 stack.getActivityType(), !ON_TOP, ainfo, intent,
Louis Changa009c762020-02-26 11:21:31 +08003279 false /* createdByOrganizer */);
Wale Ogunwale0d465192020-01-23 19:14:44 -08003280
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003281 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003282 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003283 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003284 return INVALID_TASK_ID;
3285 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003286 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003287
3288 // TODO: Send the thumbnail to WM to store it.
3289
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003290 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003291 }
3292 } finally {
3293 Binder.restoreCallingIdentity(callingIdent);
3294 }
3295 }
3296
3297 @Override
3298 public Point getAppTaskThumbnailSize() {
3299 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003300 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003301 }
3302 }
3303
3304 @Override
3305 public void setTaskResizeable(int taskId, int resizeableMode) {
3306 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003307 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003308 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3309 if (task == null) {
3310 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3311 return;
3312 }
3313 task.setResizeMode(resizeableMode);
3314 }
3315 }
3316
3317 @Override
3318 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003319 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003320 long ident = Binder.clearCallingIdentity();
3321 try {
3322 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003323 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003324 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003325 if (task == null) {
3326 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3327 return;
3328 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003329 if (!task.getWindowConfiguration().canResizeTask()) {
3330 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3331 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003332
3333 // Reparent the task to the right stack if necessary
3334 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003335
3336 // After reparenting (which only resizes the task to the stack bounds), resize the
3337 // task to the actual bounds provided
3338 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3339 }
3340 } finally {
3341 Binder.restoreCallingIdentity(ident);
3342 }
3343 }
3344
3345 @Override
3346 public boolean releaseActivityInstance(IBinder token) {
3347 synchronized (mGlobalLock) {
3348 final long origId = Binder.clearCallingIdentity();
3349 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003350 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3351 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003352 return false;
3353 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003354 r.destroyImmediately(true /* removeFromApp */, "app-req");
3355 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003356 } finally {
3357 Binder.restoreCallingIdentity(origId);
3358 }
3359 }
3360 }
3361
3362 @Override
3363 public void releaseSomeActivities(IApplicationThread appInt) {
3364 synchronized (mGlobalLock) {
3365 final long origId = Binder.clearCallingIdentity();
3366 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003367 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003368 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003369 } finally {
3370 Binder.restoreCallingIdentity(origId);
3371 }
3372 }
3373 }
3374
3375 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003376 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003377 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378 != PackageManager.PERMISSION_GRANTED) {
3379 throw new SecurityException("Requires permission "
3380 + android.Manifest.permission.DEVICE_POWER);
3381 }
3382
3383 synchronized (mGlobalLock) {
3384 long ident = Binder.clearCallingIdentity();
3385 if (mKeyguardShown != keyguardShowing) {
3386 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003387 final Message msg = PooledLambda.obtainMessage(
3388 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3389 keyguardShowing);
3390 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003391 }
3392 try {
wilsonshih177261f2019-02-22 12:02:18 +08003393 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003394 } finally {
3395 Binder.restoreCallingIdentity(ident);
3396 }
3397 }
3398
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003399 mH.post(() -> {
3400 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3401 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3402 }
3403 });
3404 }
3405
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003406 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003407 mH.post(() -> {
3408 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3409 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3410 }
3411 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 }
3413
3414 @Override
3415 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003416 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3417 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003418
3419 final File passedIconFile = new File(filePath);
3420 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3421 passedIconFile.getName());
3422 if (!legitIconFile.getPath().equals(filePath)
3423 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3424 throw new IllegalArgumentException("Bad file path: " + filePath
3425 + " passed for userId " + userId);
3426 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003427 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003428 }
3429
3430 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003431 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003432 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003433 synchronized (mGlobalLock) {
3434 final long ident = Binder.clearCallingIdentity();
3435 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003436 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003437 if (stack == null) {
3438 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3439 return;
3440 }
3441 if (!stack.isActivityTypeStandardOrUndefined()) {
3442 throw new IllegalArgumentException(
3443 "Removing non-standard stack is not allowed.");
3444 }
3445 mStackSupervisor.removeStack(stack);
3446 } finally {
3447 Binder.restoreCallingIdentity(ident);
3448 }
3449 }
3450 }
3451
3452 @Override
3453 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003454 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003455
3456 synchronized (mGlobalLock) {
3457 final long ident = Binder.clearCallingIdentity();
3458 try {
3459 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3460 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003461 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003462 } finally {
3463 Binder.restoreCallingIdentity(ident);
3464 }
3465 }
3466 }
3467
3468 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003469 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003470 synchronized (mGlobalLock) {
3471 long ident = Binder.clearCallingIdentity();
3472 try {
3473 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3474 if (r == null) {
3475 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003476 "toggleFreeformWindowingMode: No activity record matching token="
3477 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003478 }
3479
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003480 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003481 if (stack == null) {
3482 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3483 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003484 }
3485
Yunfan Chend967af82019-01-17 18:30:18 +09003486 if (!stack.inFreeformWindowingMode()
3487 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3488 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3489 + "toggle between fullscreen and freeform.");
3490 }
3491
3492 if (stack.inFreeformWindowingMode()) {
3493 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003494 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003495 throw new IllegalStateException("Size-compat windows are currently not"
3496 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003497 } else if (stack.getParent().inFreeformWindowingMode()) {
3498 // If the window is on a freeform display, set it to undefined. It will be
3499 // resolved to freeform and it can adjust windowing mode when the display mode
3500 // changes in runtime.
3501 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003502 } else {
3503 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3504 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003505 } finally {
3506 Binder.restoreCallingIdentity(ident);
3507 }
3508 }
3509 }
3510
3511 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3512 @Override
3513 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003514 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003515 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003516 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003517 }
3518
3519 /** Unregister a task stack listener so that it stops receiving callbacks. */
3520 @Override
3521 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003522 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003523 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003524 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003525 }
3526
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003527 @Override
3528 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3529 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3530 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3531 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3532 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3533 }
3534
3535 @Override
3536 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3537 IBinder activityToken, int flags) {
3538 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3539 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3540 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3541 }
3542
3543 @Override
3544 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3545 Bundle args) {
3546 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3547 true /* focused */, true /* newSessionId */, userHandle, args,
3548 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3549 }
3550
3551 @Override
3552 public Bundle getAssistContextExtras(int requestType) {
3553 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3554 null, null, true /* focused */, true /* newSessionId */,
3555 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3556 if (pae == null) {
3557 return null;
3558 }
3559 synchronized (pae) {
3560 while (!pae.haveResult) {
3561 try {
3562 pae.wait();
3563 } catch (InterruptedException e) {
3564 }
3565 }
3566 }
3567 synchronized (mGlobalLock) {
3568 buildAssistBundleLocked(pae, pae.result);
3569 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003570 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003571 }
3572 return pae.extras;
3573 }
3574
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003575 /**
3576 * Binder IPC calls go through the public entry point.
3577 * This can be called with or without the global lock held.
3578 */
3579 private static int checkCallingPermission(String permission) {
3580 return checkPermission(
3581 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3582 }
3583
3584 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003585 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003586 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3587 mAmInternal.enforceCallingPermission(permission, func);
3588 }
3589 }
3590
3591 @VisibleForTesting
3592 int checkGetTasksPermission(String permission, int pid, int uid) {
3593 return checkPermission(permission, pid, uid);
3594 }
3595
3596 static int checkPermission(String permission, int pid, int uid) {
3597 if (permission == null) {
3598 return PackageManager.PERMISSION_DENIED;
3599 }
3600 return checkComponentPermission(permission, pid, uid, -1, true);
3601 }
3602
Wale Ogunwale214f3482018-10-04 11:00:47 -07003603 public static int checkComponentPermission(String permission, int pid, int uid,
3604 int owningUid, boolean exported) {
3605 return ActivityManagerService.checkComponentPermission(
3606 permission, pid, uid, owningUid, exported);
3607 }
3608
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003609 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3610 if (getRecentTasks().isCallerRecents(callingUid)) {
3611 // Always allow the recents component to get tasks
3612 return true;
3613 }
3614
3615 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3616 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3617 if (!allowed) {
3618 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3619 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3620 // Temporary compatibility: some existing apps on the system image may
3621 // still be requesting the old permission and not switched to the new
3622 // one; if so, we'll still allow them full access. This means we need
3623 // to see if they are holding the old permission and are a system app.
3624 try {
3625 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3626 allowed = true;
3627 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3628 + " is using old GET_TASKS but privileged; allowing");
3629 }
3630 } catch (RemoteException e) {
3631 }
3632 }
3633 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3634 + " does not hold REAL_GET_TASKS; limiting output");
3635 }
3636 return allowed;
3637 }
3638
Nicholas Sauer0259e532019-08-30 08:24:55 -07003639 boolean isCrossUserAllowed(int pid, int uid) {
3640 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3641 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3642 }
3643
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003644 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3645 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3646 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3647 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003648 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003649 "enqueueAssistContext()");
3650
3651 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08003652 final ActivityStack stack = getTopDisplayFocusedStack();
3653 ActivityRecord activity = stack != null ? stack.getTopNonFinishingActivity() : null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003654 if (activity == null) {
3655 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3656 return null;
3657 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003658 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003659 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3660 return null;
3661 }
3662 if (focused) {
3663 if (activityToken != null) {
3664 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3665 if (activity != caller) {
3666 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3667 + " is not current top " + activity);
3668 return null;
3669 }
3670 }
3671 } else {
3672 activity = ActivityRecord.forTokenLocked(activityToken);
3673 if (activity == null) {
3674 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3675 + " couldn't be found");
3676 return null;
3677 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003678 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003679 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3680 return null;
3681 }
3682 }
3683
3684 PendingAssistExtras pae;
3685 Bundle extras = new Bundle();
3686 if (args != null) {
3687 extras.putAll(args);
3688 }
3689 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003690 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003691
3692 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3693 userHandle);
3694 pae.isHome = activity.isActivityTypeHome();
3695
3696 // Increment the sessionId if necessary
3697 if (newSessionId) {
3698 mViSessionId++;
3699 }
3700 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003701 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3702 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003703 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003704 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003705 } catch (RemoteException e) {
3706 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3707 return null;
3708 }
3709 return pae;
3710 }
3711 }
3712
3713 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3714 if (result != null) {
3715 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3716 }
3717 if (pae.hint != null) {
3718 pae.extras.putBoolean(pae.hint, true);
3719 }
3720 }
3721
3722 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3723 IAssistDataReceiver receiver;
3724 synchronized (mGlobalLock) {
3725 mPendingAssistExtras.remove(pae);
3726 receiver = pae.receiver;
3727 }
3728 if (receiver != null) {
3729 // Caller wants result sent back to them.
3730 Bundle sendBundle = new Bundle();
3731 // At least return the receiver extras
3732 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3733 try {
3734 pae.receiver.onHandleAssistData(sendBundle);
3735 } catch (RemoteException e) {
3736 }
3737 }
3738 }
3739
3740 public class PendingAssistExtras extends Binder implements Runnable {
3741 public final ActivityRecord activity;
3742 public boolean isHome;
3743 public final Bundle extras;
3744 public final Intent intent;
3745 public final String hint;
3746 public final IAssistDataReceiver receiver;
3747 public final int userHandle;
3748 public boolean haveResult = false;
3749 public Bundle result = null;
3750 public AssistStructure structure = null;
3751 public AssistContent content = null;
3752 public Bundle receiverExtras;
3753
3754 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3755 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3756 int _userHandle) {
3757 activity = _activity;
3758 extras = _extras;
3759 intent = _intent;
3760 hint = _hint;
3761 receiver = _receiver;
3762 receiverExtras = _receiverExtras;
3763 userHandle = _userHandle;
3764 }
3765
3766 @Override
3767 public void run() {
3768 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3769 synchronized (this) {
3770 haveResult = true;
3771 notifyAll();
3772 }
3773 pendingAssistExtrasTimedOut(this);
3774 }
3775 }
3776
3777 @Override
3778 public boolean isAssistDataAllowedOnCurrentActivity() {
3779 int userId;
3780 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003781 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003782 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3783 return false;
3784 }
3785
Wale Ogunwale21e06482019-11-18 05:14:15 -08003786 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003787 if (activity == null) {
3788 return false;
3789 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003790 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003791 }
3792 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3793 }
3794
3795 @Override
3796 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3797 long ident = Binder.clearCallingIdentity();
3798 try {
3799 synchronized (mGlobalLock) {
3800 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003801 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003802 if (top != caller) {
3803 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3804 + " is not current top " + top);
3805 return false;
3806 }
3807 if (!top.nowVisible) {
3808 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3809 + " is not visible");
3810 return false;
3811 }
3812 }
3813 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3814 token);
3815 } finally {
3816 Binder.restoreCallingIdentity(ident);
3817 }
3818 }
3819
3820 @Override
3821 public boolean isRootVoiceInteraction(IBinder token) {
3822 synchronized (mGlobalLock) {
3823 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3824 if (r == null) {
3825 return false;
3826 }
3827 return r.rootVoiceInteraction;
3828 }
3829 }
3830
Wale Ogunwalef6733932018-06-27 05:14:34 -07003831 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3832 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3833 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3834 if (activityToCallback == null) return;
3835 activityToCallback.setVoiceSessionLocked(voiceSession);
3836
3837 // Inform the activity
3838 try {
3839 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3840 voiceInteractor);
3841 long token = Binder.clearCallingIdentity();
3842 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003843 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003844 } finally {
3845 Binder.restoreCallingIdentity(token);
3846 }
3847 // TODO: VI Should we cache the activity so that it's easier to find later
3848 // rather than scan through all the stacks and activities?
3849 } catch (RemoteException re) {
3850 activityToCallback.clearVoiceSessionLocked();
3851 // TODO: VI Should this terminate the voice session?
3852 }
3853 }
3854
3855 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3856 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3857 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3858 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3859 boolean wasRunningVoice = mRunningVoice != null;
3860 mRunningVoice = session;
3861 if (!wasRunningVoice) {
3862 mVoiceWakeLock.acquire();
3863 updateSleepIfNeededLocked();
3864 }
3865 }
3866 }
3867
3868 void finishRunningVoiceLocked() {
3869 if (mRunningVoice != null) {
3870 mRunningVoice = null;
3871 mVoiceWakeLock.release();
3872 updateSleepIfNeededLocked();
3873 }
3874 }
3875
3876 @Override
3877 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3878 synchronized (mGlobalLock) {
3879 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3880 if (keepAwake) {
3881 mVoiceWakeLock.acquire();
3882 } else {
3883 mVoiceWakeLock.release();
3884 }
3885 }
3886 }
3887 }
3888
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003889 @Override
3890 public ComponentName getActivityClassForToken(IBinder token) {
3891 synchronized (mGlobalLock) {
3892 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3893 if (r == null) {
3894 return null;
3895 }
3896 return r.intent.getComponent();
3897 }
3898 }
3899
3900 @Override
3901 public String getPackageForToken(IBinder token) {
3902 synchronized (mGlobalLock) {
3903 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3904 if (r == null) {
3905 return null;
3906 }
3907 return r.packageName;
3908 }
3909 }
3910
3911 @Override
3912 public void showLockTaskEscapeMessage(IBinder token) {
3913 synchronized (mGlobalLock) {
3914 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3915 if (r == null) {
3916 return;
3917 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003918 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003919 }
3920 }
3921
3922 @Override
3923 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003924 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003925 final long token = Binder.clearCallingIdentity();
3926 try {
3927 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003928 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003929 }
3930 } finally {
3931 Binder.restoreCallingIdentity(token);
3932 }
3933 }
3934
3935 /**
3936 * Try to place task to provided position. The final position might be different depending on
3937 * current user and stacks state. The task will be moved to target stack if it's currently in
3938 * different stack.
3939 */
3940 @Override
3941 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003942 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003943 synchronized (mGlobalLock) {
3944 long ident = Binder.clearCallingIdentity();
3945 try {
3946 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3947 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003948 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003949 if (task == null) {
3950 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3951 + taskId);
3952 }
3953
Louis Chang149d5c82019-12-30 09:47:39 +08003954 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003955
3956 if (stack == null) {
3957 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3958 + stackId);
3959 }
3960 if (!stack.isActivityTypeStandardOrUndefined()) {
3961 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3962 + " the position of task " + taskId + " in/to non-standard stack");
3963 }
3964
3965 // TODO: Have the callers of this API call a separate reparent method if that is
3966 // what they intended to do vs. having this method also do reparenting.
3967 if (task.getStack() == stack) {
3968 // Change position in current stack.
3969 stack.positionChildAt(task, position);
3970 } else {
3971 // Reparent to new stack.
3972 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3973 !DEFER_RESUME, "positionTaskInStack");
3974 }
3975 } finally {
3976 Binder.restoreCallingIdentity(ident);
3977 }
3978 }
3979 }
3980
3981 @Override
3982 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3983 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3984 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003985 + Arrays.toString(horizontalSizeConfiguration) + " "
3986 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003987 synchronized (mGlobalLock) {
3988 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3989 if (record == null) {
3990 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3991 + "found for: " + token);
3992 }
3993 record.setSizeConfigurations(horizontalSizeConfiguration,
3994 verticalSizeConfigurations, smallestSizeConfigurations);
3995 }
3996 }
3997
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003998 @Override
3999 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004000 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004001 synchronized (mGlobalLock) {
4002 mSuppressResizeConfigChanges = suppress;
4003 }
4004 }
4005
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004006 /**
4007 * Moves the top activity in the input stackId to the pinned stack.
4008 *
4009 * @param stackId Id of stack to move the top activity to pinned stack.
4010 * @param bounds Bounds to use for pinned stack.
4011 *
4012 * @return True if the top activity of the input stack was successfully moved to the pinned
4013 * stack.
4014 */
4015 @Override
4016 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004017 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004018 "moveTopActivityToPinnedStack()");
4019 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004020 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004021 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4022 + "Device doesn't support picture-in-picture mode");
4023 }
4024
4025 long ident = Binder.clearCallingIdentity();
4026 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004027 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004028 } finally {
4029 Binder.restoreCallingIdentity(ident);
4030 }
4031 }
4032 }
4033
4034 @Override
4035 public boolean isInMultiWindowMode(IBinder token) {
4036 final long origId = Binder.clearCallingIdentity();
4037 try {
4038 synchronized (mGlobalLock) {
4039 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4040 if (r == null) {
4041 return false;
4042 }
4043 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4044 return r.inMultiWindowMode();
4045 }
4046 } finally {
4047 Binder.restoreCallingIdentity(origId);
4048 }
4049 }
4050
4051 @Override
4052 public boolean isInPictureInPictureMode(IBinder token) {
4053 final long origId = Binder.clearCallingIdentity();
4054 try {
4055 synchronized (mGlobalLock) {
4056 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4057 }
4058 } finally {
4059 Binder.restoreCallingIdentity(origId);
4060 }
4061 }
4062
4063 private boolean isInPictureInPictureMode(ActivityRecord r) {
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004064 return r != null
4065 && r.getRootTask() != null
4066 && r.inPinnedWindowingMode()
4067 && r.getRootTask().isInStackLocked(r) != null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004068 }
4069
4070 @Override
4071 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4072 final long origId = Binder.clearCallingIdentity();
4073 try {
4074 synchronized (mGlobalLock) {
4075 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4076 "enterPictureInPictureMode", token, params);
4077
4078 // If the activity is already in picture in picture mode, then just return early
4079 if (isInPictureInPictureMode(r)) {
4080 return true;
4081 }
4082
4083 // Activity supports picture-in-picture, now check that we can enter PiP at this
4084 // point, if it is
4085 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4086 false /* beforeStopping */)) {
4087 return false;
4088 }
4089
4090 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004091 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004092 if (r.getParent() == null) {
4093 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4094 return;
4095 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004096 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004097 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004098 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4099 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
Louis Chang149d5c82019-12-30 09:47:39 +08004100 mRootWindowContainer.moveActivityToPinnedStack(
Hongwei Wange8e32862020-04-08 13:23:45 -07004101 r, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004102 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004103 stack.setPictureInPictureAspectRatio(aspectRatio);
4104 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004105 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4106 r.info.applicationInfo.uid, r.shortComponentName,
4107 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004108 logPictureInPictureArgs(params);
4109 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004110 };
4111
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004112 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004113 // If the keyguard is showing or occluded, then try and dismiss it before
4114 // entering picture-in-picture (this will prompt the user to authenticate if the
4115 // device is currently locked).
4116 dismissKeyguard(token, new KeyguardDismissCallback() {
4117 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004118 public void onDismissSucceeded() {
4119 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004120 }
4121 }, null /* message */);
4122 } else {
4123 // Enter picture in picture immediately otherwise
4124 enterPipRunnable.run();
4125 }
4126 return true;
4127 }
4128 } finally {
4129 Binder.restoreCallingIdentity(origId);
4130 }
4131 }
4132
4133 @Override
4134 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4135 final long origId = Binder.clearCallingIdentity();
4136 try {
4137 synchronized (mGlobalLock) {
4138 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4139 "setPictureInPictureParams", token, params);
4140
4141 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004142 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004143 if (r.inPinnedWindowingMode()) {
4144 // If the activity is already in picture-in-picture, update the pinned stack now
4145 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4146 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004147 final ActivityStack stack = r.getRootTask();
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004148 stack.setPictureInPictureAspectRatio(
4149 r.pictureInPictureArgs.getAspectRatio());
4150 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004151 }
4152 logPictureInPictureArgs(params);
4153 }
4154 } finally {
4155 Binder.restoreCallingIdentity(origId);
4156 }
4157 }
4158
4159 @Override
4160 public int getMaxNumPictureInPictureActions(IBinder token) {
4161 // Currently, this is a static constant, but later, we may change this to be dependent on
4162 // the context of the activity
4163 return 3;
4164 }
4165
4166 private void logPictureInPictureArgs(PictureInPictureParams params) {
4167 if (params.hasSetActions()) {
4168 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4169 params.getActions().size());
4170 }
4171 if (params.hasSetAspectRatio()) {
4172 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4173 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4174 MetricsLogger.action(lm);
4175 }
4176 }
4177
4178 /**
4179 * Checks the state of the system and the activity associated with the given {@param token} to
4180 * verify that picture-in-picture is supported for that activity.
4181 *
4182 * @return the activity record for the given {@param token} if all the checks pass.
4183 */
4184 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4185 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004186 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004187 throw new IllegalStateException(caller
4188 + ": Device doesn't support picture-in-picture mode.");
4189 }
4190
4191 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4192 if (r == null) {
4193 throw new IllegalStateException(caller
4194 + ": Can't find activity for token=" + token);
4195 }
4196
4197 if (!r.supportsPictureInPicture()) {
4198 throw new IllegalStateException(caller
4199 + ": Current activity does not support picture-in-picture.");
4200 }
4201
4202 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004203 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004204 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004205 final float minAspectRatio = mContext.getResources().getFloat(
4206 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4207 final float maxAspectRatio = mContext.getResources().getFloat(
4208 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4209 throw new IllegalArgumentException(String.format(caller
4210 + ": Aspect ratio is too extreme (must be between %f and %f).",
4211 minAspectRatio, maxAspectRatio));
4212 }
4213
4214 // Truncate the number of actions if necessary
4215 params.truncateActions(getMaxNumPictureInPictureActions(token));
4216
4217 return r;
4218 }
4219
4220 @Override
4221 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004222 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004223 synchronized (mGlobalLock) {
4224 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4225 if (r == null) {
4226 throw new IllegalArgumentException("Activity does not exist; token="
4227 + activityToken);
4228 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004229 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004230 }
4231 }
4232
Evan Rosky73a7fe92019-11-18 18:28:01 -08004233 // TODO(b/149338177): remove when CTS no-longer requires it
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004234 @Override
4235 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4236 Rect tempDockedTaskInsetBounds,
4237 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004238 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004239 long ident = Binder.clearCallingIdentity();
4240 try {
4241 synchronized (mGlobalLock) {
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -07004242 final TaskDisplayArea tc = mRootWindowContainer.getDefaultTaskDisplayArea();
4243 final Task primary = tc.getRootSplitScreenPrimaryTask();
4244 final Task secondary = tc.getTask(t -> t.mCreatedByOrganizer && t.isRootTask()
Louis Changa009c762020-02-26 11:21:31 +08004245 && t.inSplitScreenSecondaryWindowingMode());
Evan Rosky73a7fe92019-11-18 18:28:01 -08004246 if (primary == null || secondary == null) {
4247 return;
4248 }
4249 final WindowContainerTransaction wct = new WindowContainerTransaction();
4250 final Rect primaryRect =
4251 tempDockedTaskInsetBounds != null ? tempDockedTaskInsetBounds
4252 : (tempDockedTaskBounds != null ? tempDockedTaskBounds
4253 : dockedBounds);
Wale Ogunwaleadf116e2020-03-27 16:36:01 -07004254 wct.setBounds(primary.mRemoteToken.toWindowContainerToken(), primaryRect);
Evan Rosky73a7fe92019-11-18 18:28:01 -08004255 Rect otherRect = tempOtherTaskInsetBounds != null ? tempOtherTaskInsetBounds
4256 : tempOtherTaskBounds;
4257 if (otherRect == null) {
4258 // Temporary estimation... again this is just for tests.
4259 otherRect = new Rect(secondary.getBounds());
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -07004260 if (tc.getBounds().width() > tc.getBounds().height()) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08004261 otherRect.left = primaryRect.right + 6;
4262 } else {
4263 otherRect.top = primaryRect.bottom + 6;
4264 }
4265 }
Wale Ogunwaleadf116e2020-03-27 16:36:01 -07004266 wct.setBounds(secondary.mRemoteToken.toWindowContainerToken(), otherRect);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004267 mWindowOrganizerController.applyTransaction(wct);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004268 }
4269 } finally {
4270 Binder.restoreCallingIdentity(ident);
4271 }
4272 }
4273
4274 @Override
4275 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004276 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004277 final long ident = Binder.clearCallingIdentity();
4278 try {
4279 synchronized (mGlobalLock) {
4280 mStackSupervisor.setSplitScreenResizing(resizing);
4281 }
4282 } finally {
4283 Binder.restoreCallingIdentity(ident);
4284 }
4285 }
4286
Evan Rosky0037e5f2019-11-05 10:26:24 -08004287 @Override
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004288 public IWindowOrganizerController getWindowOrganizerController() {
Evan Rosky0037e5f2019-11-05 10:26:24 -08004289 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004290 "getWindowOrganizerController()");
4291 return mWindowOrganizerController;
Evan Rosky0037e5f2019-11-05 10:26:24 -08004292 }
4293
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004294 /**
4295 * Check that we have the features required for VR-related API calls, and throw an exception if
4296 * not.
4297 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004298 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004299 if (!mContext.getPackageManager().hasSystemFeature(
4300 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4301 throw new UnsupportedOperationException("VR mode not supported on this device!");
4302 }
4303 }
4304
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004305 @Override
4306 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004307 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004308
4309 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4310
4311 ActivityRecord r;
4312 synchronized (mGlobalLock) {
4313 r = ActivityRecord.isInStackLocked(token);
4314 }
4315
4316 if (r == null) {
4317 throw new IllegalArgumentException();
4318 }
4319
4320 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004321 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004322 VrManagerInternal.NO_ERROR) {
4323 return err;
4324 }
4325
4326 // Clear the binder calling uid since this path may call moveToTask().
4327 final long callingId = Binder.clearCallingIdentity();
4328 try {
4329 synchronized (mGlobalLock) {
4330 r.requestedVrComponent = (enabled) ? packageName : null;
4331
4332 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004333 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004334 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004335 }
4336 return 0;
4337 }
4338 } finally {
4339 Binder.restoreCallingIdentity(callingId);
4340 }
4341 }
4342
4343 @Override
4344 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4345 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4346 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004347 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004348 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4349 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4350 }
Louis Changcdec0802019-11-11 11:45:07 +08004351 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004352 || activity.voiceSession != null) {
4353 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4354 return;
4355 }
4356 if (activity.pendingVoiceInteractionStart) {
4357 Slog.w(TAG, "Pending start of voice interaction already.");
4358 return;
4359 }
4360 activity.pendingVoiceInteractionStart = true;
4361 }
4362 LocalServices.getService(VoiceInteractionManagerInternal.class)
4363 .startLocalVoiceInteraction(callingActivity, options);
4364 }
4365
4366 @Override
4367 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4368 LocalServices.getService(VoiceInteractionManagerInternal.class)
4369 .stopLocalVoiceInteraction(callingActivity);
4370 }
4371
4372 @Override
4373 public boolean supportsLocalVoiceInteraction() {
4374 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4375 .supportsLocalVoiceInteraction();
4376 }
4377
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004378 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004379 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004380 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004381
4382 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004383 if (mWindowManager == null) {
4384 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4385 return false;
4386 }
4387
4388 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004389 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004390 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004391 }
4392
Riddle Hsua0022cd2019-09-09 21:12:41 +08004393 mH.sendMessage(PooledLambda.obtainMessage(
4394 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4395 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004396
4397 final long origId = Binder.clearCallingIdentity();
4398 try {
4399 if (values != null) {
4400 Settings.System.clearConfiguration(values);
4401 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004402 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004403 UserHandle.USER_NULL, false /* deferResume */,
4404 mTmpUpdateConfigurationResult);
4405 return mTmpUpdateConfigurationResult.changes != 0;
4406 } finally {
4407 Binder.restoreCallingIdentity(origId);
4408 }
4409 }
4410 }
4411
4412 @Override
4413 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4414 CharSequence message) {
4415 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004416 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004417 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4418 }
4419 final long callingId = Binder.clearCallingIdentity();
4420 try {
4421 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004422 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004423 }
4424 } finally {
4425 Binder.restoreCallingIdentity(callingId);
4426 }
4427 }
4428
4429 @Override
4430 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004431 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004432 "cancelTaskWindowTransition()");
4433 final long ident = Binder.clearCallingIdentity();
4434 try {
4435 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004436 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004437 MATCH_TASK_IN_STACKS_ONLY);
4438 if (task == null) {
4439 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4440 return;
4441 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004442 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004443 }
4444 } finally {
4445 Binder.restoreCallingIdentity(ident);
4446 }
4447 }
4448
4449 @Override
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004450 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004451 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004452 final long ident = Binder.clearCallingIdentity();
4453 try {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004454 return getTaskSnapshot(taskId, isLowResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004455 } finally {
4456 Binder.restoreCallingIdentity(ident);
4457 }
4458 }
4459
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004460 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004461 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004462 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004463 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004464 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004465 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4466 if (task == null) {
4467 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4468 return null;
4469 }
4470 }
4471 // Don't call this while holding the lock as this operation might hit the disk.
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004472 return task.getSnapshot(isLowResolution, restoreFromDisk);
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004473 }
4474
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004475 @Override
4476 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4477 synchronized (mGlobalLock) {
4478 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4479 if (r == null) {
4480 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4481 + token);
4482 return;
4483 }
4484 final long origId = Binder.clearCallingIdentity();
4485 try {
4486 r.setDisablePreviewScreenshots(disable);
4487 } finally {
4488 Binder.restoreCallingIdentity(origId);
4489 }
4490 }
4491 }
4492
Riddle Hsu440f88b2019-11-06 22:17:35 +08004493 @Override
4494 public void invalidateHomeTaskSnapshot(IBinder token) {
4495 synchronized (mGlobalLock) {
4496 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4497 if (r == null || !r.isActivityTypeHome()) {
4498 return;
4499 }
4500 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4501 }
4502 }
4503
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004504 /** Return the user id of the last resumed activity. */
4505 @Override
4506 public @UserIdInt
4507 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004508 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004509 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4510 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004511 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004512 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004513 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004514 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004515 }
4516 }
4517
4518 @Override
4519 public void updateLockTaskFeatures(int userId, int flags) {
4520 final int callingUid = Binder.getCallingUid();
4521 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004522 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004523 "updateLockTaskFeatures()");
4524 }
4525 synchronized (mGlobalLock) {
4526 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4527 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004528 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004529 }
4530 }
4531
4532 @Override
4533 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4534 synchronized (mGlobalLock) {
4535 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4536 if (r == null) {
4537 return;
4538 }
4539 final long origId = Binder.clearCallingIdentity();
4540 try {
4541 r.setShowWhenLocked(showWhenLocked);
4542 } finally {
4543 Binder.restoreCallingIdentity(origId);
4544 }
4545 }
4546 }
4547
4548 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004549 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4550 synchronized (mGlobalLock) {
4551 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4552 if (r == null) {
4553 return;
4554 }
4555 final long origId = Binder.clearCallingIdentity();
4556 try {
4557 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4558 } finally {
4559 Binder.restoreCallingIdentity(origId);
4560 }
4561 }
4562 }
4563
4564 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004565 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4566 synchronized (mGlobalLock) {
4567 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4568 if (r == null) {
4569 return;
4570 }
4571 final long origId = Binder.clearCallingIdentity();
4572 try {
4573 r.setTurnScreenOn(turnScreenOn);
4574 } finally {
4575 Binder.restoreCallingIdentity(origId);
4576 }
4577 }
4578 }
4579
4580 @Override
4581 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004582 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004583 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004584 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004585 synchronized (mGlobalLock) {
4586 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4587 if (r == null) {
4588 return;
4589 }
4590 final long origId = Binder.clearCallingIdentity();
4591 try {
4592 r.registerRemoteAnimations(definition);
4593 } finally {
4594 Binder.restoreCallingIdentity(origId);
4595 }
4596 }
4597 }
4598
4599 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004600 public void unregisterRemoteAnimations(IBinder token) {
4601 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4602 "unregisterRemoteAnimations");
4603 synchronized (mGlobalLock) {
4604 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4605 if (r == null) {
4606 return;
4607 }
4608 final long origId = Binder.clearCallingIdentity();
4609 try {
4610 r.unregisterRemoteAnimations();
4611 } finally {
4612 Binder.restoreCallingIdentity(origId);
4613 }
4614 }
4615 }
4616
4617 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004618 public void registerRemoteAnimationForNextActivityStart(String packageName,
4619 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004620 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004621 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004622 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004623 synchronized (mGlobalLock) {
4624 final long origId = Binder.clearCallingIdentity();
4625 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004626 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004627 packageName, adapter);
4628 } finally {
4629 Binder.restoreCallingIdentity(origId);
4630 }
4631 }
4632 }
4633
Evan Rosky966759f2019-01-15 10:33:58 -08004634 @Override
4635 public void registerRemoteAnimationsForDisplay(int displayId,
4636 RemoteAnimationDefinition definition) {
4637 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4638 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004639 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004640 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004641 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004642 if (display == null) {
4643 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4644 return;
4645 }
4646 final long origId = Binder.clearCallingIdentity();
4647 try {
4648 display.mDisplayContent.registerRemoteAnimations(definition);
4649 } finally {
4650 Binder.restoreCallingIdentity(origId);
4651 }
4652 }
4653 }
4654
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004655 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4656 @Override
4657 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4658 synchronized (mGlobalLock) {
4659 final long origId = Binder.clearCallingIdentity();
4660 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004661 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004662 } finally {
4663 Binder.restoreCallingIdentity(origId);
4664 }
4665 }
4666 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004667
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004668 @Override
4669 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004670 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004671 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004672 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004673 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004674 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004675 }
4676 }
4677
4678 @Override
4679 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004680 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004681 != PERMISSION_GRANTED) {
4682 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4683 + Binder.getCallingPid()
4684 + ", uid=" + Binder.getCallingUid()
4685 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4686 Slog.w(TAG, msg);
4687 throw new SecurityException(msg);
4688 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004689 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004690 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004691 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004692 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004693 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004694 }
4695 }
4696
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004697 @Override
4698 public void stopAppSwitches() {
4699 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4700 synchronized (mGlobalLock) {
4701 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004702 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004703 mDidAppSwitch = false;
4704 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4705 }
4706 }
4707
4708 @Override
4709 public void resumeAppSwitches() {
4710 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4711 synchronized (mGlobalLock) {
4712 // Note that we don't execute any pending app switches... we will
4713 // let those wait until either the timeout, or the next start
4714 // activity request.
4715 mAppSwitchesAllowedTime = 0;
4716 }
4717 }
4718
Ricky Wai906af482019-06-03 17:25:28 +01004719 long getLastStopAppSwitchesTime() {
4720 return mLastStopAppSwitchesTime;
4721 }
4722
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004723 void onStartActivitySetDidAppSwitch() {
4724 if (mDidAppSwitch) {
4725 // This is the second allowed switch since we stopped switches, so now just generally
4726 // allow switches. Use case:
4727 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4728 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4729 // anyone to switch again).
4730 mAppSwitchesAllowedTime = 0;
4731 } else {
4732 mDidAppSwitch = true;
4733 }
4734 }
4735
4736 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004737 boolean shouldDisableNonVrUiLocked() {
4738 return mVrController.shouldDisableNonVrUiLocked();
4739 }
4740
Wale Ogunwale53783742018-09-16 10:21:51 -07004741 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004742 // 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 +00004743 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004744 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004745 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4746 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004747 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004748 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004749 }
4750 mH.post(() -> {
4751 if (!mVrController.onVrModeChanged(r)) {
4752 return;
4753 }
4754 synchronized (mGlobalLock) {
4755 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4756 mWindowManager.disableNonVrUi(disableNonVrUi);
4757 if (disableNonVrUi) {
4758 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4759 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004760 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004761 }
4762 }
4763 });
4764 }
4765
Wale Ogunwale53783742018-09-16 10:21:51 -07004766 @Override
4767 public int getPackageScreenCompatMode(String packageName) {
4768 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4769 synchronized (mGlobalLock) {
4770 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4771 }
4772 }
4773
4774 @Override
4775 public void setPackageScreenCompatMode(String packageName, int mode) {
4776 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4777 "setPackageScreenCompatMode");
4778 synchronized (mGlobalLock) {
4779 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4780 }
4781 }
4782
4783 @Override
4784 public boolean getPackageAskScreenCompat(String packageName) {
4785 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4786 synchronized (mGlobalLock) {
4787 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4788 }
4789 }
4790
4791 @Override
4792 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4793 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4794 "setPackageAskScreenCompat");
4795 synchronized (mGlobalLock) {
4796 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4797 }
4798 }
4799
Wale Ogunwale64258362018-10-16 15:13:37 -07004800 public static String relaunchReasonToString(int relaunchReason) {
4801 switch (relaunchReason) {
4802 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4803 return "window_resize";
4804 case RELAUNCH_REASON_FREE_RESIZE:
4805 return "free_resize";
4806 default:
4807 return null;
4808 }
4809 }
4810
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004811 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004812 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004813 }
4814
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004815 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004816 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004817 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4818 }
4819
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004820 boolean isKeyguardLocked() {
4821 return mKeyguardController.isKeyguardLocked();
4822 }
4823
Garfield Tan01548632018-11-27 10:15:48 -08004824 /**
4825 * Clears launch params for the given package.
4826 * @param packageNames the names of the packages of which the launch params are to be cleared
4827 */
4828 @Override
4829 public void clearLaunchParamsForPackages(List<String> packageNames) {
4830 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4831 "clearLaunchParamsForPackages");
4832 synchronized (mGlobalLock) {
4833 for (int i = 0; i < packageNames.size(); ++i) {
4834 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4835 }
4836 }
4837 }
4838
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004839 /**
4840 * Makes the display with the given id a single task instance display. I.e the display can only
4841 * contain one task.
4842 */
4843 @Override
4844 public void setDisplayToSingleTaskInstance(int displayId) {
4845 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4846 "setDisplayToSingleTaskInstance");
4847 final long origId = Binder.clearCallingIdentity();
4848 try {
Louis Chang677921f2019-12-06 16:44:24 +08004849 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004850 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004851 if (display != null) {
4852 display.setDisplayToSingleTaskInstance();
4853 }
4854 } finally {
4855 Binder.restoreCallingIdentity(origId);
4856 }
4857 }
4858
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004859 /**
4860 * Requests that an activity should enter picture-in-picture mode if possible.
4861 */
4862 @Override
4863 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4864 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4865 "requestPictureInPictureMode");
4866 final long origId = Binder.clearCallingIdentity();
4867 try {
4868 synchronized (mGlobalLock) {
4869 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4870 if (activity == null) {
4871 return;
4872 }
4873
4874 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4875 "requestPictureInPictureMode", /* beforeStopping */ false);
4876 if (!canEnterPictureInPicture) {
4877 throw new IllegalStateException(
4878 "Requested PIP on an activity that doesn't support it");
4879 }
4880
4881 try {
4882 final ClientTransaction transaction = ClientTransaction.obtain(
4883 activity.app.getThread(),
4884 activity.token);
4885 transaction.addCallback(EnterPipRequestedItem.obtain());
4886 getLifecycleManager().scheduleTransaction(transaction);
4887 } catch (Exception e) {
4888 Slog.w(TAG, "Failed to send enter pip requested item: "
4889 + activity.intent.getComponent(), e);
4890 }
4891 }
4892 } finally {
4893 Binder.restoreCallingIdentity(origId);
4894 }
4895 }
4896
Wale Ogunwale31913b52018-10-13 08:29:31 -07004897 void dumpLastANRLocked(PrintWriter pw) {
4898 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4899 if (mLastANRState == null) {
4900 pw.println(" <no ANR has occurred since boot>");
4901 } else {
4902 pw.println(mLastANRState);
4903 }
4904 }
4905
4906 void dumpLastANRTracesLocked(PrintWriter pw) {
4907 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4908
4909 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4910 if (ArrayUtils.isEmpty(files)) {
4911 pw.println(" <no ANR has occurred since boot>");
4912 return;
4913 }
4914 // Find the latest file.
4915 File latest = null;
4916 for (File f : files) {
4917 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4918 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004919 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004920 }
4921 pw.print("File: ");
4922 pw.print(latest.getName());
4923 pw.println();
4924 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4925 String line;
4926 while ((line = in.readLine()) != null) {
4927 pw.println(line);
4928 }
4929 } catch (IOException e) {
4930 pw.print("Unable to read: ");
4931 pw.print(e);
4932 pw.println();
4933 }
4934 }
4935
4936 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4937 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4938 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4939 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4940 }
4941
4942 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4943 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4944 pw.println(header);
4945
Louis Chang149d5c82019-12-30 09:47:39 +08004946 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004947 dumpPackage);
4948 boolean needSep = printedAnything;
4949
4950 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08004951 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004952 " ResumedActivity: ");
4953 if (printed) {
4954 printedAnything = true;
4955 needSep = false;
4956 }
4957
4958 if (dumpPackage == null) {
4959 if (needSep) {
4960 pw.println();
4961 }
4962 printedAnything = true;
4963 mStackSupervisor.dump(pw, " ");
Winson Chung268eccb2020-03-26 13:43:44 -07004964 mTaskOrganizerController.dump(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004965 }
4966
4967 if (!printedAnything) {
4968 pw.println(" (nothing)");
4969 }
4970 }
4971
4972 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004973 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08004974 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004975 pw.println(" ");
4976 }
4977
4978 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4979 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4980 getActivityStartController().dump(pw, "", dumpPackage);
4981 }
4982
4983 /**
4984 * There are three things that cmd can be:
4985 * - a flattened component name that matches an existing activity
4986 * - the cmd arg isn't the flattened component name of an existing activity:
4987 * dump all activity whose component contains the cmd as a substring
4988 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004989 * <p>
4990 * The caller should not hold lock when calling this method because it will wait for the
4991 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004992 *
4993 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4994 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4995 */
4996 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4997 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4998 ArrayList<ActivityRecord> activities;
4999
5000 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005001 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005002 dumpFocusedStackOnly);
5003 }
5004
5005 if (activities.size() <= 0) {
5006 return false;
5007 }
5008
5009 String[] newArgs = new String[args.length - opti];
5010 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5011
Louis Changcdec0802019-11-11 11:45:07 +08005012 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005013 boolean needSep = false;
5014 for (int i = activities.size() - 1; i >= 0; i--) {
5015 ActivityRecord r = activities.get(i);
5016 if (needSep) {
5017 pw.println();
5018 }
5019 needSep = true;
5020 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005021 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005022 if (lastTask != task) {
5023 lastTask = task;
5024 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005025 pw.print(" id="); pw.print(lastTask.mTaskId);
5026 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005027 if (dumpAll) {
5028 lastTask.dump(pw, " ");
5029 }
5030 }
5031 }
5032 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5033 }
5034 return true;
5035 }
5036
5037 /**
5038 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5039 * there is a thread associated with the activity.
5040 */
5041 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5042 final ActivityRecord r, String[] args, boolean dumpAll) {
5043 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005044 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005045 synchronized (mGlobalLock) {
5046 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5047 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5048 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005049 if (r.hasProcess()) {
5050 pw.println(r.app.getPid());
5051 appThread = r.app.getThread();
5052 } else {
5053 pw.println("(not running)");
5054 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005055 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005056 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005057 }
5058 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005059 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005060 // flush anything that is already in the PrintWriter since the thread is going
5061 // to write to the file descriptor directly
5062 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005063 try (TransferPipe tp = new TransferPipe()) {
5064 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5065 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005066 } catch (IOException e) {
5067 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5068 } catch (RemoteException e) {
5069 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5070 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005071 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005072 }
5073
sanryhuang498e77e2018-12-06 14:57:01 +08005074 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5075 boolean testPssMode) {
5076 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5077 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5078 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005079 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005080 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5081 st.toString());
5082 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005083 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5084 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5085 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005086 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5087 testPssMode);
5088 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005089 }
5090
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005091 int getCurrentUserId() {
5092 return mAmInternal.getCurrentUserId();
5093 }
5094
5095 private void enforceNotIsolatedCaller(String caller) {
5096 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5097 throw new SecurityException("Isolated process not allowed to call " + caller);
5098 }
5099 }
5100
Wale Ogunwalef6733932018-06-27 05:14:34 -07005101 public Configuration getConfiguration() {
5102 Configuration ci;
5103 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005104 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005105 ci.userSetLocale = false;
5106 }
5107 return ci;
5108 }
5109
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005110 /**
5111 * Current global configuration information. Contains general settings for the entire system,
5112 * also corresponds to the merged configuration of the default display.
5113 */
5114 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005115 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005116 // while initializing process record for system, see {@link
5117 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005118 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005119 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005120 }
5121
5122 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5123 boolean initLocale) {
5124 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5125 }
5126
5127 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5128 boolean initLocale, boolean deferResume) {
5129 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5130 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5131 UserHandle.USER_NULL, deferResume);
5132 }
5133
Wale Ogunwale59507092018-10-29 09:00:30 -07005134 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005135 final long origId = Binder.clearCallingIdentity();
5136 try {
5137 synchronized (mGlobalLock) {
5138 updateConfigurationLocked(values, null, false, true, userId,
5139 false /* deferResume */);
5140 }
5141 } finally {
5142 Binder.restoreCallingIdentity(origId);
5143 }
5144 }
5145
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005146 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5147 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5148 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5149 deferResume, null /* result */);
5150 }
5151
5152 /**
5153 * Do either or both things: (1) change the current configuration, and (2)
5154 * make sure the given activity is running with the (now) current
5155 * configuration. Returns true if the activity has been left running, or
5156 * false if <var>starting</var> is being destroyed to match the new
5157 * configuration.
5158 *
5159 * @param userId is only used when persistent parameter is set to true to persist configuration
5160 * for that particular user
5161 */
5162 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5163 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5164 ActivityTaskManagerService.UpdateConfigurationResult result) {
5165 int changes = 0;
5166 boolean kept = true;
5167
Riddle Hsua0022cd2019-09-09 21:12:41 +08005168 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005169 try {
5170 if (values != null) {
5171 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5172 deferResume);
5173 }
5174
5175 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5176 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005177 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005178 }
5179
5180 if (result != null) {
5181 result.changes = changes;
5182 result.activityRelaunched = !kept;
5183 }
5184 return kept;
5185 }
5186
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005187 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005188 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005189 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005190
Louis Chang677921f2019-12-06 16:44:24 +08005191 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005192 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005193
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005194 mTempConfig.setTo(getGlobalConfiguration());
5195 final int changes = mTempConfig.updateFrom(values);
5196 if (changes == 0) {
5197 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5198 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5199 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5200 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005201 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005202 return 0;
5203 }
5204
5205 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5206 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005207 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005208 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005209 values.colorMode,
5210 values.densityDpi,
5211 values.fontScale,
5212 values.hardKeyboardHidden,
5213 values.keyboard,
5214 values.keyboardHidden,
5215 values.mcc,
5216 values.mnc,
5217 values.navigation,
5218 values.navigationHidden,
5219 values.orientation,
5220 values.screenHeightDp,
5221 values.screenLayout,
5222 values.screenWidthDp,
5223 values.smallestScreenWidthDp,
5224 values.touchscreen,
5225 values.uiMode);
5226
5227
5228 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5229 final LocaleList locales = values.getLocales();
5230 int bestLocaleIndex = 0;
5231 if (locales.size() > 1) {
5232 if (mSupportedSystemLocales == null) {
5233 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5234 }
5235 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5236 }
5237 SystemProperties.set("persist.sys.locale",
5238 locales.get(bestLocaleIndex).toLanguageTag());
5239 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005240
5241 final Message m = PooledLambda.obtainMessage(
5242 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5243 locales.get(bestLocaleIndex));
5244 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005245 }
5246
Yunfan Chen75157d72018-07-27 14:47:21 +09005247 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005248
5249 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005250 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005251
5252 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5253 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005254 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005255
5256 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005257 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005258
5259 AttributeCache ac = AttributeCache.instance();
5260 if (ac != null) {
5261 ac.updateConfiguration(mTempConfig);
5262 }
5263
5264 // Make sure all resources in our process are updated right now, so that anyone who is going
5265 // to retrieve resource values after we return will be sure to get the new ones. This is
5266 // especially important during boot, where the first config change needs to guarantee all
5267 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005268 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005269
5270 // We need another copy of global config because we're scheduling some calls instead of
5271 // running them in place. We need to be sure that object we send will be handled unchanged.
5272 final Configuration configCopy = new Configuration(mTempConfig);
5273 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005274 final Message msg = PooledLambda.obtainMessage(
5275 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5276 this, userId, configCopy);
5277 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005278 }
5279
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005280 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5281 for (int i = pidMap.size() - 1; i >= 0; i--) {
5282 final int pid = pidMap.keyAt(i);
5283 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005284 if (DEBUG_CONFIGURATION) {
5285 Slog.v(TAG_CONFIGURATION, "Update process config of "
5286 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005287 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005288 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005289 }
5290
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005291 final Message msg = PooledLambda.obtainMessage(
5292 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5293 mAmInternal, changes, initLocale);
5294 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005295
5296 // Override configuration of the default display duplicates global config, so we need to
5297 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005298 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005299 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005300
5301 return changes;
5302 }
5303
Riddle Hsua0022cd2019-09-09 21:12:41 +08005304 /** @see WindowSurfacePlacer#deferLayout */
5305 void deferWindowLayout() {
5306 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5307 // Reset the reasons at the first entrance because we only care about the changes in the
5308 // deferred scope.
5309 mLayoutReasons = 0;
5310 }
5311
5312 mWindowManager.mWindowPlacerLocked.deferLayout();
5313 }
5314
5315 /** @see WindowSurfacePlacer#continueLayout */
5316 void continueWindowLayout() {
5317 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5318 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5319 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5320 }
5321 }
5322
5323 /**
5324 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5325 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5326 * defer count is gone.
5327 */
5328 void addWindowLayoutReasons(@LayoutReason int reasons) {
5329 mLayoutReasons |= reasons;
5330 }
5331
Wale Ogunwalef6733932018-06-27 05:14:34 -07005332 private void updateEventDispatchingLocked(boolean booted) {
5333 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5334 }
5335
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005336 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5337 final ContentResolver resolver = mContext.getContentResolver();
5338 Settings.System.putConfigurationForUser(resolver, config, userId);
5339 }
5340
5341 private void sendLocaleToMountDaemonMsg(Locale l) {
5342 try {
5343 IBinder service = ServiceManager.getService("mount");
5344 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5345 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5346 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5347 } catch (RemoteException e) {
5348 Log.e(TAG, "Error storing locale for decryption UI", e);
5349 }
5350 }
5351
Alison Cichowlas3e340502018-08-07 17:15:01 -04005352 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5353 mStartActivitySources.remove(permissionToken);
5354 mExpiredStartAsCallerTokens.add(permissionToken);
5355 }
5356
5357 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5358 mExpiredStartAsCallerTokens.remove(permissionToken);
5359 }
5360
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005361 boolean isActivityStartsLoggingEnabled() {
5362 return mAmInternal.isActivityStartsLoggingEnabled();
5363 }
5364
Michal Karpinski8596ded2018-11-14 14:43:48 +00005365 boolean isBackgroundActivityStartsEnabled() {
5366 return mAmInternal.isBackgroundActivityStartsEnabled();
5367 }
5368
Wale Ogunwalef6733932018-06-27 05:14:34 -07005369 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005370 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005371 mWindowManager.enableScreenAfterBoot();
5372
5373 synchronized (mGlobalLock) {
5374 updateEventDispatchingLocked(booted);
5375 }
5376 }
5377
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005378 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5379 if (r == null || !r.hasProcess()) {
5380 return KEY_DISPATCHING_TIMEOUT_MS;
5381 }
5382 return getInputDispatchingTimeoutLocked(r.app);
5383 }
5384
5385 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005386 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005387 }
5388
Wale Ogunwalef6733932018-06-27 05:14:34 -07005389 /**
5390 * Decide based on the configuration whether we should show the ANR,
5391 * crash, etc dialogs. The idea is that if there is no affordance to
5392 * press the on-screen buttons, or the user experience would be more
5393 * greatly impacted than the crash itself, we shouldn't show the dialog.
5394 *
5395 * A thought: SystemUI might also want to get told about this, the Power
5396 * dialog / global actions also might want different behaviors.
5397 */
5398 private void updateShouldShowDialogsLocked(Configuration config) {
5399 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5400 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5401 && config.navigation == Configuration.NAVIGATION_NONAV);
5402 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5403 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5404 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5405 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5406 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5407 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5408 HIDE_ERROR_DIALOGS, 0) != 0;
5409 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5410 }
5411
5412 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5413 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5414 FONT_SCALE, 1.0f, userId);
5415
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005416 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005417 if (getGlobalConfiguration().fontScale == scaleFactor) {
5418 return;
5419 }
5420
5421 final Configuration configuration
5422 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5423 configuration.fontScale = scaleFactor;
5424 updatePersistentConfiguration(configuration, userId);
5425 }
5426 }
5427
5428 // Actually is sleeping or shutting down or whatever else in the future
5429 // is an inactive state.
5430 boolean isSleepingOrShuttingDownLocked() {
5431 return isSleepingLocked() || mShuttingDown;
5432 }
5433
5434 boolean isSleepingLocked() {
5435 return mSleeping;
5436 }
5437
Riddle Hsu16567132018-08-16 21:37:47 +08005438 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005439 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005440 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005441 if (task.isActivityTypeStandard()) {
5442 if (mCurAppTimeTracker != r.appTimeTracker) {
5443 // We are switching app tracking. Complete the current one.
5444 if (mCurAppTimeTracker != null) {
5445 mCurAppTimeTracker.stop();
5446 mH.obtainMessage(
5447 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005448 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005449 mCurAppTimeTracker = null;
5450 }
5451 if (r.appTimeTracker != null) {
5452 mCurAppTimeTracker = r.appTimeTracker;
5453 startTimeTrackingFocusedActivityLocked();
5454 }
5455 } else {
5456 startTimeTrackingFocusedActivityLocked();
5457 }
5458 } else {
5459 r.appTimeTracker = null;
5460 }
5461 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5462 // TODO: Probably not, because we don't want to resume voice on switching
5463 // back to this activity
5464 if (task.voiceInteractor != null) {
5465 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5466 } else {
5467 finishRunningVoiceLocked();
5468
5469 if (mLastResumedActivity != null) {
5470 final IVoiceInteractionSession session;
5471
Louis Changcdec0802019-11-11 11:45:07 +08005472 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005473 if (lastResumedActivityTask != null
5474 && lastResumedActivityTask.voiceSession != null) {
5475 session = lastResumedActivityTask.voiceSession;
5476 } else {
5477 session = mLastResumedActivity.voiceSession;
5478 }
5479
5480 if (session != null) {
5481 // We had been in a voice interaction session, but now focused has
5482 // move to something different. Just finish the session, we can't
5483 // return to it and retain the proper state and synchronization with
5484 // the voice interaction service.
5485 finishVoiceTask(session);
5486 }
5487 }
5488 }
5489
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005490 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5491 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005492 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005493 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5494
Wale Ogunwalef6733932018-06-27 05:14:34 -07005495 updateResumedAppTrace(r);
5496 mLastResumedActivity = r;
5497
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005498 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005499
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005500 if (prevTask == null || task != prevTask) {
5501 if (prevTask != null) {
5502 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5503 }
5504 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5505 }
5506
Wale Ogunwalef6733932018-06-27 05:14:34 -07005507 applyUpdateLockStateLocked(r);
5508 applyUpdateVrModeLocked(r);
5509
Jeff Changd136e772019-11-05 20:33:52 +08005510 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005511 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005512 r == null ? "NULL" : r.shortComponentName,
5513 reason);
5514 }
5515
5516 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5517 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005518 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005519 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005520 updateSleepIfNeededLocked();
5521 return token;
5522 }
5523 }
5524
5525 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005526 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005527 final boolean wasSleeping = mSleeping;
5528 boolean updateOomAdj = false;
5529
5530 if (!shouldSleep) {
5531 // If wasSleeping is true, we need to wake up activity manager state from when
5532 // we started sleeping. In either case, we need to apply the sleep tokens, which
5533 // will wake up stacks or put them to sleep as appropriate.
5534 if (wasSleeping) {
5535 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005536 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5537 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005538 startTimeTrackingFocusedActivityLocked();
5539 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005540 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005541 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5542 }
Louis Chang149d5c82019-12-30 09:47:39 +08005543 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005544 if (wasSleeping) {
5545 updateOomAdj = true;
5546 }
5547 } else if (!mSleeping && shouldSleep) {
5548 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005549 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5550 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005551 if (mCurAppTimeTracker != null) {
5552 mCurAppTimeTracker.stop();
5553 }
5554 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005555 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005556 mStackSupervisor.goingToSleepLocked();
5557 updateResumedAppTrace(null /* resumed */);
5558 updateOomAdj = true;
5559 }
5560 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005561 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005562 }
5563 }
5564
5565 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005566 mH.removeCallbacks(mUpdateOomAdjRunnable);
5567 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005568 }
5569
Wale Ogunwale53783742018-09-16 10:21:51 -07005570 void updateCpuStats() {
5571 mH.post(mAmInternal::updateCpuStats);
5572 }
5573
Hui Yu03d12402018-12-06 18:00:37 -08005574 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5575 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005576 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5577 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005578 mH.sendMessage(m);
5579 }
5580
Hui Yu03d12402018-12-06 18:00:37 -08005581 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005582 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005583 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005584 if (task != null) {
5585 final ActivityRecord rootActivity = task.getRootActivity();
5586 if (rootActivity != null) {
5587 taskRoot = rootActivity.mActivityComponent;
5588 }
5589 }
5590
Hui Yu03d12402018-12-06 18:00:37 -08005591 final Message m = PooledLambda.obtainMessage(
5592 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005593 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005594 mH.sendMessage(m);
5595 }
5596
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005597 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5598 String hostingType) {
5599 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005600 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5601 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005602 + activity.processName);
5603 }
5604 // Post message to start process to avoid possible deadlock of calling into AMS with the
5605 // ATMS lock held.
5606 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5607 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5608 isTop, hostingType, activity.intent.getComponent());
5609 mH.sendMessage(m);
5610 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005611 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005612 }
5613 }
5614
Wale Ogunwale53783742018-09-16 10:21:51 -07005615 void setBooting(boolean booting) {
5616 mAmInternal.setBooting(booting);
5617 }
5618
5619 boolean isBooting() {
5620 return mAmInternal.isBooting();
5621 }
5622
5623 void setBooted(boolean booted) {
5624 mAmInternal.setBooted(booted);
5625 }
5626
5627 boolean isBooted() {
5628 return mAmInternal.isBooted();
5629 }
5630
5631 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5632 mH.post(() -> {
5633 if (finishBooting) {
5634 mAmInternal.finishBooting();
5635 }
5636 if (enableScreen) {
5637 mInternal.enableScreenAfterBoot(isBooted());
5638 }
5639 });
5640 }
5641
5642 void setHeavyWeightProcess(ActivityRecord root) {
5643 mHeavyWeightProcess = root.app;
5644 final Message m = PooledLambda.obtainMessage(
5645 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005646 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005647 mH.sendMessage(m);
5648 }
5649
5650 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5651 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5652 return;
5653 }
5654
5655 mHeavyWeightProcess = null;
5656 final Message m = PooledLambda.obtainMessage(
5657 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5658 proc.mUserId);
5659 mH.sendMessage(m);
5660 }
5661
5662 private void cancelHeavyWeightProcessNotification(int userId) {
5663 final INotificationManager inm = NotificationManager.getService();
5664 if (inm == null) {
5665 return;
5666 }
5667 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005668 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005669 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5670 } catch (RuntimeException e) {
5671 Slog.w(TAG, "Error canceling notification for service", e);
5672 } catch (RemoteException e) {
5673 }
5674
5675 }
5676
5677 private void postHeavyWeightProcessNotification(
5678 WindowProcessController proc, Intent intent, int userId) {
5679 if (proc == null) {
5680 return;
5681 }
5682
5683 final INotificationManager inm = NotificationManager.getService();
5684 if (inm == null) {
5685 return;
5686 }
5687
5688 try {
5689 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5690 String text = mContext.getString(R.string.heavy_weight_notification,
5691 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5692 Notification notification =
5693 new Notification.Builder(context,
5694 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5695 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5696 .setWhen(0)
5697 .setOngoing(true)
5698 .setTicker(text)
5699 .setColor(mContext.getColor(
5700 com.android.internal.R.color.system_notification_accent_color))
5701 .setContentTitle(text)
5702 .setContentText(
5703 mContext.getText(R.string.heavy_weight_notification_detail))
5704 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5705 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5706 new UserHandle(userId)))
5707 .build();
5708 try {
5709 inm.enqueueNotificationWithTag("android", "android", null,
5710 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5711 } catch (RuntimeException e) {
5712 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5713 } catch (RemoteException e) {
5714 }
5715 } catch (PackageManager.NameNotFoundException e) {
5716 Slog.w(TAG, "Unable to create context for heavy notification", e);
5717 }
5718
5719 }
5720
Philip P. Moltmannee295092020-02-10 08:46:26 -08005721 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5722 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5723 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005724
5725 ActivityRecord activity = null;
5726 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5727 activity = ActivityRecord.isInStackLocked(token);
5728 if (activity == null) {
5729 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5730 return null;
5731 }
5732 if (activity.finishing) {
5733 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5734 return null;
5735 }
5736 }
5737
5738 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005739 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5740 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005741 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5742 if (noCreate) {
5743 return rec;
5744 }
5745 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5746 if (activity.pendingResults == null) {
5747 activity.pendingResults = new HashSet<>();
5748 }
5749 activity.pendingResults.add(rec.ref);
5750 }
5751 return rec;
5752 }
5753
Andrii Kulian52d255c2018-07-13 11:32:19 -07005754 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005755 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005756 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005757 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5758 mCurAppTimeTracker.start(resumedActivity.packageName);
5759 }
5760 }
5761
5762 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5763 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005764 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005765 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5766 }
5767 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005768 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005769 constructResumedTraceName(resumed.packageName), 0);
5770 }
5771 mTracedResumedActivity = resumed;
5772 }
5773
5774 private String constructResumedTraceName(String packageName) {
5775 return "focused app: " + packageName;
5776 }
5777
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005778 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005779 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005780 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005781 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005782 // mainStack is null during startup.
5783 if (mainStack != null) {
5784 if (changes != 0 && starting == null) {
5785 // If the configuration changed, and the caller is not already
5786 // in the process of starting an activity, then find the top
5787 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005788 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005789 }
5790
5791 if (starting != null) {
5792 kept = starting.ensureActivityConfiguration(changes,
5793 false /* preserveWindow */);
5794 // And we need to make sure at this point that all other activities
5795 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005796 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005797 !PRESERVE_WINDOWS);
5798 }
5799 }
5800
5801 return kept;
5802 }
5803
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005804 void scheduleAppGcsLocked() {
5805 mH.post(() -> mAmInternal.scheduleAppGcs());
5806 }
5807
Wale Ogunwale53783742018-09-16 10:21:51 -07005808 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5809 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5810 }
5811
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005812 /**
5813 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5814 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5815 * on demand.
5816 */
5817 IPackageManager getPackageManager() {
5818 return AppGlobals.getPackageManager();
5819 }
5820
5821 PackageManagerInternal getPackageManagerInternalLocked() {
5822 if (mPmInternal == null) {
5823 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5824 }
5825 return mPmInternal;
5826 }
5827
Darryl L Johnsona0982222020-02-18 18:21:51 -08005828 ComponentName getSysUiServiceComponentLocked() {
5829 if (mSysUiServiceComponent == null) {
5830 final PackageManagerInternal pm = getPackageManagerInternalLocked();
5831 mSysUiServiceComponent = pm.getSystemUiServiceComponent();
5832 }
5833 return mSysUiServiceComponent;
5834 }
5835
Hai Zhangf4da9be2019-05-01 13:46:06 +08005836 PermissionPolicyInternal getPermissionPolicyInternal() {
5837 if (mPermissionPolicyInternal == null) {
5838 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5839 }
5840 return mPermissionPolicyInternal;
5841 }
5842
Wale Ogunwale008163e2018-07-23 23:11:08 -07005843 AppWarnings getAppWarningsLocked() {
5844 return mAppWarnings;
5845 }
5846
Wale Ogunwale214f3482018-10-04 11:00:47 -07005847 Intent getHomeIntent() {
5848 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5849 intent.setComponent(mTopComponent);
5850 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5851 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5852 intent.addCategory(Intent.CATEGORY_HOME);
5853 }
5854 return intent;
5855 }
5856
Chilun2ef71f72018-11-16 17:57:15 +08005857 /**
5858 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5859 * activities.
5860 *
Chilun939b05c2020-02-19 14:50:59 +08005861 * @param preferredPackage Specify a preferred package name, otherwise use the package name
5862 * defined in config_secondaryHomePackage.
Chilun2ef71f72018-11-16 17:57:15 +08005863 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5864 */
5865 Intent getSecondaryHomeIntent(String preferredPackage) {
5866 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005867 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5868 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5869 if (preferredPackage == null || useSystemProvidedLauncher) {
Chilun939b05c2020-02-19 14:50:59 +08005870 // Using the package name stored in config if no preferred package name or forced.
5871 final String secondaryHomePackage = mContext.getResources().getString(
5872 com.android.internal.R.string.config_secondaryHomePackage);
5873 intent.setPackage(secondaryHomePackage);
Chilun2ef71f72018-11-16 17:57:15 +08005874 } else {
5875 intent.setPackage(preferredPackage);
5876 }
5877 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5878 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5879 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5880 }
5881 return intent;
5882 }
5883
Wale Ogunwale214f3482018-10-04 11:00:47 -07005884 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5885 if (info == null) return null;
5886 ApplicationInfo newInfo = new ApplicationInfo(info);
5887 newInfo.initForUser(userId);
5888 return newInfo;
5889 }
5890
Wale Ogunwale9c103022018-10-18 07:44:54 -07005891 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005892 if (uid == SYSTEM_UID) {
5893 // The system gets to run in any process. If there are multiple processes with the same
5894 // uid, just pick the first (this should never happen).
5895 final SparseArray<WindowProcessController> procs =
5896 mProcessNames.getMap().get(processName);
5897 if (procs == null) return null;
5898 final int procCount = procs.size();
5899 for (int i = 0; i < procCount; i++) {
5900 final int procUid = procs.keyAt(i);
5901 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5902 // Don't use an app process or different user process for system component.
5903 continue;
5904 }
5905 return procs.valueAt(i);
5906 }
5907 }
5908
5909 return mProcessNames.get(processName, uid);
5910 }
5911
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005912 WindowProcessController getProcessController(IApplicationThread thread) {
5913 if (thread == null) {
5914 return null;
5915 }
5916
5917 final IBinder threadBinder = thread.asBinder();
5918 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5919 for (int i = pmap.size()-1; i >= 0; i--) {
5920 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5921 for (int j = procs.size() - 1; j >= 0; j--) {
5922 final WindowProcessController proc = procs.valueAt(j);
5923 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5924 return proc;
5925 }
5926 }
5927 }
5928
5929 return null;
5930 }
5931
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005932 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005933 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005934 if (proc == null) return null;
5935 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5936 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005937 }
5938 return null;
5939 }
5940
Riddle Hsua0536432019-02-16 00:38:59 +08005941 int getUidState(int uid) {
5942 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005943 }
5944
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005945 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005946 // A uid is considered to be foreground if it has a visible non-toast window.
5947 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005948 }
5949
Ricky Wai96f5c352019-04-10 18:40:17 +01005950 boolean isDeviceOwner(int uid) {
5951 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005952 }
5953
Ricky Wai96f5c352019-04-10 18:40:17 +01005954 void setDeviceOwnerUid(int uid) {
5955 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005956 }
5957
Wale Ogunwale9de19442018-10-18 19:05:03 -07005958 /**
5959 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5960 * the whitelist
5961 */
5962 String getPendingTempWhitelistTagForUidLocked(int uid) {
5963 return mPendingTempWhitelist.get(uid);
5964 }
5965
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005966 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5967 if (true || Build.IS_USER) {
5968 return;
5969 }
5970
5971 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5972 StrictMode.allowThreadDiskWrites();
5973 try {
5974 File tracesDir = new File("/data/anr");
5975 File tracesFile = null;
5976 try {
5977 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5978
5979 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005980 String timeString =
5981 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5982 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005983 sb.append(": ");
5984 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5985 sb.append(" since ");
5986 sb.append(msg);
5987 FileOutputStream fos = new FileOutputStream(tracesFile);
5988 fos.write(sb.toString().getBytes());
5989 if (app == null) {
5990 fos.write("\n*** No application process!".getBytes());
5991 }
5992 fos.close();
5993 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5994 } catch (IOException e) {
5995 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5996 return;
5997 }
5998
5999 if (app != null && app.getPid() > 0) {
6000 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6001 firstPids.add(app.getPid());
6002 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6003 }
6004
6005 File lastTracesFile = null;
6006 File curTracesFile = null;
6007 for (int i=9; i>=0; i--) {
6008 String name = String.format(Locale.US, "slow%02d.txt", i);
6009 curTracesFile = new File(tracesDir, name);
6010 if (curTracesFile.exists()) {
6011 if (lastTracesFile != null) {
6012 curTracesFile.renameTo(lastTracesFile);
6013 } else {
6014 curTracesFile.delete();
6015 }
6016 }
6017 lastTracesFile = curTracesFile;
6018 }
6019 tracesFile.renameTo(curTracesFile);
6020 } finally {
6021 StrictMode.setThreadPolicy(oldPolicy);
6022 }
6023 }
6024
Michal Karpinskida34cd42019-04-02 19:46:52 +01006025 boolean isAssociatedCompanionApp(int userId, int uid) {
6026 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6027 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006028 return false;
6029 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006030 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006031 }
6032
Issei Suzuki734bc942019-06-05 13:59:52 +02006033 void notifySingleTaskDisplayEmpty(int displayId) {
6034 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6035 }
6036
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006037 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006038 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006039
6040
Wale Ogunwale98875612018-10-12 07:53:02 -07006041 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6042 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006043
Riddle Hsud93a6c42018-11-29 21:50:06 +08006044 H(Looper looper) {
6045 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006046 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006047
6048 @Override
6049 public void handleMessage(Message msg) {
6050 switch (msg.what) {
6051 case REPORT_TIME_TRACKER_MSG: {
6052 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6053 tracker.deliverResult(mContext);
6054 } break;
6055 }
6056 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006057 }
6058
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006059 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006060 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006061
6062 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006063 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006064 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006065
6066 @Override
6067 public void handleMessage(Message msg) {
6068 switch (msg.what) {
6069 case DISMISS_DIALOG_UI_MSG: {
6070 final Dialog d = (Dialog) msg.obj;
6071 d.dismiss();
6072 break;
6073 }
6074 }
6075 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006076 }
6077
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006078 final class LocalService extends ActivityTaskManagerInternal {
6079 @Override
6080 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006081 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006082 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006083 }
6084
6085 @Override
6086 public ComponentName getHomeActivityForUser(int userId) {
6087 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006088 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006089 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006090 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006091 }
6092 }
6093
6094 @Override
6095 public void onLocalVoiceInteractionStarted(IBinder activity,
6096 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6097 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006098 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006099 }
6100 }
6101
6102 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006103 public void notifySingleTaskDisplayDrawn(int displayId) {
6104 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6105 }
6106
6107 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006108 public void notifyAppTransitionFinished() {
6109 synchronized (mGlobalLock) {
6110 mStackSupervisor.notifyAppTransitionDone();
6111 }
6112 }
6113
6114 @Override
6115 public void notifyAppTransitionCancelled() {
6116 synchronized (mGlobalLock) {
6117 mStackSupervisor.notifyAppTransitionDone();
6118 }
6119 }
6120
6121 @Override
6122 public List<IBinder> getTopVisibleActivities() {
6123 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006124 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006125 }
6126 }
6127
6128 @Override
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00006129 public boolean hasResumedActivity(int uid) {
6130 synchronized (mGlobalLock) {
6131 final ArraySet<WindowProcessController> processes = mProcessMap.getProcesses(uid);
6132 for (int i = 0, n = processes.size(); i < n; i++) {
6133 final WindowProcessController process = processes.valueAt(i);
6134 if (process.hasResumedActivity()) {
6135 return true;
6136 }
6137 }
6138 }
6139 return false;
6140 }
6141
6142 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006143 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6144 int userId, Intent[] intents, Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006145 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006146 final String[] resolvedTypes = new String[intents.length];
6147
6148 // UID of the package on user userId.
6149 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6150 // packageUid may not be initialized.
6151 int packageUid = 0;
6152 final long ident = Binder.clearCallingIdentity();
6153
6154 try {
6155 for (int i = 0; i < intents.length; i++) {
6156 resolvedTypes[i] =
6157 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6158 }
6159
6160 packageUid = AppGlobals.getPackageManager().getPackageUid(
6161 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6162 } catch (RemoteException e) {
6163 // Shouldn't happen.
6164 } finally {
6165 Binder.restoreCallingIdentity(ident);
6166 }
6167
Riddle Hsu591bf612019-02-14 17:55:31 +08006168 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006169 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006170 intents, resolvedTypes, null /* resultTo */,
6171 SafeActivityOptions.fromBundle(bOptions), userId,
6172 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6173 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006174 }
6175
6176 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006177 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006178 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6179 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6180 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006181 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006182 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006183 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006184 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006185 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6186 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006187 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006188 }
6189 }
6190
6191 @Override
6192 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006193 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6194 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6195 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6196 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006197 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006198 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006199 synchronized (mGlobalLock) {
6200 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006201 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6202 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6203 reason, validateIncomingUser, originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006204 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006205 }
6206 }
6207
6208 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006209 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006210 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6211 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006212 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006213 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006214 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006215 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006216 false /*validateIncomingUser*/);
6217 }
6218
6219 @Override
lumark588a3e82018-07-20 18:53:54 +08006220 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006221 synchronized (mGlobalLock) {
6222
6223 // We might change the visibilities here, so prepare an empty app transition which
6224 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006225 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006226 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006227 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006228 return;
6229 }
Louis Chang677921f2019-12-06 16:44:24 +08006230 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006231 final boolean wasTransitionSet =
6232 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006233 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006234 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006235 }
Louis Chang149d5c82019-12-30 09:47:39 +08006236 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006237
6238 // If there was a transition set already we don't want to interfere with it as we
6239 // might be starting it too early.
6240 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006241 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006242 }
6243 }
6244 if (callback != null) {
6245 callback.run();
6246 }
6247 }
6248
6249 @Override
6250 public void notifyKeyguardTrustedChanged() {
6251 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006252 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006253 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006254 }
6255 }
6256 }
6257
6258 /**
6259 * Called after virtual display Id is updated by
6260 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6261 * {@param vrVr2dDisplayId}.
6262 */
6263 @Override
6264 public void setVr2dDisplayId(int vr2dDisplayId) {
6265 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6266 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006267 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006268 }
6269 }
6270
6271 @Override
6272 public void setFocusedActivity(IBinder token) {
6273 synchronized (mGlobalLock) {
6274 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6275 if (r == null) {
6276 throw new IllegalArgumentException(
6277 "setFocusedActivity: No activity record matching token=" + token);
6278 }
Louis Chang19443452018-10-09 12:10:21 +08006279 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006280 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006281 }
6282 }
6283 }
6284
6285 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006286 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006287 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006288 }
6289
6290 @Override
6291 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006292 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006293 }
6294
6295 @Override
6296 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006297 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006298 }
6299
6300 @Override
6301 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6302 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6303 }
6304
6305 @Override
6306 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006307 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006308 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006309
6310 @Override
6311 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6312 synchronized (mGlobalLock) {
6313 mActiveVoiceInteractionServiceComponent = component;
6314 }
6315 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006316
6317 @Override
Galia Peycheva480275a2020-03-18 17:33:42 +01006318 public void notifyDreamStateChanged(boolean dreaming) {
6319 synchronized (mGlobalLock) {
6320 mDreaming = dreaming;
6321 }
6322 }
6323
6324 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006325 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6326 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6327 return;
6328 }
6329 synchronized (mGlobalLock) {
6330 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6331 if (types == null) {
6332 if (uid < 0) {
6333 return;
6334 }
6335 types = new ArrayMap<>();
6336 mAllowAppSwitchUids.put(userId, types);
6337 }
6338 if (uid < 0) {
6339 types.remove(type);
6340 } else {
6341 types.put(type, uid);
6342 }
6343 }
6344 }
6345
6346 @Override
6347 public void onUserStopped(int userId) {
6348 synchronized (mGlobalLock) {
6349 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6350 mAllowAppSwitchUids.remove(userId);
6351 }
6352 }
6353
6354 @Override
6355 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6356 synchronized (mGlobalLock) {
6357 return ActivityTaskManagerService.this.isGetTasksAllowed(
6358 caller, callingPid, callingUid);
6359 }
6360 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006361
Riddle Hsua0536432019-02-16 00:38:59 +08006362 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006363 @Override
6364 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006365 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006366 mProcessNames.put(proc.mName, proc.mUid, proc);
6367 }
6368 }
6369
Riddle Hsua0536432019-02-16 00:38:59 +08006370 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006371 @Override
6372 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006373 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006374 mProcessNames.remove(name, uid);
6375 }
6376 }
6377
Riddle Hsua0536432019-02-16 00:38:59 +08006378 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006379 @Override
6380 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006381 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006382 if (proc == mHomeProcess) {
6383 mHomeProcess = null;
6384 }
6385 if (proc == mPreviousProcess) {
6386 mPreviousProcess = null;
6387 }
6388 }
6389 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006390
Riddle Hsua0536432019-02-16 00:38:59 +08006391 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006392 @Override
6393 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006394 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006395 return mTopProcessState;
6396 }
6397 }
6398
Riddle Hsua0536432019-02-16 00:38:59 +08006399 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006400 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006401 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006402 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006403 return proc == mHeavyWeightProcess;
6404 }
6405 }
6406
Riddle Hsua0536432019-02-16 00:38:59 +08006407 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006408 @Override
6409 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006410 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006411 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6412 }
6413 }
6414
6415 @Override
6416 public void finishHeavyWeightApp() {
6417 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006418 if (mHeavyWeightProcess != null) {
6419 mHeavyWeightProcess.finishActivities();
6420 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006421 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6422 mHeavyWeightProcess);
6423 }
6424 }
6425
Galia Peycheva480275a2020-03-18 17:33:42 +01006426 @Override
6427 public boolean isDreaming() {
6428 synchronized (mGlobalLock) {
6429 return mDreaming;
6430 }
6431 }
6432
Riddle Hsua0536432019-02-16 00:38:59 +08006433 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006434 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006435 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006436 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006437 return isSleepingLocked();
6438 }
6439 }
6440
6441 @Override
6442 public boolean isShuttingDown() {
6443 synchronized (mGlobalLock) {
6444 return mShuttingDown;
6445 }
6446 }
6447
6448 @Override
6449 public boolean shuttingDown(boolean booted, int timeout) {
6450 synchronized (mGlobalLock) {
6451 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006452 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006453 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006454 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006455 return mStackSupervisor.shutdownLocked(timeout);
6456 }
6457 }
6458
6459 @Override
6460 public void enableScreenAfterBoot(boolean booted) {
6461 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006462 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006463 mWindowManager.enableScreenAfterBoot();
6464 updateEventDispatchingLocked(booted);
6465 }
6466 }
6467
6468 @Override
6469 public boolean showStrictModeViolationDialog() {
6470 synchronized (mGlobalLock) {
6471 return mShowDialogs && !mSleeping && !mShuttingDown;
6472 }
6473 }
6474
6475 @Override
6476 public void showSystemReadyErrorDialogsIfNeeded() {
6477 synchronized (mGlobalLock) {
6478 try {
6479 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6480 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6481 + " data partition or your device will be unstable.");
6482 mUiHandler.post(() -> {
6483 if (mShowDialogs) {
6484 AlertDialog d = new BaseErrorDialog(mUiContext);
6485 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6486 d.setCancelable(false);
6487 d.setTitle(mUiContext.getText(R.string.android_system_label));
6488 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6489 d.setButton(DialogInterface.BUTTON_POSITIVE,
6490 mUiContext.getText(R.string.ok),
6491 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6492 d.show();
6493 }
6494 });
6495 }
6496 } catch (RemoteException e) {
6497 }
6498
6499 if (!Build.isBuildConsistent()) {
6500 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6501 mUiHandler.post(() -> {
6502 if (mShowDialogs) {
6503 AlertDialog d = new BaseErrorDialog(mUiContext);
6504 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6505 d.setCancelable(false);
6506 d.setTitle(mUiContext.getText(R.string.android_system_label));
6507 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6508 d.setButton(DialogInterface.BUTTON_POSITIVE,
6509 mUiContext.getText(R.string.ok),
6510 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6511 d.show();
6512 }
6513 });
6514 }
6515 }
6516 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006517
6518 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006519 public void onProcessMapped(int pid, WindowProcessController proc) {
6520 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006521 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006522 }
6523 }
6524
6525 @Override
6526 public void onProcessUnMapped(int pid) {
6527 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006528 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006529 }
6530 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006531
6532 @Override
6533 public void onPackageDataCleared(String name) {
6534 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006535 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006536 mAppWarnings.onPackageDataCleared(name);
6537 }
6538 }
6539
6540 @Override
6541 public void onPackageUninstalled(String name) {
6542 synchronized (mGlobalLock) {
6543 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006544 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006545 }
6546 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006547
6548 @Override
6549 public void onPackageAdded(String name, boolean replacing) {
6550 synchronized (mGlobalLock) {
6551 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6552 }
6553 }
6554
6555 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006556 public void onPackageReplaced(ApplicationInfo aInfo) {
6557 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006558 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006559 }
6560 }
6561
6562 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006563 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6564 synchronized (mGlobalLock) {
6565 return compatibilityInfoForPackageLocked(ai);
6566 }
6567 }
6568
Yunfan Chen75157d72018-07-27 14:47:21 +09006569 /**
6570 * Set the corresponding display information for the process global configuration. To be
6571 * called when we need to show IME on a different display.
6572 *
6573 * @param pid The process id associated with the IME window.
6574 * @param displayId The ID of the display showing the IME.
6575 */
6576 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006577 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006578 // Don't update process-level configuration for Multi-Client IME process since other
6579 // IMEs on other displays will also receive this configuration change due to IME
6580 // services use the same application config/context.
6581 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006582
Yunfan Chen75157d72018-07-27 14:47:21 +09006583 if (pid == MY_PID || pid < 0) {
6584 if (DEBUG_CONFIGURATION) {
6585 Slog.w(TAG,
6586 "Trying to update display configuration for system/invalid process.");
6587 }
6588 return;
6589 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006590 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006591 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006592 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006593 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006594 // Call might come when display is not yet added or has been removed.
6595 if (DEBUG_CONFIGURATION) {
6596 Slog.w(TAG, "Trying to update display configuration for non-existing "
6597 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006598 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006599 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006600 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006601 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006602 if (process == null) {
6603 if (DEBUG_CONFIGURATION) {
6604 Slog.w(TAG, "Trying to update display configuration for invalid "
6605 + "process, pid=" + pid);
6606 }
6607 return;
6608 }
lumarkddc77fb2019-06-27 22:22:23 +08006609 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006610 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006611 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006612 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006613
6614 @Override
6615 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006616 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006617 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006618 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006619 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006620 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006621 }
6622 }
6623 }
6624
6625 @Override
6626 public void clearPendingResultForActivity(IBinder activityToken,
6627 WeakReference<PendingIntentRecord> pir) {
6628 synchronized (mGlobalLock) {
6629 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6630 if (r != null && r.pendingResults != null) {
6631 r.pendingResults.remove(pir);
6632 }
6633 }
6634 }
6635
6636 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006637 public ActivityTokens getTopActivityForTask(int taskId) {
6638 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006639 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006640 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006641 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6642 + " Requested task not found");
6643 return null;
6644 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006645 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006646 if (activity == null) {
6647 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6648 + " Requested activity not found");
6649 return null;
6650 }
6651 if (!activity.attachedToProcess()) {
6652 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6653 + activity);
6654 return null;
6655 }
6656 return new ActivityTokens(activity.appToken, activity.assistToken,
6657 activity.app.getThread());
6658 }
6659 }
6660
6661 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006662 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006663 @Nullable String featureId, int callingUid, int userId, IBinder token,
6664 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6665 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006666 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006667 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6668 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006669 }
6670 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006671
6672 @Override
6673 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6674 synchronized (mGlobalLock) {
6675 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6676 if (r == null) {
6677 return null;
6678 }
6679 if (r.mServiceConnectionsHolder == null) {
6680 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6681 ActivityTaskManagerService.this, r);
6682 }
6683
6684 return r.mServiceConnectionsHolder;
6685 }
6686 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006687
6688 @Override
6689 public Intent getHomeIntent() {
6690 synchronized (mGlobalLock) {
6691 return ActivityTaskManagerService.this.getHomeIntent();
6692 }
6693 }
6694
6695 @Override
6696 public boolean startHomeActivity(int userId, String reason) {
6697 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006698 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006699 }
6700 }
6701
6702 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006703 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006704 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006705 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006706 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006707 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006708 }
Chilun8b1f1be2019-03-13 17:14:36 +08006709 }
6710
6711 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006712 public boolean startHomeOnAllDisplays(int userId, String reason) {
6713 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006714 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006715 }
6716 }
6717
Riddle Hsua0536432019-02-16 00:38:59 +08006718 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006719 @Override
6720 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006721 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006722 if (mFactoryTest == FACTORY_TEST_OFF) {
6723 return false;
6724 }
6725 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6726 && wpc.mName.equals(mTopComponent.getPackageName())) {
6727 return true;
6728 }
6729 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6730 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6731 }
6732 }
6733
6734 @Override
6735 public void updateTopComponentForFactoryTest() {
6736 synchronized (mGlobalLock) {
6737 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6738 return;
6739 }
6740 final ResolveInfo ri = mContext.getPackageManager()
6741 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6742 final CharSequence errorMsg;
6743 if (ri != null) {
6744 final ActivityInfo ai = ri.activityInfo;
6745 final ApplicationInfo app = ai.applicationInfo;
6746 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6747 mTopAction = Intent.ACTION_FACTORY_TEST;
6748 mTopData = null;
6749 mTopComponent = new ComponentName(app.packageName, ai.name);
6750 errorMsg = null;
6751 } else {
6752 errorMsg = mContext.getResources().getText(
6753 com.android.internal.R.string.factorytest_not_system);
6754 }
6755 } else {
6756 errorMsg = mContext.getResources().getText(
6757 com.android.internal.R.string.factorytest_no_action);
6758 }
6759 if (errorMsg == null) {
6760 return;
6761 }
6762
6763 mTopAction = null;
6764 mTopData = null;
6765 mTopComponent = null;
6766 mUiHandler.post(() -> {
6767 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6768 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006769 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006770 });
6771 }
6772 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006773
Riddle Hsua0536432019-02-16 00:38:59 +08006774 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006775 @Override
6776 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6777 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006778 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006779 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006780 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006781
6782 wpc.clearRecentTasks();
6783 wpc.clearActivities();
6784
6785 if (wpc.isInstrumenting()) {
6786 finishInstrumentationCallback.run();
6787 }
6788
Jorim Jaggid0752812018-10-16 16:07:20 +02006789 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006790 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006791 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006792 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006793 // If there was nothing to resume, and we are not already restarting
6794 // this process, but there is a visible activity that is hosted by the
6795 // process...then make sure all visible activities are running, taking
6796 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006797 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006798 !PRESERVE_WINDOWS);
6799 }
6800 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006801 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006802 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006803 }
6804 }
6805 }
6806
6807 @Override
6808 public void closeSystemDialogs(String reason) {
6809 enforceNotIsolatedCaller("closeSystemDialogs");
6810
6811 final int pid = Binder.getCallingPid();
6812 final int uid = Binder.getCallingUid();
6813 final long origId = Binder.clearCallingIdentity();
6814 try {
6815 synchronized (mGlobalLock) {
6816 // Only allow this from foreground processes, so that background
6817 // applications can't abuse it to prevent system UI from being shown.
6818 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006819 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006820 if (!proc.isPerceptible()) {
6821 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6822 + " from background process " + proc);
6823 return;
6824 }
6825 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006826 mWindowManager.closeSystemDialogs(reason);
6827
Louis Chang149d5c82019-12-30 09:47:39 +08006828 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006829 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006830 // Call into AM outside the synchronized block.
6831 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006832 } finally {
6833 Binder.restoreCallingIdentity(origId);
6834 }
6835 }
6836
6837 @Override
6838 public void cleanupDisabledPackageComponents(
6839 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6840 synchronized (mGlobalLock) {
6841 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006842 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006843 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006844 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006845 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006846 }
6847
6848 // Clean-up disabled tasks
6849 getRecentTasks().cleanupDisabledPackageTasksLocked(
6850 packageName, disabledClasses, userId);
6851 }
6852 }
6853
6854 @Override
6855 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6856 int userId) {
6857 synchronized (mGlobalLock) {
6858
6859 boolean didSomething =
6860 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006861 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006862 null, doit, evenPersistent, userId);
6863 return didSomething;
6864 }
6865 }
6866
6867 @Override
6868 public void resumeTopActivities(boolean scheduleIdle) {
6869 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006870 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006871 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006872 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006873 }
6874 }
6875 }
6876
Riddle Hsua0536432019-02-16 00:38:59 +08006877 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006878 @Override
6879 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006880 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006881 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6882 }
6883 }
6884
Riddle Hsua0536432019-02-16 00:38:59 +08006885 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006886 @Override
6887 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006888 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006889 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6890 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6891 }
6892 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006893 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006894 } finally {
6895 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6896 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006897 }
6898 }
6899
6900 @Override
6901 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6902 try {
6903 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6904 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6905 }
6906 } catch (RemoteException ex) {
6907 throw new SecurityException("Fail to check is caller a privileged app", ex);
6908 }
6909
6910 synchronized (mGlobalLock) {
6911 final long ident = Binder.clearCallingIdentity();
6912 try {
6913 if (mAmInternal.shouldConfirmCredentials(userId)) {
6914 if (mKeyguardController.isKeyguardLocked()) {
6915 // Showing launcher to avoid user entering credential twice.
6916 startHomeActivity(currentUserId, "notifyLockedProfile");
6917 }
Louis Chang149d5c82019-12-30 09:47:39 +08006918 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006919 }
6920 } finally {
6921 Binder.restoreCallingIdentity(ident);
6922 }
6923 }
6924 }
6925
6926 @Override
6927 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6928 mAmInternal.enforceCallingPermission(
6929 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6930
6931 synchronized (mGlobalLock) {
6932 final long ident = Binder.clearCallingIdentity();
6933 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006934 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6935 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006936 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006937 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6938 UserHandle.CURRENT);
6939 } finally {
6940 Binder.restoreCallingIdentity(ident);
6941 }
6942 }
6943 }
6944
6945 @Override
6946 public void writeActivitiesToProto(ProtoOutputStream proto) {
6947 synchronized (mGlobalLock) {
6948 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006949 mRootWindowContainer.dumpDebug(
6950 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006951 }
6952 }
6953
6954 @Override
6955 public void saveANRState(String reason) {
6956 synchronized (mGlobalLock) {
6957 final StringWriter sw = new StringWriter();
6958 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6959 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6960 if (reason != null) {
6961 pw.println(" Reason: " + reason);
6962 }
6963 pw.println();
6964 getActivityStartController().dump(pw, " ", null);
6965 pw.println();
6966 pw.println("-------------------------------------------------------------------------------");
6967 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6968 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6969 "" /* header */);
6970 pw.println();
6971 pw.close();
6972
6973 mLastANRState = sw.toString();
6974 }
6975 }
6976
6977 @Override
6978 public void clearSavedANRState() {
6979 synchronized (mGlobalLock) {
6980 mLastANRState = null;
6981 }
6982 }
6983
6984 @Override
6985 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6986 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6987 synchronized (mGlobalLock) {
6988 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6989 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6990 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6991 dumpLastANRLocked(pw);
6992 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6993 dumpLastANRTracesLocked(pw);
6994 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6995 dumpActivityStarterLocked(pw, dumpPackage);
6996 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6997 dumpActivityContainersLocked(pw);
6998 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6999 if (getRecentTasks() != null) {
7000 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7001 }
7002 }
7003 }
7004 }
7005
7006 @Override
7007 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7008 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7009 int wakefulness) {
7010 synchronized (mGlobalLock) {
7011 if (mHomeProcess != null && (dumpPackage == null
7012 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7013 if (needSep) {
7014 pw.println();
7015 needSep = false;
7016 }
7017 pw.println(" mHomeProcess: " + mHomeProcess);
7018 }
7019 if (mPreviousProcess != null && (dumpPackage == null
7020 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7021 if (needSep) {
7022 pw.println();
7023 needSep = false;
7024 }
7025 pw.println(" mPreviousProcess: " + mPreviousProcess);
7026 }
7027 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7028 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7029 StringBuilder sb = new StringBuilder(128);
7030 sb.append(" mPreviousProcessVisibleTime: ");
7031 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7032 pw.println(sb);
7033 }
7034 if (mHeavyWeightProcess != null && (dumpPackage == null
7035 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7036 if (needSep) {
7037 pw.println();
7038 needSep = false;
7039 }
7040 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7041 }
7042 if (dumpPackage == null) {
7043 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007044 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007045 }
7046 if (dumpAll) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007047 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7048 if (dumpPackage == null && topFocusedStack != null) {
7049 pw.println(" mConfigWillChange: " + topFocusedStack.mConfigWillChange);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007050 }
7051 if (mCompatModePackages.getPackages().size() > 0) {
7052 boolean printed = false;
7053 for (Map.Entry<String, Integer> entry
7054 : mCompatModePackages.getPackages().entrySet()) {
7055 String pkg = entry.getKey();
7056 int mode = entry.getValue();
7057 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7058 continue;
7059 }
7060 if (!printed) {
7061 pw.println(" mScreenCompatPackages:");
7062 printed = true;
7063 }
7064 pw.println(" " + pkg + ": " + mode);
7065 }
7066 }
7067 }
7068
7069 if (dumpPackage == null) {
7070 pw.println(" mWakefulness="
7071 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007072 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007073 if (mRunningVoice != null) {
7074 pw.println(" mRunningVoice=" + mRunningVoice);
7075 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7076 }
7077 pw.println(" mSleeping=" + mSleeping);
7078 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7079 pw.println(" mVrController=" + mVrController);
7080 }
7081 if (mCurAppTimeTracker != null) {
7082 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7083 }
7084 if (mAllowAppSwitchUids.size() > 0) {
7085 boolean printed = false;
7086 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7087 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7088 for (int j = 0; j < types.size(); j++) {
7089 if (dumpPackage == null ||
7090 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7091 if (needSep) {
7092 pw.println();
7093 needSep = false;
7094 }
7095 if (!printed) {
7096 pw.println(" mAllowAppSwitchUids:");
7097 printed = true;
7098 }
7099 pw.print(" User ");
7100 pw.print(mAllowAppSwitchUids.keyAt(i));
7101 pw.print(": Type ");
7102 pw.print(types.keyAt(j));
7103 pw.print(" = ");
7104 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7105 pw.println();
7106 }
7107 }
7108 }
7109 }
7110 if (dumpPackage == null) {
7111 if (mController != null) {
7112 pw.println(" mController=" + mController
7113 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7114 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007115 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7116 pw.println(" mLaunchingActivityWakeLock="
7117 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007118 }
7119
7120 return needSep;
7121 }
7122 }
7123
7124 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007125 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7126 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007127 synchronized (mGlobalLock) {
7128 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007129 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007130 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7131 if (topFocusedStack != null) {
7132 proto.write(CONFIG_WILL_CHANGE, topFocusedStack.mConfigWillChange);
7133 }
sanryhuang498e77e2018-12-06 14:57:01 +08007134 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7135 if (mRunningVoice != null) {
7136 final long vrToken = proto.start(
7137 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7138 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7139 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007140 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007141 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7142 proto.end(vrToken);
7143 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007144 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007145 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007146 if (mController != null) {
7147 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007148 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7149 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007150 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7151 proto.end(token);
7152 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007153 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7154 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007155 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007156 }
7157
7158 if (mHomeProcess != null && (dumpPackage == null
7159 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007160 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007161 }
7162
7163 if (mPreviousProcess != null && (dumpPackage == null
7164 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007165 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007166 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7167 }
7168
7169 if (mHeavyWeightProcess != null && (dumpPackage == null
7170 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007171 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007172 }
7173
7174 for (Map.Entry<String, Integer> entry
7175 : mCompatModePackages.getPackages().entrySet()) {
7176 String pkg = entry.getKey();
7177 int mode = entry.getValue();
7178 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7179 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7180 proto.write(PACKAGE, pkg);
7181 proto.write(MODE, mode);
7182 proto.end(compatToken);
7183 }
7184 }
7185
7186 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007187 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007188 }
7189
7190 }
7191 }
7192
7193 @Override
7194 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7195 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7196 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007197 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7198 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007199 }
7200
7201 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007202 public void dumpForOom(PrintWriter pw) {
7203 synchronized (mGlobalLock) {
7204 pw.println(" mHomeProcess: " + mHomeProcess);
7205 pw.println(" mPreviousProcess: " + mPreviousProcess);
7206 if (mHeavyWeightProcess != null) {
7207 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7208 }
7209 }
7210 }
7211
7212 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007213 public boolean canGcNow() {
7214 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007215 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007216 }
7217 }
7218
Riddle Hsua0536432019-02-16 00:38:59 +08007219 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007220 @Override
7221 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007222 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007223 if (mRootWindowContainer == null) {
7224 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007225 // oomadj after AMS created.
7226 return null;
7227 }
Louis Chang149d5c82019-12-30 09:47:39 +08007228 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007229 return top != null ? top.app : null;
7230 }
7231 }
7232
Riddle Hsua0536432019-02-16 00:38:59 +08007233 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007234 @Override
7235 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007236 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007237 if (mRootWindowContainer != null) {
7238 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007239 }
7240 }
7241 }
7242
7243 @Override
7244 public void scheduleDestroyAllActivities(String reason) {
7245 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007246 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007247 }
7248 }
7249
7250 @Override
7251 public void removeUser(int userId) {
7252 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007253 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007254 }
7255 }
7256
7257 @Override
7258 public boolean switchUser(int userId, UserState userState) {
7259 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007260 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007261 }
7262 }
7263
7264 @Override
7265 public void onHandleAppCrash(WindowProcessController wpc) {
7266 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007267 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007268 }
7269 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007270
7271 @Override
7272 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7273 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007274 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007275 }
7276 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007277
Riddle Hsua0536432019-02-16 00:38:59 +08007278 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007279 @Override
7280 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007281 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007282 }
7283
Riddle Hsua0536432019-02-16 00:38:59 +08007284 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007285 @Override
7286 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007287 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007288 }
7289
Riddle Hsua0536432019-02-16 00:38:59 +08007290 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007291 @Override
7292 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007293 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007294 }
7295
Riddle Hsua0536432019-02-16 00:38:59 +08007296 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007297 @Override
7298 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007299 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007300 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007301
7302 @Override
7303 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007304 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007305 mPendingTempWhitelist.put(uid, tag);
7306 }
7307 }
7308
7309 @Override
7310 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007311 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007312 mPendingTempWhitelist.remove(uid);
7313 }
7314 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007315
7316 @Override
7317 public boolean handleAppCrashInActivityController(String processName, int pid,
7318 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7319 Runnable killCrashingAppCallback) {
7320 synchronized (mGlobalLock) {
7321 if (mController == null) {
7322 return false;
7323 }
7324
7325 try {
7326 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7327 stackTrace)) {
7328 killCrashingAppCallback.run();
7329 return true;
7330 }
7331 } catch (RemoteException e) {
7332 mController = null;
7333 Watchdog.getInstance().setActivityController(null);
7334 }
7335 return false;
7336 }
7337 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007338
7339 @Override
7340 public void removeRecentTasksByPackageName(String packageName, int userId) {
7341 synchronized (mGlobalLock) {
7342 mRecentTasks.removeTasksByPackageName(packageName, userId);
7343 }
7344 }
7345
7346 @Override
7347 public void cleanupRecentTasksForUser(int userId) {
7348 synchronized (mGlobalLock) {
7349 mRecentTasks.cleanupLocked(userId);
7350 }
7351 }
7352
7353 @Override
7354 public void loadRecentTasksForUser(int userId) {
7355 synchronized (mGlobalLock) {
7356 mRecentTasks.loadUserRecentsLocked(userId);
7357 }
7358 }
7359
7360 @Override
7361 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7362 synchronized (mGlobalLock) {
7363 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7364 }
7365 }
7366
7367 @Override
7368 public void flushRecentTasks() {
7369 mRecentTasks.flush();
7370 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007371
7372 @Override
7373 public WindowProcessController getHomeProcess() {
7374 synchronized (mGlobalLock) {
7375 return mHomeProcess;
7376 }
7377 }
7378
7379 @Override
7380 public WindowProcessController getPreviousProcess() {
7381 synchronized (mGlobalLock) {
7382 return mPreviousProcess;
7383 }
7384 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007385
7386 @Override
7387 public void clearLockedTasks(String reason) {
7388 synchronized (mGlobalLock) {
7389 getLockTaskController().clearLockedTasks(reason);
7390 }
7391 }
7392
7393 @Override
7394 public void updateUserConfiguration() {
7395 synchronized (mGlobalLock) {
7396 final Configuration configuration = new Configuration(getGlobalConfiguration());
7397 final int currentUserId = mAmInternal.getCurrentUserId();
7398 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7399 configuration, currentUserId, Settings.System.canWrite(mContext));
7400 updateConfigurationLocked(configuration, null /* starting */,
7401 false /* initLocale */, false /* persistent */, currentUserId,
7402 false /* deferResume */);
7403 }
7404 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007405
7406 @Override
7407 public boolean canShowErrorDialogs() {
7408 synchronized (mGlobalLock) {
7409 return mShowDialogs && !mSleeping && !mShuttingDown
7410 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7411 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7412 mAmInternal.getCurrentUserId())
7413 && !(UserManager.isDeviceInDemoMode(mContext)
7414 && mAmInternal.getCurrentUser().isDemo());
7415 }
7416 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007417
7418 @Override
7419 public void setProfileApp(String profileApp) {
7420 synchronized (mGlobalLock) {
7421 mProfileApp = profileApp;
7422 }
7423 }
7424
7425 @Override
7426 public void setProfileProc(WindowProcessController wpc) {
7427 synchronized (mGlobalLock) {
7428 mProfileProc = wpc;
7429 }
7430 }
7431
7432 @Override
7433 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7434 synchronized (mGlobalLock) {
7435 mProfilerInfo = profilerInfo;
7436 }
7437 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007438
7439 @Override
7440 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7441 synchronized (mGlobalLock) {
7442 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7443 }
7444 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007445
7446 @Override
Zak Cohen84b43182020-03-09 14:36:01 -07007447 public ActivityManager.TaskSnapshot getTaskSnapshotBlocking(
7448 int taskId, boolean isLowResolution) {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08007449 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution,
Zak Cohen84b43182020-03-09 14:36:01 -07007450 true /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007451 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007452
7453 @Override
7454 public boolean isUidForeground(int uid) {
7455 synchronized (mGlobalLock) {
7456 return ActivityTaskManagerService.this.isUidForeground(uid);
7457 }
7458 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007459
7460 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007461 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007462 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007463 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007464 }
7465 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007466
7467 @Override
7468 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007469 // Translate package names into UIDs
7470 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007471 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007472 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7473 if (uid >= 0) {
7474 result.add(uid);
7475 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007476 }
7477 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007478 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007479 }
7480 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007481 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007482}