blob: 7f1f9c758640e8a6107e9095be27cc1e9ec1bf09 [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 Ogunwale65ebd952018-04-25 15:41:44 -070035import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Evan Rosky73a7fe92019-11-18 18:28:01 -080040import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
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;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700126
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700127import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800128import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700129import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700130import android.annotation.Nullable;
131import android.annotation.UserIdInt;
132import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700133import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700134import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700135import android.app.ActivityOptions;
136import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700137import android.app.ActivityThread;
138import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700139import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100140import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700141import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700142import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700143import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.IApplicationThread;
145import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700146import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400147import android.app.IRequestFinishCallback;
Evan Rosky0037e5f2019-11-05 10:26:24 -0800148import android.app.ITaskOrganizerController;
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;
Galia Peycheva52e89222020-02-18 23:41:43 +0100217import android.service.dreams.DreamManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700218import android.service.voice.IVoiceInteractionSession;
219import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900220import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700221import android.telecom.TelecomManager;
222import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100223import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700224import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700225import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700226import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700227import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700228import android.util.SparseArray;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700229import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700230import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700231import android.view.IRecentsAnimationRunner;
232import android.view.RemoteAnimationAdapter;
233import android.view.RemoteAnimationDefinition;
Evan Roskyaf9f27c2020-02-18 18:58:35 +0000234import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700235import android.view.WindowManager;
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;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700398 /**
399 * This is the process holding the activity the user last visited that is in a different process
400 * from the one they are currently in.
401 */
402 WindowProcessController mPreviousProcess;
403 /** The time at which the previous process was last visible. */
404 long mPreviousProcessVisibleTime;
405
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700406 /** List of intents that were used to start the most recent tasks. */
407 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700408 /** State of external calls telling us if the device is awake or asleep. */
409 private boolean mKeyguardShown = false;
410
411 // Wrapper around VoiceInteractionServiceManager
412 private AssistUtils mAssistUtils;
413
414 // VoiceInteraction session ID that changes for each new request except when
415 // being called for multi-window assist in a single session.
416 private int mViSessionId = 1000;
417
418 // How long to wait in getAssistContextExtras for the activity and foreground services
419 // to respond with the result.
420 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
421
422 // How long top wait when going through the modern assist (which doesn't need to block
423 // on getting this result before starting to launch its UI).
424 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
425
426 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
427 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
428
Alison Cichowlas3e340502018-08-07 17:15:01 -0400429 // Permission tokens are used to temporarily granted a trusted app the ability to call
430 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
431 // showing any appropriate error messages to the user.
432 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
433 10 * MINUTE_IN_MILLIS;
434
435 // How long before the service actually expires a token. This is slightly longer than
436 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
437 // expiration exception.
438 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
439 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
440
441 // How long the service will remember expired tokens, for the purpose of providing error
442 // messaging when a client uses an expired token.
443 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
444 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
445
446 // Activity tokens of system activities that are delegating their call to
447 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
448 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
449
450 // Permission tokens that have expired, but we remember for error reporting.
451 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
452
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700453 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
454
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700455 // Keeps track of the active voice interaction service component, notified from
456 // VoiceInteractionManagerService
457 ComponentName mActiveVoiceInteractionServiceComponent;
458
Michal Karpinskida34cd42019-04-02 19:46:52 +0100459 // A map userId and all its companion app uids
460 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000461
Wale Ogunwalee2172292018-10-25 10:11:10 -0700462 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700463 KeyguardController mKeyguardController;
464 private final ClientLifecycleManager mLifecycleManager;
465 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700466 /** The controller for all operations related to locktask. */
467 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700468 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700469
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700470 boolean mSuppressResizeConfigChanges;
471
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700472 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700473 new UpdateConfigurationResult();
474
475 static final class UpdateConfigurationResult {
476 // Configuration changes that were updated.
477 int changes;
478 // If the activity was relaunched to match the new configuration.
479 boolean activityRelaunched;
480
481 void reset() {
482 changes = 0;
483 activityRelaunched = false;
484 }
485 }
486
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700487 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700488 private int mConfigurationSeq;
489 // To cache the list of supported system locales
490 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700491
492 /**
493 * Temp object used when global and/or display override configuration is updated. It is also
494 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
495 * anyone...
496 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700497 private Configuration mTempConfig = new Configuration();
498
Wale Ogunwalef6733932018-06-27 05:14:34 -0700499 /** Temporary to avoid allocations. */
500 final StringBuilder mStringBuilder = new StringBuilder(256);
501
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700502 // Amount of time after a call to stopAppSwitches() during which we will
503 // prevent further untrusted switches from happening.
504 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
505
506 /**
507 * The time at which we will allow normal application switches again,
508 * after a call to {@link #stopAppSwitches()}.
509 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700510 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511 /**
512 * This is set to true after the first switch after mAppSwitchesAllowedTime
513 * is set; any switches after that will clear the time.
514 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700515 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700516
Ricky Wai906af482019-06-03 17:25:28 +0100517 /**
518 * Last stop app switches time, apps finished before this time cannot start background activity
519 * even if they are in grace period.
520 */
521 private long mLastStopAppSwitchesTime;
522
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700523 IActivityController mController = null;
524 boolean mControllerIsAMonkey = false;
525
Wale Ogunwale214f3482018-10-04 11:00:47 -0700526 final int mFactoryTest;
527
528 /** Used to control how we initialize the service. */
529 ComponentName mTopComponent;
530 String mTopAction = Intent.ACTION_MAIN;
531 String mTopData;
532
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800533 /** Profiling app information. */
534 String mProfileApp = null;
535 WindowProcessController mProfileProc = null;
536 ProfilerInfo mProfilerInfo = null;
537
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700538 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700539 * Dump of the activity state at the time of the last ANR. Cleared after
540 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
541 */
542 String mLastANRState;
543
544 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700545 * Used to retain an update lock when the foreground activity is in
546 * immersive mode.
547 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700548 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700549
550 /**
551 * Packages that are being allowed to perform unrestricted app switches. Mapping is
552 * User -> Type -> uid.
553 */
554 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
555
556 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700557 private int mThumbnailWidth;
558 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700559
560 /**
561 * Flag that indicates if multi-window is enabled.
562 *
563 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
564 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
565 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
566 * At least one of the forms of multi-window must be enabled in order for this flag to be
567 * initialized to 'true'.
568 *
569 * @see #mSupportsSplitScreenMultiWindow
570 * @see #mSupportsFreeformWindowManagement
571 * @see #mSupportsPictureInPicture
572 * @see #mSupportsMultiDisplay
573 */
574 boolean mSupportsMultiWindow;
575 boolean mSupportsSplitScreenMultiWindow;
576 boolean mSupportsFreeformWindowManagement;
577 boolean mSupportsPictureInPicture;
578 boolean mSupportsMultiDisplay;
579 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700580 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700581
582 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
583
584 // VR Vr2d Display Id.
585 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700586
Wale Ogunwalef6733932018-06-27 05:14:34 -0700587 /**
588 * Set while we are wanting to sleep, to prevent any
589 * activities from being started/resumed.
590 *
591 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
592 *
593 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
594 * while in the sleep state until there is a pending transition out of sleep, in which case
595 * mSleeping is set to false, and remains false while awake.
596 *
597 * Whether mSleeping can quickly toggled between true/false without the device actually
598 * display changing states is undefined.
599 */
600 private boolean mSleeping = false;
601
602 /**
603 * The process state used for processes that are running the top activities.
604 * This changes between TOP and TOP_SLEEPING to following mSleeping.
605 */
606 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
607
Riddle Hsua0022cd2019-09-09 21:12:41 +0800608 @Retention(RetentionPolicy.SOURCE)
609 @IntDef({
610 LAYOUT_REASON_CONFIG_CHANGED,
611 LAYOUT_REASON_VISIBILITY_CHANGED,
612 })
613 @interface LayoutReason {}
614 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
615 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
616
617 /** The reasons to perform surface placement. */
618 @LayoutReason
619 private int mLayoutReasons;
620
Wale Ogunwalef6733932018-06-27 05:14:34 -0700621 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
622 // automatically. Important for devices without direct input devices.
623 private boolean mShowDialogs = true;
624
625 /** Set if we are shutting down the system, similar to sleeping. */
626 boolean mShuttingDown = false;
627
628 /**
629 * We want to hold a wake lock while running a voice interaction session, since
630 * this may happen with the screen off and we need to keep the CPU running to
631 * be able to continue to interact with the user.
632 */
633 PowerManager.WakeLock mVoiceWakeLock;
634
635 /**
636 * Set while we are running a voice interaction. This overrides sleeping while it is active.
637 */
638 IVoiceInteractionSession mRunningVoice;
639
640 /**
641 * The last resumed activity. This is identical to the current resumed activity most
642 * of the time but could be different when we're pausing one activity before we resume
643 * another activity.
644 */
645 ActivityRecord mLastResumedActivity;
646
647 /**
648 * The activity that is currently being traced as the active resumed activity.
649 *
650 * @see #updateResumedAppTrace
651 */
652 private @Nullable ActivityRecord mTracedResumedActivity;
653
654 /** If non-null, we are tracking the time the user spends in the currently focused app. */
655 AppTimeTracker mCurAppTimeTracker;
656
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700657 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700658
Wale Ogunwale53783742018-09-16 10:21:51 -0700659 /**
660 * Packages that the user has asked to have run in screen size
661 * compatibility mode instead of filling the screen.
662 */
663 CompatModePackages mCompatModePackages;
664
Wale Ogunwalef6733932018-06-27 05:14:34 -0700665 private FontScaleSettingObserver mFontScaleSettingObserver;
666
Robert Carr8a2f9132019-11-11 15:03:15 -0800667 /**
668 * Stores the registration and state of TaskOrganizers in use.
669 */
Evan Rosky0037e5f2019-11-05 10:26:24 -0800670 TaskOrganizerController mTaskOrganizerController = new TaskOrganizerController(this);
Robert Carr8a2f9132019-11-11 15:03:15 -0800671
Ricky Wai96f5c352019-04-10 18:40:17 +0100672 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000673
Wale Ogunwalef6733932018-06-27 05:14:34 -0700674 private final class FontScaleSettingObserver extends ContentObserver {
675 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
676 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
677
678 public FontScaleSettingObserver() {
679 super(mH);
680 final ContentResolver resolver = mContext.getContentResolver();
681 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
682 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
683 UserHandle.USER_ALL);
684 }
685
686 @Override
Jeff Sharkey8b0cff72020-03-09 15:49:01 -0600687 public void onChange(boolean selfChange, Collection<Uri> uris, int flags,
Riddle Hsu9c024d12020-03-09 16:10:07 +0800688 @UserIdInt int userId) {
689 for (Uri uri : uris) {
690 if (mFontScaleUri.equals(uri)) {
691 updateFontScaleIfNeeded(userId);
692 } else if (mHideErrorDialogsUri.equals(uri)) {
693 synchronized (mGlobalLock) {
694 updateShouldShowDialogsLocked(getGlobalConfiguration());
695 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700696 }
697 }
698 }
699 }
700
Riddle Hsua0536432019-02-16 00:38:59 +0800701 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
702 @Target(ElementType.METHOD)
703 @Retention(RetentionPolicy.SOURCE)
704 @interface HotPath {
705 int NONE = 0;
706 int OOM_ADJUSTMENT = 1;
707 int LRU_UPDATE = 2;
708 int PROCESS_CHANGE = 3;
709 int caller() default NONE;
710 }
711
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800712 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
713 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900714 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800715 mAmInternal.updateOomAdj();
716 }
717 };
718
Charles Chen8d98dd22018-12-26 17:36:54 +0800719 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
720 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700721 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700722 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700723 mSystemThread = ActivityThread.currentActivityThread();
724 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700725 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800726 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700727 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700728 }
729
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700730 public void onSystemReady() {
731 synchronized (mGlobalLock) {
732 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
733 PackageManager.FEATURE_CANT_SAVE_STATE);
734 mAssistUtils = new AssistUtils(mContext);
735 mVrController.onSystemReady();
736 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700737 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700738 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700739 }
740
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700741 public void onInitPowerManagement() {
742 synchronized (mGlobalLock) {
743 mStackSupervisor.initPowerManagement();
744 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
745 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
746 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
747 mVoiceWakeLock.setReferenceCounted(false);
748 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700749 }
750
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700751 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700752 mFontScaleSettingObserver = new FontScaleSettingObserver();
753 }
754
Wale Ogunwale59507092018-10-29 09:00:30 -0700755 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700756 final boolean freeformWindowManagement =
757 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
758 || Settings.Global.getInt(
759 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
760
761 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
762 final boolean supportsPictureInPicture = supportsMultiWindow &&
763 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
764 final boolean supportsSplitScreenMultiWindow =
765 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
766 final boolean supportsMultiDisplay = mContext.getPackageManager()
767 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700768 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
769 final boolean forceResizable = Settings.Global.getInt(
770 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700771 final boolean sizeCompatFreeform = Settings.Global.getInt(
772 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700773
774 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900775 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700776
777 final Configuration configuration = new Configuration();
778 Settings.System.getConfiguration(resolver, configuration);
779 if (forceRtl) {
780 // This will take care of setting the correct layout direction flags
781 configuration.setLayoutDirection(configuration.locale);
782 }
783
784 synchronized (mGlobalLock) {
785 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700786 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700787 final boolean multiWindowFormEnabled = freeformWindowManagement
788 || supportsSplitScreenMultiWindow
789 || supportsPictureInPicture
790 || supportsMultiDisplay;
791 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
792 mSupportsMultiWindow = true;
793 mSupportsFreeformWindowManagement = freeformWindowManagement;
794 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
795 mSupportsPictureInPicture = supportsPictureInPicture;
796 mSupportsMultiDisplay = supportsMultiDisplay;
797 } else {
798 mSupportsMultiWindow = false;
799 mSupportsFreeformWindowManagement = false;
800 mSupportsSplitScreenMultiWindow = false;
801 mSupportsPictureInPicture = false;
802 mSupportsMultiDisplay = false;
803 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700804 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700805 // This happens before any activities are started, so we can change global configuration
806 // in-place.
807 updateConfigurationLocked(configuration, null, true);
808 final Configuration globalConfig = getGlobalConfiguration();
809 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
810
811 // Load resources only after the current configuration has been set.
812 final Resources res = mContext.getResources();
813 mThumbnailWidth = res.getDimensionPixelSize(
814 com.android.internal.R.dimen.thumbnail_width);
815 mThumbnailHeight = res.getDimensionPixelSize(
816 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700817 }
818 }
819
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800820 public WindowManagerGlobalLock getGlobalLock() {
821 return mGlobalLock;
822 }
823
Yunfan Chen585f2932019-01-29 16:04:45 +0900824 /** For test purpose only. */
825 @VisibleForTesting
826 public ActivityTaskManagerInternal getAtmInternal() {
827 return mInternal;
828 }
829
Riddle Hsud93a6c42018-11-29 21:50:06 +0800830 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
831 Looper looper) {
832 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700833 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700834 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700835 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800836 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700837 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700838 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700839 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700840
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700841 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700842 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700843 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700844 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700845 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700846 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700847 mKeyguardController = mStackSupervisor.getKeyguardController();
848 }
849
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700850 public void onActivityManagerInternalAdded() {
851 synchronized (mGlobalLock) {
852 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
853 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
854 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700855 }
856
Yunfan Chen75157d72018-07-27 14:47:21 +0900857 int increaseConfigurationSeqLocked() {
858 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
859 return mConfigurationSeq;
860 }
861
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700862 protected ActivityStackSupervisor createStackSupervisor() {
863 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
864 supervisor.initialize();
865 return supervisor;
866 }
867
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800868 protected AppWarnings createAppWarnings(
869 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
870 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
871 }
872
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700873 public void setWindowManager(WindowManagerService wm) {
874 synchronized (mGlobalLock) {
875 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800876 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800877 mTempConfig.setToDefaults();
878 mTempConfig.setLocales(LocaleList.getDefault());
879 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800880 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700881 mLockTaskController.setWindowManager(wm);
882 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800883 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700884 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700885 }
886
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700887 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
888 synchronized (mGlobalLock) {
889 mUsageStatsInternal = usageStatsManager;
890 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700891 }
892
Wale Ogunwalef6733932018-06-27 05:14:34 -0700893 UserManagerService getUserManager() {
894 if (mUserManager == null) {
895 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
896 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
897 }
898 return mUserManager;
899 }
900
Philip P. Moltmannee295092020-02-10 08:46:26 -0800901 AppOpsManager getAppOpsManager() {
902 if (mAppOpsManager == null) {
903 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Wale Ogunwalef6733932018-06-27 05:14:34 -0700904 }
Philip P. Moltmannee295092020-02-10 08:46:26 -0800905 return mAppOpsManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700906 }
907
908 boolean hasUserRestriction(String restriction, int userId) {
909 return getUserManager().hasUserRestriction(restriction, userId);
910 }
911
Michal Karpinski15486842019-04-25 17:33:42 +0100912 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
Philip P. Moltmannee295092020-02-10 08:46:26 -0800913 final int mode = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
914 callingUid, callingPackage, /* featureId */ null, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100915 if (mode == AppOpsManager.MODE_DEFAULT) {
916 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
917 == PERMISSION_GRANTED;
918 }
919 return mode == AppOpsManager.MODE_ALLOWED;
920 }
921
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700922 @VisibleForTesting
923 protected void setRecentTasks(RecentTasks recentTasks) {
924 mRecentTasks = recentTasks;
925 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700926 }
927
928 RecentTasks getRecentTasks() {
929 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700930 }
931
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700932 ClientLifecycleManager getLifecycleManager() {
933 return mLifecycleManager;
934 }
935
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700936 ActivityStartController getActivityStartController() {
937 return mActivityStartController;
938 }
939
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700940 TaskChangeNotificationController getTaskChangeNotificationController() {
941 return mTaskChangeNotificationController;
942 }
943
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700944 LockTaskController getLockTaskController() {
945 return mLockTaskController;
946 }
947
Yunfan Chen75157d72018-07-27 14:47:21 +0900948 /**
949 * Return the global configuration used by the process corresponding to the input pid. This is
950 * usually the global configuration with some overrides specific to that process.
951 */
952 Configuration getGlobalConfigurationForCallingPid() {
953 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800954 return getGlobalConfigurationForPid(pid);
955 }
956
957 /**
958 * Return the global configuration used by the process corresponding to the given pid.
959 */
960 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900961 if (pid == MY_PID || pid < 0) {
962 return getGlobalConfiguration();
963 }
964 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100965 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900966 return app != null ? app.getConfiguration() : getGlobalConfiguration();
967 }
968 }
969
970 /**
971 * Return the device configuration info used by the process corresponding to the input pid.
972 * The value is consistent with the global configuration for the process.
973 */
974 @Override
975 public ConfigurationInfo getDeviceConfigurationInfo() {
976 ConfigurationInfo config = new ConfigurationInfo();
977 synchronized (mGlobalLock) {
978 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
979 config.reqTouchScreen = globalConfig.touchscreen;
980 config.reqKeyboardType = globalConfig.keyboard;
981 config.reqNavigation = globalConfig.navigation;
982 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
983 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
984 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
985 }
986 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
987 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
988 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
989 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700990 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900991 }
992 return config;
993 }
994
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700995 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700996 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700997 }
998
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700999 public static final class Lifecycle extends SystemService {
1000 private final ActivityTaskManagerService mService;
1001
1002 public Lifecycle(Context context) {
1003 super(context);
1004 mService = new ActivityTaskManagerService(context);
1005 }
1006
1007 @Override
1008 public void onStart() {
1009 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001010 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001011 }
1012
Garfield Tan891146c2018-10-09 12:14:00 -07001013 @Override
1014 public void onUnlockUser(int userId) {
1015 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001016 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001017 }
1018 }
1019
1020 @Override
1021 public void onCleanupUser(int userId) {
1022 synchronized (mService.getGlobalLock()) {
1023 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1024 }
1025 }
1026
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001027 public ActivityTaskManagerService getService() {
1028 return mService;
1029 }
1030 }
1031
1032 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001033 public final int startActivity(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001034 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1035 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1036 Bundle bOptions) {
1037 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1038 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001039 UserHandle.getCallingUserId());
1040 }
1041
1042 @Override
1043 public final int startActivities(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001044 String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
1045 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001046 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001047 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001048 enforceNotIsolatedCaller(reason);
1049 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001050 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001051 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001052 callingFeatureId, intents, resolvedTypes, resultTo,
1053 SafeActivityOptions.fromBundle(bOptions), userId, reason,
1054 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001055 }
1056
1057 @Override
1058 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001059 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1060 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1061 Bundle bOptions, int userId) {
1062 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1063 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001064 true /*validateIncomingUser*/);
1065 }
1066
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001067 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001068 @Nullable String callingFeatureId, Intent intent, String resolvedType,
1069 IBinder resultTo, String resultWho, int requestCode, int startFlags,
1070 ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001071 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001072 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001073
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001074 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001075 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1076
1077 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001078 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001079 .setCaller(caller)
1080 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001081 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001082 .setResolvedType(resolvedType)
1083 .setResultTo(resultTo)
1084 .setResultWho(resultWho)
1085 .setRequestCode(requestCode)
1086 .setStartFlags(startFlags)
1087 .setProfilerInfo(profilerInfo)
1088 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001089 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001090 .execute();
1091
1092 }
1093
1094 @Override
1095 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1096 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001097 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1098 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001099 // Refuse possible leaked file descriptors
1100 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1101 throw new IllegalArgumentException("File descriptors passed in Intent");
1102 }
1103
1104 if (!(target instanceof PendingIntentRecord)) {
1105 throw new IllegalArgumentException("Bad PendingIntent object");
1106 }
1107
1108 PendingIntentRecord pir = (PendingIntentRecord)target;
1109
1110 synchronized (mGlobalLock) {
1111 // If this is coming from the currently resumed activity, it is
1112 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001113 final ActivityStack stack = getTopDisplayFocusedStack();
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001114 if (stack != null && stack.mResumedActivity != null
1115 && stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001116 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001117 }
1118 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001119 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001120 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001121 }
1122
1123 @Override
1124 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1125 Bundle bOptions) {
1126 // Refuse possible leaked file descriptors
1127 if (intent != null && intent.hasFileDescriptors()) {
1128 throw new IllegalArgumentException("File descriptors passed in Intent");
1129 }
1130 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1131
1132 synchronized (mGlobalLock) {
1133 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1134 if (r == null) {
1135 SafeActivityOptions.abort(options);
1136 return false;
1137 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001138 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001139 // The caller is not running... d'oh!
1140 SafeActivityOptions.abort(options);
1141 return false;
1142 }
1143 intent = new Intent(intent);
1144 // The caller is not allowed to change the data.
1145 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1146 // And we are resetting to find the next component...
1147 intent.setComponent(null);
1148
1149 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1150
1151 ActivityInfo aInfo = null;
1152 try {
1153 List<ResolveInfo> resolves =
1154 AppGlobals.getPackageManager().queryIntentActivities(
1155 intent, r.resolvedType,
1156 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1157 UserHandle.getCallingUserId()).getList();
1158
1159 // Look for the original activity in the list...
1160 final int N = resolves != null ? resolves.size() : 0;
1161 for (int i=0; i<N; i++) {
1162 ResolveInfo rInfo = resolves.get(i);
1163 if (rInfo.activityInfo.packageName.equals(r.packageName)
1164 && rInfo.activityInfo.name.equals(r.info.name)) {
1165 // We found the current one... the next matching is
1166 // after it.
1167 i++;
1168 if (i<N) {
1169 aInfo = resolves.get(i).activityInfo;
1170 }
1171 if (debug) {
1172 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1173 + "/" + r.info.name);
1174 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1175 ? "null" : aInfo.packageName + "/" + aInfo.name));
1176 }
1177 break;
1178 }
1179 }
1180 } catch (RemoteException e) {
1181 }
1182
1183 if (aInfo == null) {
1184 // Nobody who is next!
1185 SafeActivityOptions.abort(options);
1186 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1187 return false;
1188 }
1189
1190 intent.setComponent(new ComponentName(
1191 aInfo.applicationInfo.packageName, aInfo.name));
1192 intent.setFlags(intent.getFlags()&~(
1193 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1194 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1195 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1196 FLAG_ACTIVITY_NEW_TASK));
1197
1198 // Okay now we need to start the new activity, replacing the currently running activity.
1199 // This is a little tricky because we want to start the new one as if the current one is
1200 // finished, but not finish the current one first so that there is no flicker.
1201 // And thus...
1202 final boolean wasFinishing = r.finishing;
1203 r.finishing = true;
1204
1205 // Propagate reply information over to the new activity.
1206 final ActivityRecord resultTo = r.resultTo;
1207 final String resultWho = r.resultWho;
1208 final int requestCode = r.requestCode;
1209 r.resultTo = null;
1210 if (resultTo != null) {
1211 resultTo.removeResultsLocked(r, resultWho, requestCode);
1212 }
1213
1214 final long origId = Binder.clearCallingIdentity();
1215 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001216 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001217 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001218 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001219 .setResolvedType(r.resolvedType)
1220 .setActivityInfo(aInfo)
1221 .setResultTo(resultTo != null ? resultTo.appToken : null)
1222 .setResultWho(resultWho)
1223 .setRequestCode(requestCode)
1224 .setCallingPid(-1)
1225 .setCallingUid(r.launchedFromUid)
1226 .setCallingPackage(r.launchedFromPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001227 .setCallingFeatureId(r.launchedFromFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001228 .setRealCallingPid(-1)
1229 .setRealCallingUid(r.launchedFromUid)
1230 .setActivityOptions(options)
1231 .execute();
1232 Binder.restoreCallingIdentity(origId);
1233
1234 r.finishing = wasFinishing;
1235 if (res != ActivityManager.START_SUCCESS) {
1236 return false;
1237 }
1238 return true;
1239 }
1240 }
1241
1242 @Override
Galia Peycheva6861e912019-08-21 10:20:23 +02001243 public boolean startDreamActivity(Intent intent) {
Galia Peycheva52e89222020-02-18 23:41:43 +01001244 final WindowProcessController process = mProcessMap.getProcess(Binder.getCallingPid());
1245 final long origId = Binder.clearCallingIdentity();
1246
1247 // The dream activity is only called for non-doze dreams.
1248 final ComponentName currentDream = LocalServices.getService(DreamManagerInternal.class)
1249 .getActiveDreamComponent(/* doze= */ false);
1250
1251 if (currentDream == null || currentDream.getPackageName() == null
1252 || !currentDream.getPackageName().equals(process.mInfo.packageName)) {
1253 Slog.e(TAG, "Calling package is not the current dream package. "
1254 + "Aborting startDreamActivity...");
1255 return false;
1256 }
1257
Galia Peycheva6861e912019-08-21 10:20:23 +02001258 final ActivityInfo a = new ActivityInfo();
1259 a.theme = com.android.internal.R.style.Theme_Dream;
1260 a.exported = true;
1261 a.name = DreamActivity.class.getName();
1262
Galia Peycheva6861e912019-08-21 10:20:23 +02001263
1264 a.packageName = process.mInfo.packageName;
1265 a.applicationInfo = process.mInfo;
1266 a.processName = process.mInfo.processName;
1267 a.uiOptions = process.mInfo.uiOptions;
1268 a.taskAffinity = "android:" + a.packageName + "/dream";
1269 a.enabled = true;
1270 a.launchMode = ActivityInfo.LAUNCH_SINGLE_INSTANCE;
1271
1272 a.persistableMode = ActivityInfo.PERSIST_NEVER;
1273 a.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1274 a.colorMode = ActivityInfo.COLOR_MODE_DEFAULT;
1275 a.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1276
Galia Peycheva45f48d32020-02-20 15:39:10 +01001277 final ActivityOptions options = ActivityOptions.makeBasic();
1278 options.setLaunchActivityType(ACTIVITY_TYPE_DREAM);
1279
Galia Peycheva6861e912019-08-21 10:20:23 +02001280 try {
1281 getActivityStartController().obtainStarter(intent, "dream")
1282 .setActivityInfo(a)
Galia Peycheva45f48d32020-02-20 15:39:10 +01001283 .setActivityOptions(options.toBundle())
Galia Peycheva6861e912019-08-21 10:20:23 +02001284 .setIsDream(true)
1285 .execute();
1286 return true;
1287 } finally {
1288 Binder.restoreCallingIdentity(origId);
1289 }
1290 }
1291
1292 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001293 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001294 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1295 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1296 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001297 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001298 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001299 enforceNotIsolatedCaller("startActivityAndWait");
1300 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1301 userId, "startActivityAndWait");
1302 // TODO: Switch to user app stacks here.
1303 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1304 .setCaller(caller)
1305 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001306 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001307 .setResolvedType(resolvedType)
1308 .setResultTo(resultTo)
1309 .setResultWho(resultWho)
1310 .setRequestCode(requestCode)
1311 .setStartFlags(startFlags)
1312 .setActivityOptions(bOptions)
1313 .setUserId(userId)
1314 .setProfilerInfo(profilerInfo)
1315 .setWaitResult(res)
1316 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001317 return res;
1318 }
1319
1320 @Override
1321 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001322 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1323 String resultWho, int requestCode, int startFlags, Configuration config,
1324 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001325 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001326 enforceNotIsolatedCaller("startActivityWithConfig");
1327 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1328 "startActivityWithConfig");
1329 // TODO: Switch to user app stacks here.
1330 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1331 .setCaller(caller)
1332 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001333 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001334 .setResolvedType(resolvedType)
1335 .setResultTo(resultTo)
1336 .setResultWho(resultWho)
1337 .setRequestCode(requestCode)
1338 .setStartFlags(startFlags)
1339 .setGlobalConfiguration(config)
1340 .setActivityOptions(bOptions)
1341 .setUserId(userId)
1342 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001343 }
1344
Robert Carr8a2f9132019-11-11 15:03:15 -08001345 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001346 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1347 int callingUid = Binder.getCallingUid();
1348 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1349 throw new SecurityException("Only the system process can request a permission token, "
1350 + "received request from uid: " + callingUid);
1351 }
1352 IBinder permissionToken = new Binder();
1353 synchronized (mGlobalLock) {
1354 mStartActivitySources.put(permissionToken, delegatorToken);
1355 }
1356
1357 Message expireMsg = PooledLambda.obtainMessage(
1358 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1359 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1360
1361 Message forgetMsg = PooledLambda.obtainMessage(
1362 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1363 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1364
1365 return permissionToken;
1366 }
1367
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 @Override
1369 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1370 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001371 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1372 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001373 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001374 // permission grants) as any app that may launch one of your own activities. So we only
1375 // allow this in two cases:
1376 // 1) The caller is an activity that is part of the core framework, and then only when it
1377 // is running as the system.
1378 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1379 // can only be requested by a system activity, which may then delegate this call to
1380 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001381 final ActivityRecord sourceRecord;
1382 final int targetUid;
1383 final String targetPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001384 final String targetFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001385 final boolean isResolver;
1386 synchronized (mGlobalLock) {
1387 if (resultTo == null) {
1388 throw new SecurityException("Must be called from an activity");
1389 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001390 final IBinder sourceToken;
1391 if (permissionToken != null) {
1392 // To even attempt to use a permissionToken, an app must also have this signature
1393 // permission.
1394 mAmInternal.enforceCallingPermission(
1395 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1396 "startActivityAsCaller");
1397 // If called with a permissionToken, we want the sourceRecord from the delegator
1398 // activity that requested this token.
1399 sourceToken = mStartActivitySources.remove(permissionToken);
1400 if (sourceToken == null) {
1401 // Invalid permissionToken, check if it recently expired.
1402 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1403 throw new SecurityException("Called with expired permission token: "
1404 + permissionToken);
1405 } else {
1406 throw new SecurityException("Called with invalid permission token: "
1407 + permissionToken);
1408 }
1409 }
1410 } else {
1411 // This method was called directly by the source.
1412 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001414
Louis Chang149d5c82019-12-30 09:47:39 +08001415 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001416 if (sourceRecord == null) {
1417 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001418 }
1419 if (sourceRecord.app == null) {
1420 throw new SecurityException("Called without a process attached to activity");
1421 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001422
1423 // Whether called directly or from a delegate, the source activity must be from the
1424 // android package.
1425 if (!sourceRecord.info.packageName.equals("android")) {
1426 throw new SecurityException("Must be called from an activity that is "
1427 + "declared in the android package");
1428 }
1429
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001430 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001431 // This is still okay, as long as this activity is running under the
1432 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001433 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001434 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001435 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001436 + " must be system uid or original calling uid "
1437 + sourceRecord.launchedFromUid);
1438 }
1439 }
1440 if (ignoreTargetSecurity) {
1441 if (intent.getComponent() == null) {
1442 throw new SecurityException(
1443 "Component must be specified with ignoreTargetSecurity");
1444 }
1445 if (intent.getSelector() != null) {
1446 throw new SecurityException(
1447 "Selector not allowed with ignoreTargetSecurity");
1448 }
1449 }
1450 targetUid = sourceRecord.launchedFromUid;
1451 targetPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001452 targetFeatureId = sourceRecord.launchedFromFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 isResolver = sourceRecord.isResolverOrChildActivity();
1454 }
1455
1456 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001457 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458 }
1459
1460 // TODO: Switch to user app stacks here.
1461 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001462 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001463 .setCallingUid(targetUid)
1464 .setCallingPackage(targetPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001465 .setCallingFeatureId(targetFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001466 .setResolvedType(resolvedType)
1467 .setResultTo(resultTo)
1468 .setResultWho(resultWho)
1469 .setRequestCode(requestCode)
1470 .setStartFlags(startFlags)
1471 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001472 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1474 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001475 // The target may well be in the background, which would normally prevent it
1476 // from starting an activity. Here we definitely want the start to succeed.
1477 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001478 .execute();
1479 } catch (SecurityException e) {
1480 // XXX need to figure out how to propagate to original app.
1481 // A SecurityException here is generally actually a fault of the original
1482 // calling activity (such as a fairly granting permissions), so propagate it
1483 // back to them.
1484 /*
1485 StringBuilder msg = new StringBuilder();
1486 msg.append("While launching");
1487 msg.append(intent.toString());
1488 msg.append(": ");
1489 msg.append(e.getMessage());
1490 */
1491 throw e;
1492 }
1493 }
1494
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001495 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1496 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001497 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001498 }
1499
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001500 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001501 public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1502 int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001503 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1504 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001505 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001506 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001507 if (session == null || interactor == null) {
1508 throw new NullPointerException("null session or interactor");
1509 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001510 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001511 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001512 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001513 .setCallingUid(callingUid)
1514 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001515 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001516 .setResolvedType(resolvedType)
1517 .setVoiceSession(session)
1518 .setVoiceInteractor(interactor)
1519 .setStartFlags(startFlags)
1520 .setProfilerInfo(profilerInfo)
1521 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001522 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001523 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001524 .execute();
1525 }
1526
1527 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001528 public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1529 int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1530 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001531 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001532 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1533 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001534
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001535 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001536 .setCallingUid(callingUid)
1537 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001538 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001539 .setResolvedType(resolvedType)
1540 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001541 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001542 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001543 .execute();
1544 }
1545
Riddle Hsu609a8e22019-06-27 16:46:29 -06001546 /**
1547 * Start the recents activity to perform the recents animation.
1548 *
1549 * @param intent The intent to start the recents activity.
1550 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1551 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001552 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001553 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1554 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001555 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001556 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001557 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001558 final long origId = Binder.clearCallingIdentity();
1559 try {
1560 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001561 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
Philip P. Moltmannee295092020-02-10 08:46:26 -08001562 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001563 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001564 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001565
1566 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001567 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001568 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001569 recentsFeatureId, recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001570 if (recentsAnimationRunner == null) {
1571 anim.preloadRecentsActivity();
1572 } else {
1573 anim.startRecentsActivity(recentsAnimationRunner);
1574 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001575 }
1576 } finally {
1577 Binder.restoreCallingIdentity(origId);
1578 }
1579 }
1580
1581 @Override
1582 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001583 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001584 "startActivityFromRecents()");
1585
1586 final int callingPid = Binder.getCallingPid();
1587 final int callingUid = Binder.getCallingUid();
1588 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1589 final long origId = Binder.clearCallingIdentity();
1590 try {
1591 synchronized (mGlobalLock) {
1592 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1593 safeOptions);
1594 }
1595 } finally {
1596 Binder.restoreCallingIdentity(origId);
1597 }
1598 }
1599
1600 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001601 * Public API to check if the client is allowed to start an activity on specified display.
1602 *
1603 * If the target display is private or virtual, some restrictions will apply.
1604 *
1605 * @param displayId Target display id.
1606 * @param intent Intent used to launch the activity.
1607 * @param resolvedType The MIME type of the intent.
1608 * @param userId The id of the user for whom the call is made.
1609 * @return {@code true} if a call to start an activity on the target display should succeed and
1610 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1611 */
1612 @Override
1613 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1614 String resolvedType, int userId) {
1615 final int callingUid = Binder.getCallingUid();
1616 final int callingPid = Binder.getCallingPid();
1617 final long origId = Binder.clearCallingIdentity();
1618
1619 try {
1620 // Collect information about the target of the Intent.
1621 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1622 0 /* startFlags */, null /* profilerInfo */, userId,
1623 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1624 UserHandle.USER_NULL));
1625 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1626
1627 synchronized (mGlobalLock) {
1628 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1629 aInfo);
1630 }
1631 } finally {
1632 Binder.restoreCallingIdentity(origId);
1633 }
1634 }
1635
1636 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001637 * This is the internal entry point for handling Activity.finish().
1638 *
1639 * @param token The Binder token referencing the Activity we want to finish.
1640 * @param resultCode Result code, if any, from this Activity.
1641 * @param resultData Result data (Intent), if any, from this Activity.
1642 * @param finishTask Whether to finish the task associated with this Activity.
1643 *
1644 * @return Returns true if the activity successfully finished, or false if it is still running.
1645 */
1646 @Override
1647 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1648 int finishTask) {
1649 // Refuse possible leaked file descriptors
1650 if (resultData != null && resultData.hasFileDescriptors()) {
1651 throw new IllegalArgumentException("File descriptors passed in Intent");
1652 }
1653
1654 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001655 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001656 if (r == null) {
1657 return true;
1658 }
1659 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001660 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001661 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001662 if (rootR == null) {
1663 Slog.w(TAG, "Finishing task with all activities already finished");
1664 }
1665 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1666 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001667 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001668 return false;
1669 }
1670
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001671 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1672 // We should consolidate.
1673 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001674 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001675 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001676 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001677 if (next != null) {
1678 // ask watcher if this is allowed
1679 boolean resumeOK = true;
1680 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001681 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001682 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001683 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001684 Watchdog.getInstance().setActivityController(null);
1685 }
1686
1687 if (!resumeOK) {
1688 Slog.i(TAG, "Not finishing activity because controller resumed");
1689 return false;
1690 }
1691 }
1692 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001693
1694 // note down that the process has finished an activity and is in background activity
1695 // starts grace period
1696 if (r.app != null) {
1697 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1698 }
1699
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001700 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001701 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001702 try {
1703 boolean res;
1704 final boolean finishWithRootActivity =
1705 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1706 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1707 || (finishWithRootActivity && r == rootR)) {
1708 // If requested, remove the task that is associated to this activity only if it
1709 // was the root activity in the task. The result code and data is ignored
1710 // because we don't support returning them across task boundaries. Also, to
1711 // keep backwards compatibility we remove the task from recents when finishing
1712 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001713 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001714 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001715 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001716 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001717 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001718 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001719 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001720 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001721 if (!res) {
1722 Slog.i(TAG, "Failed to finish by app-request");
1723 }
1724 }
1725 return res;
1726 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001727 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001728 Binder.restoreCallingIdentity(origId);
1729 }
1730 }
1731 }
1732
1733 @Override
1734 public boolean finishActivityAffinity(IBinder token) {
1735 synchronized (mGlobalLock) {
1736 final long origId = Binder.clearCallingIdentity();
1737 try {
1738 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1739 if (r == null) {
1740 return false;
1741 }
1742
1743 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1744 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001745 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001746 return false;
1747 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001748
1749 final PooledFunction p = PooledLambda.obtainFunction(
1750 ActivityRecord::finishIfSameAffinity, r,
1751 PooledLambda.__(ActivityRecord.class));
1752 r.getTask().forAllActivities(
1753 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1754 p.recycle();
1755
Andrii Kuliande93eff2019-07-12 12:21:27 -07001756 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001757 } finally {
1758 Binder.restoreCallingIdentity(origId);
1759 }
1760 }
1761 }
1762
1763 @Override
1764 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1765 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001766 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001767 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001768 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001769 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1770 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001771 return;
1772 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001773 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1774 false /* processPausingActivities */, config);
1775 if (stopProfiling && r.hasProcess()) {
1776 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001777 }
1778 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001779 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001780 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001781 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001782 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001783 }
1784
1785 @Override
1786 public final void activityResumed(IBinder token) {
1787 final long origId = Binder.clearCallingIdentity();
1788 synchronized (mGlobalLock) {
1789 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001790 }
1791 Binder.restoreCallingIdentity(origId);
1792 }
1793
1794 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001795 public final void activityTopResumedStateLost() {
1796 final long origId = Binder.clearCallingIdentity();
1797 synchronized (mGlobalLock) {
1798 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1799 }
1800 Binder.restoreCallingIdentity(origId);
1801 }
1802
1803 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001804 public final void activityPaused(IBinder token) {
1805 final long origId = Binder.clearCallingIdentity();
1806 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001807 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001808 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1809 if (r != null) {
1810 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001811 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001812 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001813 }
1814 Binder.restoreCallingIdentity(origId);
1815 }
1816
1817 @Override
1818 public final void activityStopped(IBinder token, Bundle icicle,
1819 PersistableBundle persistentState, CharSequence description) {
1820 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1821
1822 // Refuse possible leaked file descriptors
1823 if (icicle != null && icicle.hasFileDescriptors()) {
1824 throw new IllegalArgumentException("File descriptors passed in Bundle");
1825 }
1826
1827 final long origId = Binder.clearCallingIdentity();
1828
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001829 String restartingName = null;
1830 int restartingUid = 0;
1831 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001832 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001833 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001834 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001835 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001836 if (r.attachedToProcess()
1837 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1838 // The activity was requested to restart from
1839 // {@link #restartActivityProcessIfVisible}.
1840 restartingName = r.app.mName;
1841 restartingUid = r.app.mUid;
1842 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001843 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001844 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001845 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001846 }
1847
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001848 if (restartingName != null) {
1849 // In order to let the foreground activity can be restarted with its saved state from
1850 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1851 // until the activity reports stopped with the state. And the activity record will be
1852 // kept because the record state is restarting, then the activity will be restarted
1853 // immediately if it is still the top one.
1854 mStackSupervisor.removeRestartTimeouts(r);
1855 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1856 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001857 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001858
1859 Binder.restoreCallingIdentity(origId);
1860 }
1861
1862 @Override
1863 public final void activityDestroyed(IBinder token) {
1864 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1865 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001866 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001867 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001868 try {
1869 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1870 if (activity != null) {
1871 activity.destroyed("activityDestroyed");
1872 }
1873 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001874 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001875 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001876 }
1877 }
1878 }
1879
1880 @Override
1881 public final void activityRelaunched(IBinder token) {
1882 final long origId = Binder.clearCallingIdentity();
1883 synchronized (mGlobalLock) {
1884 mStackSupervisor.activityRelaunchedLocked(token);
1885 }
1886 Binder.restoreCallingIdentity(origId);
1887 }
1888
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001889 @Override
1890 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1891 synchronized (mGlobalLock) {
1892 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1893 if (r == null) {
1894 return;
1895 }
1896 final long origId = Binder.clearCallingIdentity();
1897 try {
1898 r.setRequestedOrientation(requestedOrientation);
1899 } finally {
1900 Binder.restoreCallingIdentity(origId);
1901 }
1902 }
1903 }
1904
1905 @Override
1906 public int getRequestedOrientation(IBinder token) {
1907 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001908 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1909 return (r != null)
1910 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001911 }
1912 }
1913
1914 @Override
1915 public void setImmersive(IBinder token, boolean immersive) {
1916 synchronized (mGlobalLock) {
1917 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1918 if (r == null) {
1919 throw new IllegalArgumentException();
1920 }
1921 r.immersive = immersive;
1922
1923 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001924 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001925 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001926 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001927 }
1928 }
1929 }
1930
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001931 void applyUpdateLockStateLocked(ActivityRecord r) {
1932 // Modifications to the UpdateLock state are done on our handler, outside
1933 // the activity manager's locks. The new state is determined based on the
1934 // state *now* of the relevant activity record. The object is passed to
1935 // the handler solely for logging detail, not to be consulted/modified.
1936 final boolean nextState = r != null && r.immersive;
1937 mH.post(() -> {
1938 if (mUpdateLock.isHeld() != nextState) {
1939 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1940 "Applying new update lock state '" + nextState + "' for " + r);
1941 if (nextState) {
1942 mUpdateLock.acquire();
1943 } else {
1944 mUpdateLock.release();
1945 }
1946 }
1947 });
1948 }
1949
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001950 @Override
1951 public boolean isImmersive(IBinder token) {
1952 synchronized (mGlobalLock) {
1953 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1954 if (r == null) {
1955 throw new IllegalArgumentException();
1956 }
1957 return r.immersive;
1958 }
1959 }
1960
1961 @Override
1962 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001963 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001964 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001965 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
1966 if (topFocusedStack == null) {
1967 return false;
1968 }
1969
1970 final ActivityRecord r = topFocusedStack.topRunningActivity();
1971 return r != null && r.immersive;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001972 }
1973 }
1974
1975 @Override
1976 public void overridePendingTransition(IBinder token, String packageName,
1977 int enterAnim, int exitAnim) {
1978 synchronized (mGlobalLock) {
1979 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1980 if (self == null) {
1981 return;
1982 }
1983
1984 final long origId = Binder.clearCallingIdentity();
1985
1986 if (self.isState(
1987 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001988 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001989 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001990 }
1991
1992 Binder.restoreCallingIdentity(origId);
1993 }
1994 }
1995
1996 @Override
1997 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001998 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002000 final ActivityStack stack = getTopDisplayFocusedStack();
2001 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002002 if (r == null) {
2003 return ActivityManager.COMPAT_MODE_UNKNOWN;
2004 }
Wale Ogunwale53783742018-09-16 10:21:51 -07002005 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002006 }
2007 }
2008
2009 @Override
2010 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002011 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002012 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002013 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002014 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002015 final ActivityStack stack = getTopDisplayFocusedStack();
2016 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002017 if (r == null) {
2018 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
2019 return;
2020 }
2021 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07002022 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002023 }
2024 }
2025
2026 @Override
2027 public int getLaunchedFromUid(IBinder activityToken) {
2028 ActivityRecord srec;
2029 synchronized (mGlobalLock) {
2030 srec = ActivityRecord.forTokenLocked(activityToken);
2031 }
2032 if (srec == null) {
2033 return -1;
2034 }
2035 return srec.launchedFromUid;
2036 }
2037
2038 @Override
2039 public String getLaunchedFromPackage(IBinder activityToken) {
2040 ActivityRecord srec;
2041 synchronized (mGlobalLock) {
2042 srec = ActivityRecord.forTokenLocked(activityToken);
2043 }
2044 if (srec == null) {
2045 return null;
2046 }
2047 return srec.launchedFromPackage;
2048 }
2049
2050 @Override
2051 public boolean convertFromTranslucent(IBinder token) {
2052 final long origId = Binder.clearCallingIdentity();
2053 try {
2054 synchronized (mGlobalLock) {
2055 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2056 if (r == null) {
2057 return false;
2058 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002059 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 }
2061 } finally {
2062 Binder.restoreCallingIdentity(origId);
2063 }
2064 }
2065
2066 @Override
2067 public boolean convertToTranslucent(IBinder token, Bundle options) {
2068 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2069 final long origId = Binder.clearCallingIdentity();
2070 try {
2071 synchronized (mGlobalLock) {
2072 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2073 if (r == null) {
2074 return false;
2075 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002076 final ActivityRecord under = r.getTask().getActivityBelow(r);
2077 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002078 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2079 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002080 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002081 }
2082 } finally {
2083 Binder.restoreCallingIdentity(origId);
2084 }
2085 }
2086
2087 @Override
2088 public void notifyActivityDrawn(IBinder token) {
2089 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2090 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002091 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002092 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002093 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002094 }
2095 }
2096 }
2097
2098 @Override
2099 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2100 synchronized (mGlobalLock) {
2101 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2102 if (r == null) {
2103 return;
2104 }
2105 r.reportFullyDrawnLocked(restoredFromBundle);
2106 }
2107 }
2108
2109 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002110 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002111 synchronized (mGlobalLock) {
2112 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002113 if (stack != null) {
2114 final int displayId = stack.getDisplayId();
2115 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002116 }
2117 return DEFAULT_DISPLAY;
2118 }
2119 }
2120
2121 @Override
2122 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002123 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002124 long ident = Binder.clearCallingIdentity();
2125 try {
2126 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002127 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002128 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002129 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002130 }
2131 return null;
2132 }
2133 } finally {
2134 Binder.restoreCallingIdentity(ident);
2135 }
2136 }
2137
2138 @Override
2139 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002140 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002141 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2142 final long callingId = Binder.clearCallingIdentity();
2143 try {
2144 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002145 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002146 if (stack == null) {
2147 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2148 return;
2149 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002150 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002151 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002152 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002153 }
2154 }
2155 } finally {
2156 Binder.restoreCallingIdentity(callingId);
2157 }
2158 }
2159
2160 @Override
2161 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002162 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002163 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2164 final long callingId = Binder.clearCallingIdentity();
2165 try {
2166 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002167 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002168 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002169 if (task == null) {
2170 return;
2171 }
2172 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002173 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002174 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002175 }
2176 }
2177 } finally {
2178 Binder.restoreCallingIdentity(callingId);
2179 }
2180 }
2181
2182 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002183 public void restartActivityProcessIfVisible(IBinder activityToken) {
2184 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2185 final long callingId = Binder.clearCallingIdentity();
2186 try {
2187 synchronized (mGlobalLock) {
2188 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2189 if (r == null) {
2190 return;
2191 }
2192 r.restartProcessIfVisible();
2193 }
2194 } finally {
2195 Binder.restoreCallingIdentity(callingId);
2196 }
2197 }
2198
2199 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002200 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002201 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002202 synchronized (mGlobalLock) {
2203 final long ident = Binder.clearCallingIdentity();
2204 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002205 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002206 "remove-task");
2207 } finally {
2208 Binder.restoreCallingIdentity(ident);
2209 }
2210 }
2211 }
2212
2213 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002214 public void removeAllVisibleRecentTasks() {
2215 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2216 synchronized (mGlobalLock) {
2217 final long ident = Binder.clearCallingIdentity();
2218 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002219 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002220 } finally {
2221 Binder.restoreCallingIdentity(ident);
2222 }
2223 }
2224 }
2225
2226 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2228 synchronized (mGlobalLock) {
2229 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2230 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002231 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002232 }
2233 }
2234 return false;
2235 }
2236
2237 @Override
2238 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2239 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002240
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002241 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002242 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2243 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002244 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002245 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002246 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002247 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002248 }
2249 }
2250
2251 /**
2252 * Attempts to move a task backwards in z-order (the order of activities within the task is
2253 * unchanged).
2254 *
2255 * There are several possible results of this call:
2256 * - if the task is locked, then we will show the lock toast
2257 * - if there is a task behind the provided task, then that task is made visible and resumed as
2258 * this task is moved to the back
2259 * - otherwise, if there are no other tasks in the stack:
2260 * - if this task is in the pinned stack, then we remove the stack completely, which will
2261 * have the effect of moving the task to the top or bottom of the fullscreen stack
2262 * (depending on whether it is visible)
2263 * - otherwise, we simply return home and hide this task
2264 *
2265 * @param token A reference to the activity we wish to move
2266 * @param nonRoot If false then this only works if the activity is the root
2267 * of a task; if true it will work for any activity in a task.
2268 * @return Returns true if the move completed, false if not.
2269 */
2270 @Override
2271 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002272 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002273 synchronized (mGlobalLock) {
2274 final long origId = Binder.clearCallingIdentity();
2275 try {
2276 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002277 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002278 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002279 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002280 }
2281 } finally {
2282 Binder.restoreCallingIdentity(origId);
2283 }
2284 }
2285 return false;
2286 }
2287
2288 @Override
2289 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002290 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002291 long ident = Binder.clearCallingIdentity();
2292 Rect rect = new Rect();
2293 try {
2294 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002295 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002296 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2297 if (task == null) {
2298 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2299 return rect;
2300 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002301 if (task.getParent() != null) {
2302 rect.set(task.getBounds());
2303 } else if (task.mLastNonFullscreenBounds != null) {
2304 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002305 }
2306 }
2307 } finally {
2308 Binder.restoreCallingIdentity(ident);
2309 }
2310 return rect;
2311 }
2312
2313 @Override
2314 public ActivityManager.TaskDescription getTaskDescription(int id) {
2315 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002316 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002317 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002318 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002319 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2320 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002321 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002322 }
2323 }
2324 return null;
2325 }
2326
2327 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002328 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002329 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08002330 return setTaskWindowingModeSplitScreenPrimary(taskId, toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002331 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002332 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002333 synchronized (mGlobalLock) {
2334 final long ident = Binder.clearCallingIdentity();
2335 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002336 if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2337 return setTaskWindowingModeSplitScreen(taskId, windowingMode, toTop);
2338 }
Louis Chang149d5c82019-12-30 09:47:39 +08002339 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002340 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002341 if (task == null) {
2342 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002343 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002344 }
2345
2346 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2347 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2348
2349 if (!task.isActivityTypeStandardOrUndefined()) {
2350 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2351 + " non-standard task " + taskId + " to windowing mode="
2352 + windowingMode);
2353 }
2354
2355 final ActivityStack stack = task.getStack();
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002356 // Convert some windowing-mode changes into root-task reparents for split-screen.
2357 if (stack.getTile() != null) {
2358 stack.getDisplay().onSplitScreenModeDismissed();
2359 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002360 if (toTop) {
2361 stack.moveToFront("setTaskWindowingMode", task);
2362 }
2363 stack.setWindowingMode(windowingMode);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002364 stack.getDisplay().ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2365 true /* notifyClients */);
Winson Chung7ccc6812020-01-23 16:15:10 -08002366 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002367 } finally {
2368 Binder.restoreCallingIdentity(ident);
2369 }
2370 }
2371 }
2372
2373 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002374 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002375 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002376 ActivityRecord r = getCallingRecordLocked(token);
2377 return r != null ? r.info.packageName : null;
2378 }
2379 }
2380
2381 @Override
2382 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002383 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002384 ActivityRecord r = getCallingRecordLocked(token);
2385 return r != null ? r.intent.getComponent() : null;
2386 }
2387 }
2388
2389 private ActivityRecord getCallingRecordLocked(IBinder token) {
2390 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2391 if (r == null) {
2392 return null;
2393 }
2394 return r.resultTo;
2395 }
2396
2397 @Override
2398 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002399 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002400
2401 synchronized (mGlobalLock) {
2402 final long origId = Binder.clearCallingIdentity();
2403 try {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002404 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
2405 if (topFocusedStack != null) {
2406 topFocusedStack.unhandledBackLocked();
2407 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002408 } finally {
2409 Binder.restoreCallingIdentity(origId);
2410 }
2411 }
2412 }
2413
Mark Renouf446251d2019-04-26 10:22:41 -04002414 @Override
2415 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2416 synchronized (mGlobalLock) {
2417 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2418 if (r == null) {
2419 return;
2420 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002421 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002422 if (stack != null && stack.isSingleTaskInstance()) {
2423 // Single-task stacks are used for activities which are presented in floating
2424 // windows above full screen activities. Instead of directly finishing the
2425 // task, a task change listener is used to notify SystemUI so the action can be
2426 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002427 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002428 mTaskChangeNotificationController
2429 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2430 } else {
2431 try {
2432 callback.requestFinish();
2433 } catch (RemoteException e) {
2434 Slog.e(TAG, "Failed to invoke request finish callback", e);
2435 }
2436 }
2437 }
2438 }
2439
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002440 /**
2441 * TODO: Add mController hook
2442 */
2443 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002444 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2445 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002446 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002447
2448 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2449 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002450 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2451 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002452 }
2453 }
2454
Ricky Waiaca8a772019-04-04 16:01:06 +01002455 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2456 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002457 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002458 final int callingPid = Binder.getCallingPid();
2459 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002460 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002461 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002462 SafeActivityOptions.abort(options);
2463 return;
2464 }
2465 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002466 WindowProcessController callerApp = null;
2467 if (appThread != null) {
2468 callerApp = getProcessController(appThread);
2469 }
2470 final ActivityStarter starter = getActivityStartController().obtainStarter(
2471 null /* intent */, "moveTaskToFront");
2472 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
Galia Peycheva6861e912019-08-21 10:20:23 +02002473 -1, callerApp, null, false, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002474 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002475 return;
2476 }
2477 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002478 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002479 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002480 if (task == null) {
2481 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002482 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002483 return;
2484 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002485 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002486 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002487 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002488 return;
2489 }
2490 ActivityOptions realOptions = options != null
2491 ? options.getOptions(mStackSupervisor)
2492 : null;
2493 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2494 false /* forceNonResizable */);
2495
Wale Ogunwale21e06482019-11-18 05:14:15 -08002496 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002497 if (topActivity != null) {
2498
2499 // We are reshowing a task, use a starting window to hide the initial draw delay
2500 // so the transition can start earlier.
2501 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2502 true /* taskSwitch */, fromRecents);
2503 }
2504 } finally {
2505 Binder.restoreCallingIdentity(origId);
2506 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002507 }
2508
Ricky Waiaca8a772019-04-04 16:01:06 +01002509 /**
2510 * Return true if callingUid is system, or packageName belongs to that callingUid.
2511 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002512 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002513 try {
2514 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2515 if (packageName == null) {
2516 return false;
2517 }
2518 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2519 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2520 UserHandle.getUserId(callingUid));
2521 return UserHandle.isSameApp(callingUid, uid);
2522 }
2523 } catch (RemoteException e) {
2524 // Should not happen
2525 }
2526 return true;
2527 }
2528
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002529 /**
2530 * Checks that the provided package name matches the current calling UID, throws a security
2531 * exception if it doesn't.
2532 */
2533 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2534 final int callingUid = Binder.getCallingUid();
2535 if (isSameApp(callingUid, packageName)) {
2536 return;
2537 }
2538 final String msg = "Permission Denial: package=" + packageName
2539 + " does not belong to uid=" + callingUid;
2540 Slog.w(TAG, msg);
2541 throw new SecurityException(msg);
2542 }
2543
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002544 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2545 int callingPid, int callingUid, String name) {
2546 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2547 return true;
2548 }
2549
2550 if (getRecentTasks().isCallerRecents(sourceUid)) {
2551 return true;
2552 }
2553
2554 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2555 if (perm == PackageManager.PERMISSION_GRANTED) {
2556 return true;
2557 }
2558 if (checkAllowAppSwitchUid(sourceUid)) {
2559 return true;
2560 }
2561
2562 // If the actual IPC caller is different from the logical source, then
2563 // also see if they are allowed to control app switches.
2564 if (callingUid != -1 && callingUid != sourceUid) {
2565 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2566 if (perm == PackageManager.PERMISSION_GRANTED) {
2567 return true;
2568 }
2569 if (checkAllowAppSwitchUid(callingUid)) {
2570 return true;
2571 }
2572 }
2573
2574 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2575 return false;
2576 }
2577
2578 private boolean checkAllowAppSwitchUid(int uid) {
2579 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2580 if (types != null) {
2581 for (int i = types.size() - 1; i >= 0; i--) {
2582 if (types.valueAt(i).intValue() == uid) {
2583 return true;
2584 }
2585 }
2586 }
2587 return false;
2588 }
2589
2590 @Override
2591 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2592 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2593 "setActivityController()");
2594 synchronized (mGlobalLock) {
2595 mController = controller;
2596 mControllerIsAMonkey = imAMonkey;
2597 Watchdog.getInstance().setActivityController(controller);
2598 }
2599 }
2600
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002601 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002602 synchronized (mGlobalLock) {
2603 return mController != null && mControllerIsAMonkey;
2604 }
2605 }
2606
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002607 @Override
2608 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2609 synchronized (mGlobalLock) {
2610 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2611 }
2612 }
2613
2614 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002615 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2616 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2617 }
2618
2619 @Override
2620 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2621 @WindowConfiguration.ActivityType int ignoreActivityType,
2622 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2623 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002624 final int callingPid = Binder.getCallingPid();
2625 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002626 final int[] profileIds = getUserManager().getProfileIds(
2627 UserHandle.getUserId(callingUid), true);
2628 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2629 for (int i = 0; i < profileIds.length; i++) {
2630 callingProfileIds.add(profileIds[i]);
2631 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002632 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2633
2634 synchronized (mGlobalLock) {
2635 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2636
Nicholas Sauer0259e532019-08-30 08:24:55 -07002637 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002638 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002639 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002640 }
2641
2642 return list;
2643 }
2644
2645 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002646 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2647 synchronized (mGlobalLock) {
2648 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002649 try {
2650 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2651 if (r == null) return;
2652
2653 final PooledConsumer c = PooledLambda.obtainConsumer(
2654 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2655 r, resultWho, requestCode);
2656 // TODO: This should probably only loop over the task since you need to be in the
2657 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002658 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002659 c.recycle();
2660
2661 updateOomAdj();
2662 } finally {
2663 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002664 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002665 }
2666 }
2667
2668 @Override
2669 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002670 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002671 ActivityStack stack = ActivityRecord.getStackLocked(token);
2672 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002673 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002674 }
2675 return false;
2676 }
2677 }
2678
2679 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002680 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002681 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002682 synchronized (mGlobalLock) {
2683 final long ident = Binder.clearCallingIdentity();
2684 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002685 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002686 if (task == null) {
2687 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2688 return;
2689 }
2690
2691 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2692 + " to stackId=" + stackId + " toTop=" + toTop);
2693
Louis Chang149d5c82019-12-30 09:47:39 +08002694 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002695 if (stack == null) {
2696 throw new IllegalStateException(
2697 "moveTaskToStack: No stack for stackId=" + stackId);
2698 }
2699 if (!stack.isActivityTypeStandardOrUndefined()) {
2700 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2701 + taskId + " to stack " + stackId);
2702 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002703 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2704 "moveTaskToStack");
2705 } finally {
2706 Binder.restoreCallingIdentity(ident);
2707 }
2708 }
2709 }
2710
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002711 /**
2712 * Moves the specified task to the primary-split-screen stack.
2713 *
2714 * @param taskId Id of task to move.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002715 * @param toTop If the task and stack should be moved to the top.
Winson Chung7ccc6812020-01-23 16:15:10 -08002716 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002717 */
2718 @Override
Evan Rosky73a7fe92019-11-18 18:28:01 -08002719 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002720 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002721 "setTaskWindowingModeSplitScreenPrimary()");
2722 synchronized (mGlobalLock) {
2723 final long ident = Binder.clearCallingIdentity();
2724 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002725 return setTaskWindowingModeSplitScreen(taskId, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY,
2726 toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002727 } finally {
2728 Binder.restoreCallingIdentity(ident);
2729 }
2730 }
2731 }
2732
2733 /**
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002734 * Moves the specified task into a split-screen tile.
2735 */
2736 private boolean setTaskWindowingModeSplitScreen(int taskId, int windowingMode, boolean toTop) {
2737 if (!WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2738 throw new IllegalArgumentException("Calling setTaskWindowingModeSplitScreen with non"
2739 + "split-screen mode: " + windowingMode);
2740 }
2741 if (isInLockTaskMode()) {
2742 Slog.w(TAG, "setTaskWindowingModeSplitScreen: Is in lock task mode="
2743 + getLockTaskModeState());
2744 return false;
2745 }
2746
2747 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2748 MATCH_TASK_IN_STACKS_ONLY);
2749 if (task == null) {
2750 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2751 return false;
2752 }
2753 if (!task.isActivityTypeStandardOrUndefined()) {
2754 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2755 + " non-standard task " + taskId + " to split-screen windowing mode");
2756 }
Wale Ogunwale0d465192020-01-23 19:14:44 -08002757 if (!task.supportsSplitScreenWindowingMode()) {
2758 return false;
2759 }
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002760
2761 final int prevMode = task.getWindowingMode();
Wale Ogunwale0d465192020-01-23 19:14:44 -08002762 moveTaskToSplitScreenPrimaryTile(task, toTop);
2763 return prevMode != task.getWindowingMode();
2764 }
2765
2766 void moveTaskToSplitScreenPrimaryTile(Task task, boolean toTop) {
2767 ActivityStack stack = task.getStack();
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002768 TaskTile tile = null;
2769 for (int i = stack.getDisplay().getStackCount() - 1; i >= 0; --i) {
2770 tile = stack.getDisplay().getStackAt(i).asTile();
2771 if (tile != null && tile.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2772 break;
2773 }
2774 }
2775 if (tile == null) {
2776 throw new IllegalStateException("Can't enter split without associated tile");
2777 }
2778 WindowContainerTransaction wct = new WindowContainerTransaction();
2779 wct.reparent(stack.mRemoteToken, tile.mRemoteToken, toTop);
2780 mTaskOrganizerController.applyContainerTransaction(wct, null);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002781 }
2782
2783 /**
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002784 * Removes stacks in the input windowing modes from the system if they are of activity type
2785 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2786 */
2787 @Override
2788 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002789 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002790 "removeStacksInWindowingModes()");
2791
2792 synchronized (mGlobalLock) {
2793 final long ident = Binder.clearCallingIdentity();
2794 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002795 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002796 } finally {
2797 Binder.restoreCallingIdentity(ident);
2798 }
2799 }
2800 }
2801
2802 @Override
2803 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002804 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002805 "removeStacksWithActivityTypes()");
2806
2807 synchronized (mGlobalLock) {
2808 final long ident = Binder.clearCallingIdentity();
2809 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002810 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002811 } finally {
2812 Binder.restoreCallingIdentity(ident);
2813 }
2814 }
2815 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002816
2817 @Override
2818 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2819 int userId) {
2820 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002821 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2822 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002823 callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002824 synchronized (mGlobalLock) {
Winson Chung66b08f02020-03-03 14:32:35 -08002825 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, userId, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 }
2827 }
2828
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002829 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002830 @Override
2831 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002832 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002833 long ident = Binder.clearCallingIdentity();
2834 try {
2835 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002836 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002837 }
2838 } finally {
2839 Binder.restoreCallingIdentity(ident);
2840 }
2841 }
2842
2843 @Override
2844 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002845 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002846 long ident = Binder.clearCallingIdentity();
2847 try {
2848 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002849 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002850 }
2851 } finally {
2852 Binder.restoreCallingIdentity(ident);
2853 }
2854 }
2855
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002856 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002857 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002858 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2859 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2860 long ident = Binder.clearCallingIdentity();
2861 try {
2862 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002863 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002864 }
2865 } finally {
2866 Binder.restoreCallingIdentity(ident);
2867 }
2868 }
2869
2870 @Override
2871 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2872 int displayId) {
2873 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2874 long ident = Binder.clearCallingIdentity();
2875 try {
2876 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002877 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002878 }
2879 } finally {
2880 Binder.restoreCallingIdentity(ident);
2881 }
2882 }
2883
2884 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002885 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002886 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002887 final long callingUid = Binder.getCallingUid();
2888 final long origId = Binder.clearCallingIdentity();
2889 try {
2890 synchronized (mGlobalLock) {
2891 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002892 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002893 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2894 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2895 }
2896 } finally {
2897 Binder.restoreCallingIdentity(origId);
2898 }
2899 }
2900
2901 @Override
2902 public void startLockTaskModeByToken(IBinder token) {
2903 synchronized (mGlobalLock) {
2904 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2905 if (r == null) {
2906 return;
2907 }
Louis Changcdec0802019-11-11 11:45:07 +08002908 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002909 }
2910 }
2911
2912 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002913 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002914 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002915 // This makes inner call to look as if it was initiated by system.
2916 long ident = Binder.clearCallingIdentity();
2917 try {
2918 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002919 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002920 MATCH_TASK_IN_STACKS_ONLY);
2921 if (task == null) {
2922 return;
2923 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002924
2925 // When starting lock task mode the stack must be in front and focused
2926 task.getStack().moveToFront("startSystemLockTaskMode");
2927 startLockTaskModeLocked(task, true /* isSystemCaller */);
2928 }
2929 } finally {
2930 Binder.restoreCallingIdentity(ident);
2931 }
2932 }
2933
2934 @Override
2935 public void stopLockTaskModeByToken(IBinder token) {
2936 synchronized (mGlobalLock) {
2937 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2938 if (r == null) {
2939 return;
2940 }
Louis Changcdec0802019-11-11 11:45:07 +08002941 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002942 }
2943 }
2944
2945 /**
2946 * This API should be called by SystemUI only when user perform certain action to dismiss
2947 * lock task mode. We should only dismiss pinned lock task mode in this case.
2948 */
2949 @Override
2950 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002951 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2953 }
2954
Louis Changcdec0802019-11-11 11:45:07 +08002955 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002956 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2957 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2958 return;
2959 }
2960
Louis Chang149d5c82019-12-30 09:47:39 +08002961 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002962 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002963 throw new IllegalArgumentException("Invalid task, not in foreground");
2964 }
2965
2966 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2967 // system or a specific app.
2968 // * System-initiated requests will only start the pinned mode (screen pinning)
2969 // * App-initiated requests
2970 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2971 // - will start the pinned mode, otherwise
2972 final int callingUid = Binder.getCallingUid();
2973 long ident = Binder.clearCallingIdentity();
2974 try {
2975 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002976 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002977
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002978 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002979 } finally {
2980 Binder.restoreCallingIdentity(ident);
2981 }
2982 }
2983
Louis Changcdec0802019-11-11 11:45:07 +08002984 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002985 final int callingUid = Binder.getCallingUid();
2986 long ident = Binder.clearCallingIdentity();
2987 try {
2988 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002989 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002990 }
2991 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2992 // task and jumping straight into a call in the case of emergency call back.
2993 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2994 if (tm != null) {
2995 tm.showInCallScreen(false);
2996 }
2997 } finally {
2998 Binder.restoreCallingIdentity(ident);
2999 }
3000 }
3001
3002 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003003 public void updateLockTaskPackages(int userId, String[] packages) {
3004 final int callingUid = Binder.getCallingUid();
3005 if (callingUid != 0 && callingUid != SYSTEM_UID) {
3006 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
3007 "updateLockTaskPackages()");
3008 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08003009 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003010 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
3011 + Arrays.toString(packages));
3012 getLockTaskController().updateLockTaskPackages(userId, packages);
3013 }
3014 }
3015
3016 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003017 public boolean isInLockTaskMode() {
3018 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3019 }
3020
3021 @Override
3022 public int getLockTaskModeState() {
3023 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003024 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003025 }
3026 }
3027
3028 @Override
3029 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3030 synchronized (mGlobalLock) {
3031 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3032 if (r != null) {
3033 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003034 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003035 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003036 }
3037 }
3038 }
3039
3040 @Override
3041 public Bundle getActivityOptions(IBinder token) {
3042 final long origId = Binder.clearCallingIdentity();
3043 try {
3044 synchronized (mGlobalLock) {
3045 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3046 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003047 final ActivityOptions activityOptions = r.takeOptionsLocked(
3048 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003049 return activityOptions == null ? null : activityOptions.toBundle();
3050 }
3051 return null;
3052 }
3053 } finally {
3054 Binder.restoreCallingIdentity(origId);
3055 }
3056 }
3057
3058 @Override
3059 public List<IBinder> getAppTasks(String callingPackage) {
3060 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003061 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003062 long ident = Binder.clearCallingIdentity();
3063 try {
3064 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003065 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003066 }
3067 } finally {
3068 Binder.restoreCallingIdentity(ident);
3069 }
3070 }
3071
3072 @Override
3073 public void finishVoiceTask(IVoiceInteractionSession session) {
3074 synchronized (mGlobalLock) {
3075 final long origId = Binder.clearCallingIdentity();
3076 try {
3077 // TODO: VI Consider treating local voice interactions and voice tasks
3078 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003079 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003080 } finally {
3081 Binder.restoreCallingIdentity(origId);
3082 }
3083 }
3084
3085 }
3086
3087 @Override
3088 public boolean isTopOfTask(IBinder token) {
3089 synchronized (mGlobalLock) {
3090 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003091 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003092 }
3093 }
3094
3095 @Override
3096 public void notifyLaunchTaskBehindComplete(IBinder token) {
3097 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3098 }
3099
3100 @Override
3101 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003102 mH.post(() -> {
3103 synchronized (mGlobalLock) {
3104 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003105 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003106 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003107 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003108 } catch (RemoteException e) {
3109 }
3110 }
3111 }
3112
3113 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003114 }
3115
3116 /** Called from an app when assist data is ready. */
3117 @Override
3118 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3119 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003120 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003121 synchronized (pae) {
3122 pae.result = extras;
3123 pae.structure = structure;
3124 pae.content = content;
3125 if (referrer != null) {
3126 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3127 }
3128 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003129 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003130 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003131 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003132 structure.setHomeActivity(pae.isHome);
3133 }
3134 pae.haveResult = true;
3135 pae.notifyAll();
3136 if (pae.intent == null && pae.receiver == null) {
3137 // Caller is just waiting for the result.
3138 return;
3139 }
3140 }
3141 // We are now ready to launch the assist activity.
3142 IAssistDataReceiver sendReceiver = null;
3143 Bundle sendBundle = null;
3144 synchronized (mGlobalLock) {
3145 buildAssistBundleLocked(pae, extras);
3146 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003147 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003148 if (!exists) {
3149 // Timed out.
3150 return;
3151 }
3152
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003153 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003154 // Caller wants result sent back to them.
3155 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003156 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003157 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003158 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3159 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003160 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3161 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3162 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3163 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3164 }
3165 }
3166 if (sendReceiver != null) {
3167 try {
3168 sendReceiver.onHandleAssistData(sendBundle);
3169 } catch (RemoteException e) {
3170 }
3171 return;
3172 }
3173
3174 final long ident = Binder.clearCallingIdentity();
3175 try {
3176 if (TextUtils.equals(pae.intent.getAction(),
3177 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003178 // Start voice interaction through VoiceInteractionManagerService.
3179 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3180 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003181 } else {
3182 pae.intent.replaceExtras(pae.extras);
3183 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3184 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3185 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003186 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003187
3188 try {
3189 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3190 } catch (ActivityNotFoundException e) {
3191 Slog.w(TAG, "No activity to handle assist action.", e);
3192 }
3193 }
3194 } finally {
3195 Binder.restoreCallingIdentity(ident);
3196 }
3197 }
3198
3199 @Override
3200 public int addAppTask(IBinder activityToken, Intent intent,
3201 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3202 final int callingUid = Binder.getCallingUid();
3203 final long callingIdent = Binder.clearCallingIdentity();
3204
3205 try {
3206 synchronized (mGlobalLock) {
3207 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3208 if (r == null) {
3209 throw new IllegalArgumentException("Activity does not exist; token="
3210 + activityToken);
3211 }
3212 ComponentName comp = intent.getComponent();
3213 if (comp == null) {
3214 throw new IllegalArgumentException("Intent " + intent
3215 + " must specify explicit component");
3216 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003217 if (thumbnail.getWidth() != mThumbnailWidth
3218 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003219 throw new IllegalArgumentException("Bad thumbnail size: got "
3220 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003221 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003222 }
3223 if (intent.getSelector() != null) {
3224 intent.setSelector(null);
3225 }
3226 if (intent.getSourceBounds() != null) {
3227 intent.setSourceBounds(null);
3228 }
3229 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3230 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3231 // The caller has added this as an auto-remove task... that makes no
3232 // sense, so turn off auto-remove.
3233 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3234 }
3235 }
3236 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3237 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3238 if (ainfo.applicationInfo.uid != callingUid) {
3239 throw new SecurityException(
3240 "Can't add task for another application: target uid="
3241 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3242 }
3243
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003244 final ActivityStack stack = r.getRootTask();
Wale Ogunwale0d465192020-01-23 19:14:44 -08003245 final Task task = stack.getDisplay().createStack(stack.getWindowingMode(),
3246 stack.getActivityType(), !ON_TOP, ainfo, intent);
3247
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003248 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003249 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003250 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003251 return INVALID_TASK_ID;
3252 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003253 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003254
3255 // TODO: Send the thumbnail to WM to store it.
3256
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003257 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003258 }
3259 } finally {
3260 Binder.restoreCallingIdentity(callingIdent);
3261 }
3262 }
3263
3264 @Override
3265 public Point getAppTaskThumbnailSize() {
3266 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003267 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003268 }
3269 }
3270
3271 @Override
3272 public void setTaskResizeable(int taskId, int resizeableMode) {
3273 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003274 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003275 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3276 if (task == null) {
3277 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3278 return;
3279 }
3280 task.setResizeMode(resizeableMode);
3281 }
3282 }
3283
3284 @Override
3285 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003286 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003287 long ident = Binder.clearCallingIdentity();
3288 try {
3289 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003290 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003291 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003292 if (task == null) {
3293 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3294 return;
3295 }
3296 // Place the task in the right stack if it isn't there already based on
3297 // the requested bounds.
3298 // The stack transition logic is:
3299 // - a null bounds on a freeform task moves that task to fullscreen
3300 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3301 // that task to freeform
3302 // - otherwise the task is not moved
3303 ActivityStack stack = task.getStack();
3304 if (!task.getWindowConfiguration().canResizeTask()) {
3305 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3306 }
3307 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3308 stack = stack.getDisplay().getOrCreateStack(
3309 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3310 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3311 stack = stack.getDisplay().getOrCreateStack(
3312 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3313 }
3314
3315 // Reparent the task to the right stack if necessary
3316 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3317 if (stack != task.getStack()) {
3318 // Defer resume until the task is resized below
3319 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3320 DEFER_RESUME, "resizeTask");
3321 preserveWindow = false;
3322 }
3323
3324 // After reparenting (which only resizes the task to the stack bounds), resize the
3325 // task to the actual bounds provided
3326 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3327 }
3328 } finally {
3329 Binder.restoreCallingIdentity(ident);
3330 }
3331 }
3332
3333 @Override
3334 public boolean releaseActivityInstance(IBinder token) {
3335 synchronized (mGlobalLock) {
3336 final long origId = Binder.clearCallingIdentity();
3337 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003338 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3339 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003340 return false;
3341 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003342 r.destroyImmediately(true /* removeFromApp */, "app-req");
3343 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003344 } finally {
3345 Binder.restoreCallingIdentity(origId);
3346 }
3347 }
3348 }
3349
3350 @Override
3351 public void releaseSomeActivities(IApplicationThread appInt) {
3352 synchronized (mGlobalLock) {
3353 final long origId = Binder.clearCallingIdentity();
3354 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003355 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003356 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003357 } finally {
3358 Binder.restoreCallingIdentity(origId);
3359 }
3360 }
3361 }
3362
3363 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003364 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003365 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003366 != PackageManager.PERMISSION_GRANTED) {
3367 throw new SecurityException("Requires permission "
3368 + android.Manifest.permission.DEVICE_POWER);
3369 }
3370
3371 synchronized (mGlobalLock) {
3372 long ident = Binder.clearCallingIdentity();
3373 if (mKeyguardShown != keyguardShowing) {
3374 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003375 final Message msg = PooledLambda.obtainMessage(
3376 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3377 keyguardShowing);
3378 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003379 }
3380 try {
wilsonshih177261f2019-02-22 12:02:18 +08003381 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003382 } finally {
3383 Binder.restoreCallingIdentity(ident);
3384 }
3385 }
3386
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003387 mH.post(() -> {
3388 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3389 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3390 }
3391 });
3392 }
3393
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003394 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003395 mH.post(() -> {
3396 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3397 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3398 }
3399 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003400 }
3401
3402 @Override
3403 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003404 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3405 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003406
3407 final File passedIconFile = new File(filePath);
3408 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3409 passedIconFile.getName());
3410 if (!legitIconFile.getPath().equals(filePath)
3411 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3412 throw new IllegalArgumentException("Bad file path: " + filePath
3413 + " passed for userId " + userId);
3414 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003415 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416 }
3417
3418 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003419 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003420 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003421 synchronized (mGlobalLock) {
3422 final long ident = Binder.clearCallingIdentity();
3423 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003424 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003425 if (stack == null) {
3426 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3427 return;
3428 }
3429 if (!stack.isActivityTypeStandardOrUndefined()) {
3430 throw new IllegalArgumentException(
3431 "Removing non-standard stack is not allowed.");
3432 }
3433 mStackSupervisor.removeStack(stack);
3434 } finally {
3435 Binder.restoreCallingIdentity(ident);
3436 }
3437 }
3438 }
3439
3440 @Override
3441 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003442 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003443
3444 synchronized (mGlobalLock) {
3445 final long ident = Binder.clearCallingIdentity();
3446 try {
3447 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3448 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003449 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003450 } finally {
3451 Binder.restoreCallingIdentity(ident);
3452 }
3453 }
3454 }
3455
3456 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003457 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003458 synchronized (mGlobalLock) {
3459 long ident = Binder.clearCallingIdentity();
3460 try {
3461 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3462 if (r == null) {
3463 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003464 "toggleFreeformWindowingMode: No activity record matching token="
3465 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003466 }
3467
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003468 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003469 if (stack == null) {
3470 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3471 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003472 }
3473
Yunfan Chend967af82019-01-17 18:30:18 +09003474 if (!stack.inFreeformWindowingMode()
3475 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3476 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3477 + "toggle between fullscreen and freeform.");
3478 }
3479
3480 if (stack.inFreeformWindowingMode()) {
3481 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003482 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003483 throw new IllegalStateException("Size-compat windows are currently not"
3484 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003485 } else if (stack.getParent().inFreeformWindowingMode()) {
3486 // If the window is on a freeform display, set it to undefined. It will be
3487 // resolved to freeform and it can adjust windowing mode when the display mode
3488 // changes in runtime.
3489 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003490 } else {
3491 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3492 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003493 } finally {
3494 Binder.restoreCallingIdentity(ident);
3495 }
3496 }
3497 }
3498
3499 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3500 @Override
3501 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003502 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003503 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003504 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003505 }
3506
3507 /** Unregister a task stack listener so that it stops receiving callbacks. */
3508 @Override
3509 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003510 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003511 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003512 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003513 }
3514
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003515 @Override
3516 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3517 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3518 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3519 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3520 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3521 }
3522
3523 @Override
3524 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3525 IBinder activityToken, int flags) {
3526 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3527 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3528 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3529 }
3530
3531 @Override
3532 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3533 Bundle args) {
3534 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3535 true /* focused */, true /* newSessionId */, userHandle, args,
3536 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3537 }
3538
3539 @Override
3540 public Bundle getAssistContextExtras(int requestType) {
3541 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3542 null, null, true /* focused */, true /* newSessionId */,
3543 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3544 if (pae == null) {
3545 return null;
3546 }
3547 synchronized (pae) {
3548 while (!pae.haveResult) {
3549 try {
3550 pae.wait();
3551 } catch (InterruptedException e) {
3552 }
3553 }
3554 }
3555 synchronized (mGlobalLock) {
3556 buildAssistBundleLocked(pae, pae.result);
3557 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003558 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003559 }
3560 return pae.extras;
3561 }
3562
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003563 /**
3564 * Binder IPC calls go through the public entry point.
3565 * This can be called with or without the global lock held.
3566 */
3567 private static int checkCallingPermission(String permission) {
3568 return checkPermission(
3569 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3570 }
3571
3572 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003573 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003574 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3575 mAmInternal.enforceCallingPermission(permission, func);
3576 }
3577 }
3578
3579 @VisibleForTesting
3580 int checkGetTasksPermission(String permission, int pid, int uid) {
3581 return checkPermission(permission, pid, uid);
3582 }
3583
3584 static int checkPermission(String permission, int pid, int uid) {
3585 if (permission == null) {
3586 return PackageManager.PERMISSION_DENIED;
3587 }
3588 return checkComponentPermission(permission, pid, uid, -1, true);
3589 }
3590
Wale Ogunwale214f3482018-10-04 11:00:47 -07003591 public static int checkComponentPermission(String permission, int pid, int uid,
3592 int owningUid, boolean exported) {
3593 return ActivityManagerService.checkComponentPermission(
3594 permission, pid, uid, owningUid, exported);
3595 }
3596
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003597 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3598 if (getRecentTasks().isCallerRecents(callingUid)) {
3599 // Always allow the recents component to get tasks
3600 return true;
3601 }
3602
3603 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3604 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3605 if (!allowed) {
3606 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3607 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3608 // Temporary compatibility: some existing apps on the system image may
3609 // still be requesting the old permission and not switched to the new
3610 // one; if so, we'll still allow them full access. This means we need
3611 // to see if they are holding the old permission and are a system app.
3612 try {
3613 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3614 allowed = true;
3615 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3616 + " is using old GET_TASKS but privileged; allowing");
3617 }
3618 } catch (RemoteException e) {
3619 }
3620 }
3621 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3622 + " does not hold REAL_GET_TASKS; limiting output");
3623 }
3624 return allowed;
3625 }
3626
Nicholas Sauer0259e532019-08-30 08:24:55 -07003627 boolean isCrossUserAllowed(int pid, int uid) {
3628 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3629 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3630 }
3631
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003632 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3633 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3634 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3635 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003636 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003637 "enqueueAssistContext()");
3638
3639 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08003640 final ActivityStack stack = getTopDisplayFocusedStack();
3641 ActivityRecord activity = stack != null ? stack.getTopNonFinishingActivity() : null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003642 if (activity == null) {
3643 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3644 return null;
3645 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003646 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003647 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3648 return null;
3649 }
3650 if (focused) {
3651 if (activityToken != null) {
3652 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3653 if (activity != caller) {
3654 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3655 + " is not current top " + activity);
3656 return null;
3657 }
3658 }
3659 } else {
3660 activity = ActivityRecord.forTokenLocked(activityToken);
3661 if (activity == null) {
3662 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3663 + " couldn't be found");
3664 return null;
3665 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003666 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003667 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3668 return null;
3669 }
3670 }
3671
3672 PendingAssistExtras pae;
3673 Bundle extras = new Bundle();
3674 if (args != null) {
3675 extras.putAll(args);
3676 }
3677 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003678 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003679
3680 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3681 userHandle);
3682 pae.isHome = activity.isActivityTypeHome();
3683
3684 // Increment the sessionId if necessary
3685 if (newSessionId) {
3686 mViSessionId++;
3687 }
3688 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003689 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3690 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003691 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003692 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003693 } catch (RemoteException e) {
3694 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3695 return null;
3696 }
3697 return pae;
3698 }
3699 }
3700
3701 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3702 if (result != null) {
3703 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3704 }
3705 if (pae.hint != null) {
3706 pae.extras.putBoolean(pae.hint, true);
3707 }
3708 }
3709
3710 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3711 IAssistDataReceiver receiver;
3712 synchronized (mGlobalLock) {
3713 mPendingAssistExtras.remove(pae);
3714 receiver = pae.receiver;
3715 }
3716 if (receiver != null) {
3717 // Caller wants result sent back to them.
3718 Bundle sendBundle = new Bundle();
3719 // At least return the receiver extras
3720 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3721 try {
3722 pae.receiver.onHandleAssistData(sendBundle);
3723 } catch (RemoteException e) {
3724 }
3725 }
3726 }
3727
3728 public class PendingAssistExtras extends Binder implements Runnable {
3729 public final ActivityRecord activity;
3730 public boolean isHome;
3731 public final Bundle extras;
3732 public final Intent intent;
3733 public final String hint;
3734 public final IAssistDataReceiver receiver;
3735 public final int userHandle;
3736 public boolean haveResult = false;
3737 public Bundle result = null;
3738 public AssistStructure structure = null;
3739 public AssistContent content = null;
3740 public Bundle receiverExtras;
3741
3742 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3743 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3744 int _userHandle) {
3745 activity = _activity;
3746 extras = _extras;
3747 intent = _intent;
3748 hint = _hint;
3749 receiver = _receiver;
3750 receiverExtras = _receiverExtras;
3751 userHandle = _userHandle;
3752 }
3753
3754 @Override
3755 public void run() {
3756 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3757 synchronized (this) {
3758 haveResult = true;
3759 notifyAll();
3760 }
3761 pendingAssistExtrasTimedOut(this);
3762 }
3763 }
3764
3765 @Override
3766 public boolean isAssistDataAllowedOnCurrentActivity() {
3767 int userId;
3768 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003769 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003770 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3771 return false;
3772 }
3773
Wale Ogunwale21e06482019-11-18 05:14:15 -08003774 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003775 if (activity == null) {
3776 return false;
3777 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003778 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003779 }
3780 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3781 }
3782
3783 @Override
3784 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3785 long ident = Binder.clearCallingIdentity();
3786 try {
3787 synchronized (mGlobalLock) {
3788 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003789 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003790 if (top != caller) {
3791 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3792 + " is not current top " + top);
3793 return false;
3794 }
3795 if (!top.nowVisible) {
3796 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3797 + " is not visible");
3798 return false;
3799 }
3800 }
3801 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3802 token);
3803 } finally {
3804 Binder.restoreCallingIdentity(ident);
3805 }
3806 }
3807
3808 @Override
3809 public boolean isRootVoiceInteraction(IBinder token) {
3810 synchronized (mGlobalLock) {
3811 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3812 if (r == null) {
3813 return false;
3814 }
3815 return r.rootVoiceInteraction;
3816 }
3817 }
3818
Wale Ogunwalef6733932018-06-27 05:14:34 -07003819 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3820 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3821 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3822 if (activityToCallback == null) return;
3823 activityToCallback.setVoiceSessionLocked(voiceSession);
3824
3825 // Inform the activity
3826 try {
3827 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3828 voiceInteractor);
3829 long token = Binder.clearCallingIdentity();
3830 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003831 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003832 } finally {
3833 Binder.restoreCallingIdentity(token);
3834 }
3835 // TODO: VI Should we cache the activity so that it's easier to find later
3836 // rather than scan through all the stacks and activities?
3837 } catch (RemoteException re) {
3838 activityToCallback.clearVoiceSessionLocked();
3839 // TODO: VI Should this terminate the voice session?
3840 }
3841 }
3842
3843 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3844 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3845 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3846 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3847 boolean wasRunningVoice = mRunningVoice != null;
3848 mRunningVoice = session;
3849 if (!wasRunningVoice) {
3850 mVoiceWakeLock.acquire();
3851 updateSleepIfNeededLocked();
3852 }
3853 }
3854 }
3855
3856 void finishRunningVoiceLocked() {
3857 if (mRunningVoice != null) {
3858 mRunningVoice = null;
3859 mVoiceWakeLock.release();
3860 updateSleepIfNeededLocked();
3861 }
3862 }
3863
3864 @Override
3865 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3866 synchronized (mGlobalLock) {
3867 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3868 if (keepAwake) {
3869 mVoiceWakeLock.acquire();
3870 } else {
3871 mVoiceWakeLock.release();
3872 }
3873 }
3874 }
3875 }
3876
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003877 @Override
3878 public ComponentName getActivityClassForToken(IBinder token) {
3879 synchronized (mGlobalLock) {
3880 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3881 if (r == null) {
3882 return null;
3883 }
3884 return r.intent.getComponent();
3885 }
3886 }
3887
3888 @Override
3889 public String getPackageForToken(IBinder token) {
3890 synchronized (mGlobalLock) {
3891 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3892 if (r == null) {
3893 return null;
3894 }
3895 return r.packageName;
3896 }
3897 }
3898
3899 @Override
3900 public void showLockTaskEscapeMessage(IBinder token) {
3901 synchronized (mGlobalLock) {
3902 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3903 if (r == null) {
3904 return;
3905 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003906 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003907 }
3908 }
3909
3910 @Override
3911 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003912 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003913 final long token = Binder.clearCallingIdentity();
3914 try {
3915 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003916 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003917 }
3918 } finally {
3919 Binder.restoreCallingIdentity(token);
3920 }
3921 }
3922
3923 /**
3924 * Try to place task to provided position. The final position might be different depending on
3925 * current user and stacks state. The task will be moved to target stack if it's currently in
3926 * different stack.
3927 */
3928 @Override
3929 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003930 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003931 synchronized (mGlobalLock) {
3932 long ident = Binder.clearCallingIdentity();
3933 try {
3934 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3935 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003936 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003937 if (task == null) {
3938 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3939 + taskId);
3940 }
3941
Louis Chang149d5c82019-12-30 09:47:39 +08003942 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003943
3944 if (stack == null) {
3945 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3946 + stackId);
3947 }
3948 if (!stack.isActivityTypeStandardOrUndefined()) {
3949 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3950 + " the position of task " + taskId + " in/to non-standard stack");
3951 }
3952
3953 // TODO: Have the callers of this API call a separate reparent method if that is
3954 // what they intended to do vs. having this method also do reparenting.
3955 if (task.getStack() == stack) {
3956 // Change position in current stack.
3957 stack.positionChildAt(task, position);
3958 } else {
3959 // Reparent to new stack.
3960 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3961 !DEFER_RESUME, "positionTaskInStack");
3962 }
3963 } finally {
3964 Binder.restoreCallingIdentity(ident);
3965 }
3966 }
3967 }
3968
3969 @Override
3970 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3971 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3972 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003973 + Arrays.toString(horizontalSizeConfiguration) + " "
3974 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003975 synchronized (mGlobalLock) {
3976 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3977 if (record == null) {
3978 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3979 + "found for: " + token);
3980 }
3981 record.setSizeConfigurations(horizontalSizeConfiguration,
3982 verticalSizeConfigurations, smallestSizeConfigurations);
3983 }
3984 }
3985
3986 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003987 * Dismisses Pip
3988 * @param animate True if the dismissal should be animated.
3989 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3990 * default animation duration should be used.
3991 */
3992 @Override
3993 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003994 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003995 final long ident = Binder.clearCallingIdentity();
3996 try {
3997 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003998 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08003999 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004000 if (stack == null) {
4001 Slog.w(TAG, "dismissPip: pinned stack not found.");
4002 return;
4003 }
4004 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4005 throw new IllegalArgumentException("Stack: " + stack
4006 + " doesn't support animated resize.");
4007 }
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004008 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004009 }
4010 } finally {
4011 Binder.restoreCallingIdentity(ident);
4012 }
4013 }
4014
4015 @Override
4016 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004017 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004018 synchronized (mGlobalLock) {
4019 mSuppressResizeConfigChanges = suppress;
4020 }
4021 }
4022
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004023 @Override
4024 // TODO: API should just be about changing windowing modes...
4025 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004026 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004027 "moveTasksToFullscreenStack()");
4028 synchronized (mGlobalLock) {
4029 final long origId = Binder.clearCallingIdentity();
4030 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004031 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004032 if (stack != null){
4033 if (!stack.isActivityTypeStandardOrUndefined()) {
4034 throw new IllegalArgumentException(
4035 "You can't move tasks from non-standard stacks.");
4036 }
4037 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4038 }
4039 } finally {
4040 Binder.restoreCallingIdentity(origId);
4041 }
4042 }
4043 }
4044
4045 /**
4046 * Moves the top activity in the input stackId to the pinned stack.
4047 *
4048 * @param stackId Id of stack to move the top activity to pinned stack.
4049 * @param bounds Bounds to use for pinned stack.
4050 *
4051 * @return True if the top activity of the input stack was successfully moved to the pinned
4052 * stack.
4053 */
4054 @Override
4055 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004056 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004057 "moveTopActivityToPinnedStack()");
4058 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004059 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004060 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4061 + "Device doesn't support picture-in-picture mode");
4062 }
4063
4064 long ident = Binder.clearCallingIdentity();
4065 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004066 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004067 } finally {
4068 Binder.restoreCallingIdentity(ident);
4069 }
4070 }
4071 }
4072
4073 @Override
4074 public boolean isInMultiWindowMode(IBinder token) {
4075 final long origId = Binder.clearCallingIdentity();
4076 try {
4077 synchronized (mGlobalLock) {
4078 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4079 if (r == null) {
4080 return false;
4081 }
4082 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4083 return r.inMultiWindowMode();
4084 }
4085 } finally {
4086 Binder.restoreCallingIdentity(origId);
4087 }
4088 }
4089
4090 @Override
4091 public boolean isInPictureInPictureMode(IBinder token) {
4092 final long origId = Binder.clearCallingIdentity();
4093 try {
4094 synchronized (mGlobalLock) {
4095 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4096 }
4097 } finally {
4098 Binder.restoreCallingIdentity(origId);
4099 }
4100 }
4101
4102 private boolean isInPictureInPictureMode(ActivityRecord r) {
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004103 return r != null
4104 && r.getRootTask() != null
4105 && r.inPinnedWindowingMode()
4106 && r.getRootTask().isInStackLocked(r) != null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004107 }
4108
4109 @Override
4110 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4111 final long origId = Binder.clearCallingIdentity();
4112 try {
4113 synchronized (mGlobalLock) {
4114 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4115 "enterPictureInPictureMode", token, params);
4116
4117 // If the activity is already in picture in picture mode, then just return early
4118 if (isInPictureInPictureMode(r)) {
4119 return true;
4120 }
4121
4122 // Activity supports picture-in-picture, now check that we can enter PiP at this
4123 // point, if it is
4124 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4125 false /* beforeStopping */)) {
4126 return false;
4127 }
4128
4129 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004130 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004131 if (r.getParent() == null) {
4132 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4133 return;
4134 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004135 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004136 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004137 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4138 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4139 // Adjust the source bounds by the insets for the transition down
4140 final Rect sourceBounds = new Rect(
4141 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004142 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004143 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004144 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004145 stack.setPictureInPictureAspectRatio(aspectRatio);
4146 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004147 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4148 r.info.applicationInfo.uid, r.shortComponentName,
4149 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004150 logPictureInPictureArgs(params);
4151 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004152 };
4153
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004154 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004155 // If the keyguard is showing or occluded, then try and dismiss it before
4156 // entering picture-in-picture (this will prompt the user to authenticate if the
4157 // device is currently locked).
4158 dismissKeyguard(token, new KeyguardDismissCallback() {
4159 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004160 public void onDismissSucceeded() {
4161 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004162 }
4163 }, null /* message */);
4164 } else {
4165 // Enter picture in picture immediately otherwise
4166 enterPipRunnable.run();
4167 }
4168 return true;
4169 }
4170 } finally {
4171 Binder.restoreCallingIdentity(origId);
4172 }
4173 }
4174
4175 @Override
4176 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4177 final long origId = Binder.clearCallingIdentity();
4178 try {
4179 synchronized (mGlobalLock) {
4180 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4181 "setPictureInPictureParams", token, params);
4182
4183 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004184 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004185 if (r.inPinnedWindowingMode()) {
4186 // If the activity is already in picture-in-picture, update the pinned stack now
4187 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4188 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004189 final ActivityStack stack = r.getRootTask();
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004190 stack.setPictureInPictureAspectRatio(
4191 r.pictureInPictureArgs.getAspectRatio());
4192 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004193 }
4194 logPictureInPictureArgs(params);
4195 }
4196 } finally {
4197 Binder.restoreCallingIdentity(origId);
4198 }
4199 }
4200
4201 @Override
4202 public int getMaxNumPictureInPictureActions(IBinder token) {
4203 // Currently, this is a static constant, but later, we may change this to be dependent on
4204 // the context of the activity
4205 return 3;
4206 }
4207
4208 private void logPictureInPictureArgs(PictureInPictureParams params) {
4209 if (params.hasSetActions()) {
4210 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4211 params.getActions().size());
4212 }
4213 if (params.hasSetAspectRatio()) {
4214 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4215 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4216 MetricsLogger.action(lm);
4217 }
4218 }
4219
4220 /**
4221 * Checks the state of the system and the activity associated with the given {@param token} to
4222 * verify that picture-in-picture is supported for that activity.
4223 *
4224 * @return the activity record for the given {@param token} if all the checks pass.
4225 */
4226 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4227 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004228 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004229 throw new IllegalStateException(caller
4230 + ": Device doesn't support picture-in-picture mode.");
4231 }
4232
4233 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4234 if (r == null) {
4235 throw new IllegalStateException(caller
4236 + ": Can't find activity for token=" + token);
4237 }
4238
4239 if (!r.supportsPictureInPicture()) {
4240 throw new IllegalStateException(caller
4241 + ": Current activity does not support picture-in-picture.");
4242 }
4243
4244 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004245 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004246 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004247 final float minAspectRatio = mContext.getResources().getFloat(
4248 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4249 final float maxAspectRatio = mContext.getResources().getFloat(
4250 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4251 throw new IllegalArgumentException(String.format(caller
4252 + ": Aspect ratio is too extreme (must be between %f and %f).",
4253 minAspectRatio, maxAspectRatio));
4254 }
4255
4256 // Truncate the number of actions if necessary
4257 params.truncateActions(getMaxNumPictureInPictureActions(token));
4258
4259 return r;
4260 }
4261
4262 @Override
4263 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004264 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004265 synchronized (mGlobalLock) {
4266 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4267 if (r == null) {
4268 throw new IllegalArgumentException("Activity does not exist; token="
4269 + activityToken);
4270 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004271 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004272 }
4273 }
4274
Evan Rosky73a7fe92019-11-18 18:28:01 -08004275 // TODO(b/149338177): remove when CTS no-longer requires it
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004276 @Override
4277 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4278 Rect tempDockedTaskInsetBounds,
4279 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004280 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004281 long ident = Binder.clearCallingIdentity();
4282 try {
4283 synchronized (mGlobalLock) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08004284 final DisplayContent dc = mRootWindowContainer.getDefaultDisplay();
4285 TaskTile primary = null;
4286 TaskTile secondary = null;
4287 for (int i = dc.getStackCount() - 1; i >= 0; --i) {
4288 final TaskTile t = dc.getStackAt(i).asTile();
4289 if (t == null) {
4290 continue;
4291 }
4292 if (t.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
4293 primary = t;
4294 } else if (t.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY) {
4295 secondary = t;
4296 }
4297 }
4298 if (primary == null || secondary == null) {
4299 return;
4300 }
4301 final WindowContainerTransaction wct = new WindowContainerTransaction();
4302 final Rect primaryRect =
4303 tempDockedTaskInsetBounds != null ? tempDockedTaskInsetBounds
4304 : (tempDockedTaskBounds != null ? tempDockedTaskBounds
4305 : dockedBounds);
4306 wct.setBounds(primary.mRemoteToken, primaryRect);
4307 Rect otherRect = tempOtherTaskInsetBounds != null ? tempOtherTaskInsetBounds
4308 : tempOtherTaskBounds;
4309 if (otherRect == null) {
4310 // Temporary estimation... again this is just for tests.
4311 otherRect = new Rect(secondary.getBounds());
4312 if (dc.getBounds().width() > dc.getBounds().height()) {
4313 otherRect.left = primaryRect.right + 6;
4314 } else {
4315 otherRect.top = primaryRect.bottom + 6;
4316 }
4317 }
4318 wct.setBounds(secondary.mRemoteToken, otherRect);
4319 mTaskOrganizerController.applyContainerTransaction(wct, null /* organizer */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004320 }
4321 } finally {
4322 Binder.restoreCallingIdentity(ident);
4323 }
4324 }
4325
4326 @Override
4327 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004328 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004329 final long ident = Binder.clearCallingIdentity();
4330 try {
4331 synchronized (mGlobalLock) {
4332 mStackSupervisor.setSplitScreenResizing(resizing);
4333 }
4334 } finally {
4335 Binder.restoreCallingIdentity(ident);
4336 }
4337 }
4338
Evan Rosky0037e5f2019-11-05 10:26:24 -08004339 @Override
4340 public ITaskOrganizerController getTaskOrganizerController() {
4341 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
4342 "getTaskOrganizerController()");
4343 return mTaskOrganizerController;
4344 }
4345
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004346 /**
4347 * Check that we have the features required for VR-related API calls, and throw an exception if
4348 * not.
4349 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004350 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004351 if (!mContext.getPackageManager().hasSystemFeature(
4352 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4353 throw new UnsupportedOperationException("VR mode not supported on this device!");
4354 }
4355 }
4356
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004357 @Override
4358 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004359 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004360
4361 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4362
4363 ActivityRecord r;
4364 synchronized (mGlobalLock) {
4365 r = ActivityRecord.isInStackLocked(token);
4366 }
4367
4368 if (r == null) {
4369 throw new IllegalArgumentException();
4370 }
4371
4372 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004373 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004374 VrManagerInternal.NO_ERROR) {
4375 return err;
4376 }
4377
4378 // Clear the binder calling uid since this path may call moveToTask().
4379 final long callingId = Binder.clearCallingIdentity();
4380 try {
4381 synchronized (mGlobalLock) {
4382 r.requestedVrComponent = (enabled) ? packageName : null;
4383
4384 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004385 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004386 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004387 }
4388 return 0;
4389 }
4390 } finally {
4391 Binder.restoreCallingIdentity(callingId);
4392 }
4393 }
4394
4395 @Override
4396 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4397 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4398 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004399 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004400 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4401 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4402 }
Louis Changcdec0802019-11-11 11:45:07 +08004403 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004404 || activity.voiceSession != null) {
4405 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4406 return;
4407 }
4408 if (activity.pendingVoiceInteractionStart) {
4409 Slog.w(TAG, "Pending start of voice interaction already.");
4410 return;
4411 }
4412 activity.pendingVoiceInteractionStart = true;
4413 }
4414 LocalServices.getService(VoiceInteractionManagerInternal.class)
4415 .startLocalVoiceInteraction(callingActivity, options);
4416 }
4417
4418 @Override
4419 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4420 LocalServices.getService(VoiceInteractionManagerInternal.class)
4421 .stopLocalVoiceInteraction(callingActivity);
4422 }
4423
4424 @Override
4425 public boolean supportsLocalVoiceInteraction() {
4426 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4427 .supportsLocalVoiceInteraction();
4428 }
4429
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004430 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004431 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004432 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004433
4434 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004435 if (mWindowManager == null) {
4436 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4437 return false;
4438 }
4439
4440 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004441 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004442 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004443 }
4444
Riddle Hsua0022cd2019-09-09 21:12:41 +08004445 mH.sendMessage(PooledLambda.obtainMessage(
4446 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4447 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004448
4449 final long origId = Binder.clearCallingIdentity();
4450 try {
4451 if (values != null) {
4452 Settings.System.clearConfiguration(values);
4453 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004454 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004455 UserHandle.USER_NULL, false /* deferResume */,
4456 mTmpUpdateConfigurationResult);
4457 return mTmpUpdateConfigurationResult.changes != 0;
4458 } finally {
4459 Binder.restoreCallingIdentity(origId);
4460 }
4461 }
4462 }
4463
4464 @Override
4465 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4466 CharSequence message) {
4467 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004468 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004469 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4470 }
4471 final long callingId = Binder.clearCallingIdentity();
4472 try {
4473 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004474 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004475 }
4476 } finally {
4477 Binder.restoreCallingIdentity(callingId);
4478 }
4479 }
4480
4481 @Override
4482 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004483 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004484 "cancelTaskWindowTransition()");
4485 final long ident = Binder.clearCallingIdentity();
4486 try {
4487 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004488 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004489 MATCH_TASK_IN_STACKS_ONLY);
4490 if (task == null) {
4491 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4492 return;
4493 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004494 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004495 }
4496 } finally {
4497 Binder.restoreCallingIdentity(ident);
4498 }
4499 }
4500
4501 @Override
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004502 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004503 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004504 final long ident = Binder.clearCallingIdentity();
4505 try {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004506 return getTaskSnapshot(taskId, isLowResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004507 } finally {
4508 Binder.restoreCallingIdentity(ident);
4509 }
4510 }
4511
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004512 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004513 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004514 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004515 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004516 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004517 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4518 if (task == null) {
4519 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4520 return null;
4521 }
4522 }
4523 // Don't call this while holding the lock as this operation might hit the disk.
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004524 return task.getSnapshot(isLowResolution, restoreFromDisk);
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004525 }
4526
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004527 @Override
4528 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4529 synchronized (mGlobalLock) {
4530 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4531 if (r == null) {
4532 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4533 + token);
4534 return;
4535 }
4536 final long origId = Binder.clearCallingIdentity();
4537 try {
4538 r.setDisablePreviewScreenshots(disable);
4539 } finally {
4540 Binder.restoreCallingIdentity(origId);
4541 }
4542 }
4543 }
4544
Riddle Hsu440f88b2019-11-06 22:17:35 +08004545 @Override
4546 public void invalidateHomeTaskSnapshot(IBinder token) {
4547 synchronized (mGlobalLock) {
4548 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4549 if (r == null || !r.isActivityTypeHome()) {
4550 return;
4551 }
4552 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4553 }
4554 }
4555
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004556 /** Return the user id of the last resumed activity. */
4557 @Override
4558 public @UserIdInt
4559 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004560 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004561 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4562 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004563 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004564 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004565 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004566 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004567 }
4568 }
4569
4570 @Override
4571 public void updateLockTaskFeatures(int userId, int flags) {
4572 final int callingUid = Binder.getCallingUid();
4573 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004574 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004575 "updateLockTaskFeatures()");
4576 }
4577 synchronized (mGlobalLock) {
4578 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4579 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004580 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004581 }
4582 }
4583
4584 @Override
4585 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4586 synchronized (mGlobalLock) {
4587 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4588 if (r == null) {
4589 return;
4590 }
4591 final long origId = Binder.clearCallingIdentity();
4592 try {
4593 r.setShowWhenLocked(showWhenLocked);
4594 } finally {
4595 Binder.restoreCallingIdentity(origId);
4596 }
4597 }
4598 }
4599
4600 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004601 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4602 synchronized (mGlobalLock) {
4603 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4604 if (r == null) {
4605 return;
4606 }
4607 final long origId = Binder.clearCallingIdentity();
4608 try {
4609 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4610 } finally {
4611 Binder.restoreCallingIdentity(origId);
4612 }
4613 }
4614 }
4615
4616 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004617 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4618 synchronized (mGlobalLock) {
4619 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4620 if (r == null) {
4621 return;
4622 }
4623 final long origId = Binder.clearCallingIdentity();
4624 try {
4625 r.setTurnScreenOn(turnScreenOn);
4626 } finally {
4627 Binder.restoreCallingIdentity(origId);
4628 }
4629 }
4630 }
4631
4632 @Override
4633 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004634 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004635 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004636 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004637 synchronized (mGlobalLock) {
4638 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4639 if (r == null) {
4640 return;
4641 }
4642 final long origId = Binder.clearCallingIdentity();
4643 try {
4644 r.registerRemoteAnimations(definition);
4645 } finally {
4646 Binder.restoreCallingIdentity(origId);
4647 }
4648 }
4649 }
4650
4651 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004652 public void unregisterRemoteAnimations(IBinder token) {
4653 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4654 "unregisterRemoteAnimations");
4655 synchronized (mGlobalLock) {
4656 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4657 if (r == null) {
4658 return;
4659 }
4660 final long origId = Binder.clearCallingIdentity();
4661 try {
4662 r.unregisterRemoteAnimations();
4663 } finally {
4664 Binder.restoreCallingIdentity(origId);
4665 }
4666 }
4667 }
4668
4669 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004670 public void registerRemoteAnimationForNextActivityStart(String packageName,
4671 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004672 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004673 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004674 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004675 synchronized (mGlobalLock) {
4676 final long origId = Binder.clearCallingIdentity();
4677 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004678 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004679 packageName, adapter);
4680 } finally {
4681 Binder.restoreCallingIdentity(origId);
4682 }
4683 }
4684 }
4685
Evan Rosky966759f2019-01-15 10:33:58 -08004686 @Override
4687 public void registerRemoteAnimationsForDisplay(int displayId,
4688 RemoteAnimationDefinition definition) {
4689 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4690 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004691 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004692 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004693 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004694 if (display == null) {
4695 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4696 return;
4697 }
4698 final long origId = Binder.clearCallingIdentity();
4699 try {
4700 display.mDisplayContent.registerRemoteAnimations(definition);
4701 } finally {
4702 Binder.restoreCallingIdentity(origId);
4703 }
4704 }
4705 }
4706
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004707 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4708 @Override
4709 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4710 synchronized (mGlobalLock) {
4711 final long origId = Binder.clearCallingIdentity();
4712 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004713 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004714 } finally {
4715 Binder.restoreCallingIdentity(origId);
4716 }
4717 }
4718 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004719
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004720 @Override
4721 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004722 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004723 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004724 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004725 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004726 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004727 }
4728 }
4729
4730 @Override
4731 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004732 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004733 != PERMISSION_GRANTED) {
4734 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4735 + Binder.getCallingPid()
4736 + ", uid=" + Binder.getCallingUid()
4737 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4738 Slog.w(TAG, msg);
4739 throw new SecurityException(msg);
4740 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004741 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004742 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004743 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004744 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004745 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004746 }
4747 }
4748
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004749 @Override
4750 public void stopAppSwitches() {
4751 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4752 synchronized (mGlobalLock) {
4753 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004754 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004755 mDidAppSwitch = false;
4756 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4757 }
4758 }
4759
4760 @Override
4761 public void resumeAppSwitches() {
4762 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4763 synchronized (mGlobalLock) {
4764 // Note that we don't execute any pending app switches... we will
4765 // let those wait until either the timeout, or the next start
4766 // activity request.
4767 mAppSwitchesAllowedTime = 0;
4768 }
4769 }
4770
Ricky Wai906af482019-06-03 17:25:28 +01004771 long getLastStopAppSwitchesTime() {
4772 return mLastStopAppSwitchesTime;
4773 }
4774
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004775 void onStartActivitySetDidAppSwitch() {
4776 if (mDidAppSwitch) {
4777 // This is the second allowed switch since we stopped switches, so now just generally
4778 // allow switches. Use case:
4779 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4780 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4781 // anyone to switch again).
4782 mAppSwitchesAllowedTime = 0;
4783 } else {
4784 mDidAppSwitch = true;
4785 }
4786 }
4787
4788 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004789 boolean shouldDisableNonVrUiLocked() {
4790 return mVrController.shouldDisableNonVrUiLocked();
4791 }
4792
Wale Ogunwale53783742018-09-16 10:21:51 -07004793 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004794 // 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 +00004795 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004796 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004797 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4798 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004799 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004800 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004801 }
4802 mH.post(() -> {
4803 if (!mVrController.onVrModeChanged(r)) {
4804 return;
4805 }
4806 synchronized (mGlobalLock) {
4807 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4808 mWindowManager.disableNonVrUi(disableNonVrUi);
4809 if (disableNonVrUi) {
4810 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4811 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004812 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004813 }
4814 }
4815 });
4816 }
4817
Wale Ogunwale53783742018-09-16 10:21:51 -07004818 @Override
4819 public int getPackageScreenCompatMode(String packageName) {
4820 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4821 synchronized (mGlobalLock) {
4822 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4823 }
4824 }
4825
4826 @Override
4827 public void setPackageScreenCompatMode(String packageName, int mode) {
4828 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4829 "setPackageScreenCompatMode");
4830 synchronized (mGlobalLock) {
4831 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4832 }
4833 }
4834
4835 @Override
4836 public boolean getPackageAskScreenCompat(String packageName) {
4837 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4838 synchronized (mGlobalLock) {
4839 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4840 }
4841 }
4842
4843 @Override
4844 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4845 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4846 "setPackageAskScreenCompat");
4847 synchronized (mGlobalLock) {
4848 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4849 }
4850 }
4851
Wale Ogunwale64258362018-10-16 15:13:37 -07004852 public static String relaunchReasonToString(int relaunchReason) {
4853 switch (relaunchReason) {
4854 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4855 return "window_resize";
4856 case RELAUNCH_REASON_FREE_RESIZE:
4857 return "free_resize";
4858 default:
4859 return null;
4860 }
4861 }
4862
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004863 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004864 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004865 }
4866
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004867 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004868 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004869 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4870 }
4871
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004872 boolean isKeyguardLocked() {
4873 return mKeyguardController.isKeyguardLocked();
4874 }
4875
Garfield Tan01548632018-11-27 10:15:48 -08004876 /**
4877 * Clears launch params for the given package.
4878 * @param packageNames the names of the packages of which the launch params are to be cleared
4879 */
4880 @Override
4881 public void clearLaunchParamsForPackages(List<String> packageNames) {
4882 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4883 "clearLaunchParamsForPackages");
4884 synchronized (mGlobalLock) {
4885 for (int i = 0; i < packageNames.size(); ++i) {
4886 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4887 }
4888 }
4889 }
4890
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004891 /**
4892 * Makes the display with the given id a single task instance display. I.e the display can only
4893 * contain one task.
4894 */
4895 @Override
4896 public void setDisplayToSingleTaskInstance(int displayId) {
4897 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4898 "setDisplayToSingleTaskInstance");
4899 final long origId = Binder.clearCallingIdentity();
4900 try {
Louis Chang677921f2019-12-06 16:44:24 +08004901 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004902 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004903 if (display != null) {
4904 display.setDisplayToSingleTaskInstance();
4905 }
4906 } finally {
4907 Binder.restoreCallingIdentity(origId);
4908 }
4909 }
4910
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004911 /**
4912 * Requests that an activity should enter picture-in-picture mode if possible.
4913 */
4914 @Override
4915 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4916 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4917 "requestPictureInPictureMode");
4918 final long origId = Binder.clearCallingIdentity();
4919 try {
4920 synchronized (mGlobalLock) {
4921 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4922 if (activity == null) {
4923 return;
4924 }
4925
4926 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4927 "requestPictureInPictureMode", /* beforeStopping */ false);
4928 if (!canEnterPictureInPicture) {
4929 throw new IllegalStateException(
4930 "Requested PIP on an activity that doesn't support it");
4931 }
4932
4933 try {
4934 final ClientTransaction transaction = ClientTransaction.obtain(
4935 activity.app.getThread(),
4936 activity.token);
4937 transaction.addCallback(EnterPipRequestedItem.obtain());
4938 getLifecycleManager().scheduleTransaction(transaction);
4939 } catch (Exception e) {
4940 Slog.w(TAG, "Failed to send enter pip requested item: "
4941 + activity.intent.getComponent(), e);
4942 }
4943 }
4944 } finally {
4945 Binder.restoreCallingIdentity(origId);
4946 }
4947 }
4948
Wale Ogunwale31913b52018-10-13 08:29:31 -07004949 void dumpLastANRLocked(PrintWriter pw) {
4950 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4951 if (mLastANRState == null) {
4952 pw.println(" <no ANR has occurred since boot>");
4953 } else {
4954 pw.println(mLastANRState);
4955 }
4956 }
4957
4958 void dumpLastANRTracesLocked(PrintWriter pw) {
4959 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4960
4961 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4962 if (ArrayUtils.isEmpty(files)) {
4963 pw.println(" <no ANR has occurred since boot>");
4964 return;
4965 }
4966 // Find the latest file.
4967 File latest = null;
4968 for (File f : files) {
4969 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4970 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004971 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004972 }
4973 pw.print("File: ");
4974 pw.print(latest.getName());
4975 pw.println();
4976 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4977 String line;
4978 while ((line = in.readLine()) != null) {
4979 pw.println(line);
4980 }
4981 } catch (IOException e) {
4982 pw.print("Unable to read: ");
4983 pw.print(e);
4984 pw.println();
4985 }
4986 }
4987
4988 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4989 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4990 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4991 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4992 }
4993
4994 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4995 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4996 pw.println(header);
4997
Louis Chang149d5c82019-12-30 09:47:39 +08004998 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004999 dumpPackage);
5000 boolean needSep = printedAnything;
5001
5002 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08005003 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005004 " ResumedActivity: ");
5005 if (printed) {
5006 printedAnything = true;
5007 needSep = false;
5008 }
5009
5010 if (dumpPackage == null) {
5011 if (needSep) {
5012 pw.println();
5013 }
5014 printedAnything = true;
5015 mStackSupervisor.dump(pw, " ");
5016 }
5017
5018 if (!printedAnything) {
5019 pw.println(" (nothing)");
5020 }
5021 }
5022
5023 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005024 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005025 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005026 pw.println(" ");
5027 }
5028
5029 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5030 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5031 getActivityStartController().dump(pw, "", dumpPackage);
5032 }
5033
5034 /**
5035 * There are three things that cmd can be:
5036 * - a flattened component name that matches an existing activity
5037 * - the cmd arg isn't the flattened component name of an existing activity:
5038 * dump all activity whose component contains the cmd as a substring
5039 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005040 * <p>
5041 * The caller should not hold lock when calling this method because it will wait for the
5042 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005043 *
5044 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5045 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5046 */
5047 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5048 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5049 ArrayList<ActivityRecord> activities;
5050
5051 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005052 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005053 dumpFocusedStackOnly);
5054 }
5055
5056 if (activities.size() <= 0) {
5057 return false;
5058 }
5059
5060 String[] newArgs = new String[args.length - opti];
5061 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5062
Louis Changcdec0802019-11-11 11:45:07 +08005063 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005064 boolean needSep = false;
5065 for (int i = activities.size() - 1; i >= 0; i--) {
5066 ActivityRecord r = activities.get(i);
5067 if (needSep) {
5068 pw.println();
5069 }
5070 needSep = true;
5071 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005072 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005073 if (lastTask != task) {
5074 lastTask = task;
5075 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005076 pw.print(" id="); pw.print(lastTask.mTaskId);
5077 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005078 if (dumpAll) {
5079 lastTask.dump(pw, " ");
5080 }
5081 }
5082 }
5083 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5084 }
5085 return true;
5086 }
5087
5088 /**
5089 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5090 * there is a thread associated with the activity.
5091 */
5092 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5093 final ActivityRecord r, String[] args, boolean dumpAll) {
5094 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005095 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005096 synchronized (mGlobalLock) {
5097 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5098 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5099 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005100 if (r.hasProcess()) {
5101 pw.println(r.app.getPid());
5102 appThread = r.app.getThread();
5103 } else {
5104 pw.println("(not running)");
5105 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005106 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005107 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005108 }
5109 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005110 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005111 // flush anything that is already in the PrintWriter since the thread is going
5112 // to write to the file descriptor directly
5113 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005114 try (TransferPipe tp = new TransferPipe()) {
5115 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5116 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005117 } catch (IOException e) {
5118 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5119 } catch (RemoteException e) {
5120 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5121 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005122 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005123 }
5124
sanryhuang498e77e2018-12-06 14:57:01 +08005125 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5126 boolean testPssMode) {
5127 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5128 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5129 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005130 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005131 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5132 st.toString());
5133 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005134 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5135 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5136 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005137 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5138 testPssMode);
5139 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005140 }
5141
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005142 int getCurrentUserId() {
5143 return mAmInternal.getCurrentUserId();
5144 }
5145
5146 private void enforceNotIsolatedCaller(String caller) {
5147 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5148 throw new SecurityException("Isolated process not allowed to call " + caller);
5149 }
5150 }
5151
Wale Ogunwalef6733932018-06-27 05:14:34 -07005152 public Configuration getConfiguration() {
5153 Configuration ci;
5154 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005155 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005156 ci.userSetLocale = false;
5157 }
5158 return ci;
5159 }
5160
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005161 /**
5162 * Current global configuration information. Contains general settings for the entire system,
5163 * also corresponds to the merged configuration of the default display.
5164 */
5165 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005166 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005167 // while initializing process record for system, see {@link
5168 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005169 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005170 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005171 }
5172
5173 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5174 boolean initLocale) {
5175 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5176 }
5177
5178 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5179 boolean initLocale, boolean deferResume) {
5180 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5181 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5182 UserHandle.USER_NULL, deferResume);
5183 }
5184
Wale Ogunwale59507092018-10-29 09:00:30 -07005185 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005186 final long origId = Binder.clearCallingIdentity();
5187 try {
5188 synchronized (mGlobalLock) {
5189 updateConfigurationLocked(values, null, false, true, userId,
5190 false /* deferResume */);
5191 }
5192 } finally {
5193 Binder.restoreCallingIdentity(origId);
5194 }
5195 }
5196
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005197 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5198 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5199 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5200 deferResume, null /* result */);
5201 }
5202
5203 /**
5204 * Do either or both things: (1) change the current configuration, and (2)
5205 * make sure the given activity is running with the (now) current
5206 * configuration. Returns true if the activity has been left running, or
5207 * false if <var>starting</var> is being destroyed to match the new
5208 * configuration.
5209 *
5210 * @param userId is only used when persistent parameter is set to true to persist configuration
5211 * for that particular user
5212 */
5213 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5214 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5215 ActivityTaskManagerService.UpdateConfigurationResult result) {
5216 int changes = 0;
5217 boolean kept = true;
5218
Riddle Hsua0022cd2019-09-09 21:12:41 +08005219 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005220 try {
5221 if (values != null) {
5222 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5223 deferResume);
5224 }
5225
5226 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5227 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005228 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005229 }
5230
5231 if (result != null) {
5232 result.changes = changes;
5233 result.activityRelaunched = !kept;
5234 }
5235 return kept;
5236 }
5237
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005238 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005239 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005240 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005241
Louis Chang677921f2019-12-06 16:44:24 +08005242 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005243 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005244
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005245 mTempConfig.setTo(getGlobalConfiguration());
5246 final int changes = mTempConfig.updateFrom(values);
5247 if (changes == 0) {
5248 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5249 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5250 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5251 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005252 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005253 return 0;
5254 }
5255
5256 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5257 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005258 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005259 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005260 values.colorMode,
5261 values.densityDpi,
5262 values.fontScale,
5263 values.hardKeyboardHidden,
5264 values.keyboard,
5265 values.keyboardHidden,
5266 values.mcc,
5267 values.mnc,
5268 values.navigation,
5269 values.navigationHidden,
5270 values.orientation,
5271 values.screenHeightDp,
5272 values.screenLayout,
5273 values.screenWidthDp,
5274 values.smallestScreenWidthDp,
5275 values.touchscreen,
5276 values.uiMode);
5277
5278
5279 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5280 final LocaleList locales = values.getLocales();
5281 int bestLocaleIndex = 0;
5282 if (locales.size() > 1) {
5283 if (mSupportedSystemLocales == null) {
5284 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5285 }
5286 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5287 }
5288 SystemProperties.set("persist.sys.locale",
5289 locales.get(bestLocaleIndex).toLanguageTag());
5290 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005291
5292 final Message m = PooledLambda.obtainMessage(
5293 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5294 locales.get(bestLocaleIndex));
5295 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005296 }
5297
Yunfan Chen75157d72018-07-27 14:47:21 +09005298 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005299
5300 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005301 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005302
5303 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5304 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005305 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005306
5307 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005308 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005309
5310 AttributeCache ac = AttributeCache.instance();
5311 if (ac != null) {
5312 ac.updateConfiguration(mTempConfig);
5313 }
5314
5315 // Make sure all resources in our process are updated right now, so that anyone who is going
5316 // to retrieve resource values after we return will be sure to get the new ones. This is
5317 // especially important during boot, where the first config change needs to guarantee all
5318 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005319 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005320
5321 // We need another copy of global config because we're scheduling some calls instead of
5322 // running them in place. We need to be sure that object we send will be handled unchanged.
5323 final Configuration configCopy = new Configuration(mTempConfig);
5324 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005325 final Message msg = PooledLambda.obtainMessage(
5326 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5327 this, userId, configCopy);
5328 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005329 }
5330
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005331 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5332 for (int i = pidMap.size() - 1; i >= 0; i--) {
5333 final int pid = pidMap.keyAt(i);
5334 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005335 if (DEBUG_CONFIGURATION) {
5336 Slog.v(TAG_CONFIGURATION, "Update process config of "
5337 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005338 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005339 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005340 }
5341
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005342 final Message msg = PooledLambda.obtainMessage(
5343 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5344 mAmInternal, changes, initLocale);
5345 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005346
5347 // Override configuration of the default display duplicates global config, so we need to
5348 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005349 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005350 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005351
5352 return changes;
5353 }
5354
Riddle Hsua0022cd2019-09-09 21:12:41 +08005355 /** @see WindowSurfacePlacer#deferLayout */
5356 void deferWindowLayout() {
5357 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5358 // Reset the reasons at the first entrance because we only care about the changes in the
5359 // deferred scope.
5360 mLayoutReasons = 0;
5361 }
5362
5363 mWindowManager.mWindowPlacerLocked.deferLayout();
5364 }
5365
5366 /** @see WindowSurfacePlacer#continueLayout */
5367 void continueWindowLayout() {
5368 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5369 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5370 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5371 }
5372 }
5373
5374 /**
5375 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5376 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5377 * defer count is gone.
5378 */
5379 void addWindowLayoutReasons(@LayoutReason int reasons) {
5380 mLayoutReasons |= reasons;
5381 }
5382
Wale Ogunwalef6733932018-06-27 05:14:34 -07005383 private void updateEventDispatchingLocked(boolean booted) {
5384 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5385 }
5386
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005387 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5388 final ContentResolver resolver = mContext.getContentResolver();
5389 Settings.System.putConfigurationForUser(resolver, config, userId);
5390 }
5391
5392 private void sendLocaleToMountDaemonMsg(Locale l) {
5393 try {
5394 IBinder service = ServiceManager.getService("mount");
5395 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5396 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5397 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5398 } catch (RemoteException e) {
5399 Log.e(TAG, "Error storing locale for decryption UI", e);
5400 }
5401 }
5402
Alison Cichowlas3e340502018-08-07 17:15:01 -04005403 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5404 mStartActivitySources.remove(permissionToken);
5405 mExpiredStartAsCallerTokens.add(permissionToken);
5406 }
5407
5408 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5409 mExpiredStartAsCallerTokens.remove(permissionToken);
5410 }
5411
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005412 boolean isActivityStartsLoggingEnabled() {
5413 return mAmInternal.isActivityStartsLoggingEnabled();
5414 }
5415
Michal Karpinski8596ded2018-11-14 14:43:48 +00005416 boolean isBackgroundActivityStartsEnabled() {
5417 return mAmInternal.isBackgroundActivityStartsEnabled();
5418 }
5419
Wale Ogunwalef6733932018-06-27 05:14:34 -07005420 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005421 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005422 mWindowManager.enableScreenAfterBoot();
5423
5424 synchronized (mGlobalLock) {
5425 updateEventDispatchingLocked(booted);
5426 }
5427 }
5428
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005429 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5430 if (r == null || !r.hasProcess()) {
5431 return KEY_DISPATCHING_TIMEOUT_MS;
5432 }
5433 return getInputDispatchingTimeoutLocked(r.app);
5434 }
5435
5436 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005437 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005438 }
5439
Wale Ogunwalef6733932018-06-27 05:14:34 -07005440 /**
5441 * Decide based on the configuration whether we should show the ANR,
5442 * crash, etc dialogs. The idea is that if there is no affordance to
5443 * press the on-screen buttons, or the user experience would be more
5444 * greatly impacted than the crash itself, we shouldn't show the dialog.
5445 *
5446 * A thought: SystemUI might also want to get told about this, the Power
5447 * dialog / global actions also might want different behaviors.
5448 */
5449 private void updateShouldShowDialogsLocked(Configuration config) {
5450 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5451 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5452 && config.navigation == Configuration.NAVIGATION_NONAV);
5453 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5454 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5455 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5456 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5457 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5458 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5459 HIDE_ERROR_DIALOGS, 0) != 0;
5460 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5461 }
5462
5463 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5464 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5465 FONT_SCALE, 1.0f, userId);
5466
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005467 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005468 if (getGlobalConfiguration().fontScale == scaleFactor) {
5469 return;
5470 }
5471
5472 final Configuration configuration
5473 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5474 configuration.fontScale = scaleFactor;
5475 updatePersistentConfiguration(configuration, userId);
5476 }
5477 }
5478
5479 // Actually is sleeping or shutting down or whatever else in the future
5480 // is an inactive state.
5481 boolean isSleepingOrShuttingDownLocked() {
5482 return isSleepingLocked() || mShuttingDown;
5483 }
5484
5485 boolean isSleepingLocked() {
5486 return mSleeping;
5487 }
5488
Riddle Hsu16567132018-08-16 21:37:47 +08005489 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005490 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005491 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005492 if (task.isActivityTypeStandard()) {
5493 if (mCurAppTimeTracker != r.appTimeTracker) {
5494 // We are switching app tracking. Complete the current one.
5495 if (mCurAppTimeTracker != null) {
5496 mCurAppTimeTracker.stop();
5497 mH.obtainMessage(
5498 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005499 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005500 mCurAppTimeTracker = null;
5501 }
5502 if (r.appTimeTracker != null) {
5503 mCurAppTimeTracker = r.appTimeTracker;
5504 startTimeTrackingFocusedActivityLocked();
5505 }
5506 } else {
5507 startTimeTrackingFocusedActivityLocked();
5508 }
5509 } else {
5510 r.appTimeTracker = null;
5511 }
5512 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5513 // TODO: Probably not, because we don't want to resume voice on switching
5514 // back to this activity
5515 if (task.voiceInteractor != null) {
5516 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5517 } else {
5518 finishRunningVoiceLocked();
5519
5520 if (mLastResumedActivity != null) {
5521 final IVoiceInteractionSession session;
5522
Louis Changcdec0802019-11-11 11:45:07 +08005523 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005524 if (lastResumedActivityTask != null
5525 && lastResumedActivityTask.voiceSession != null) {
5526 session = lastResumedActivityTask.voiceSession;
5527 } else {
5528 session = mLastResumedActivity.voiceSession;
5529 }
5530
5531 if (session != null) {
5532 // We had been in a voice interaction session, but now focused has
5533 // move to something different. Just finish the session, we can't
5534 // return to it and retain the proper state and synchronization with
5535 // the voice interaction service.
5536 finishVoiceTask(session);
5537 }
5538 }
5539 }
5540
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005541 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5542 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005543 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005544 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5545
Wale Ogunwalef6733932018-06-27 05:14:34 -07005546 updateResumedAppTrace(r);
5547 mLastResumedActivity = r;
5548
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005549 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005550
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005551 if (prevTask == null || task != prevTask) {
5552 if (prevTask != null) {
5553 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5554 }
5555 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5556 }
5557
Wale Ogunwalef6733932018-06-27 05:14:34 -07005558 applyUpdateLockStateLocked(r);
5559 applyUpdateVrModeLocked(r);
5560
Jeff Changd136e772019-11-05 20:33:52 +08005561 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005562 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005563 r == null ? "NULL" : r.shortComponentName,
5564 reason);
5565 }
5566
5567 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5568 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005569 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005570 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005571 updateSleepIfNeededLocked();
5572 return token;
5573 }
5574 }
5575
5576 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005577 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005578 final boolean wasSleeping = mSleeping;
5579 boolean updateOomAdj = false;
5580
5581 if (!shouldSleep) {
5582 // If wasSleeping is true, we need to wake up activity manager state from when
5583 // we started sleeping. In either case, we need to apply the sleep tokens, which
5584 // will wake up stacks or put them to sleep as appropriate.
5585 if (wasSleeping) {
5586 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005587 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5588 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005589 startTimeTrackingFocusedActivityLocked();
5590 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005591 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005592 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5593 }
Louis Chang149d5c82019-12-30 09:47:39 +08005594 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005595 if (wasSleeping) {
5596 updateOomAdj = true;
5597 }
5598 } else if (!mSleeping && shouldSleep) {
5599 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005600 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5601 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005602 if (mCurAppTimeTracker != null) {
5603 mCurAppTimeTracker.stop();
5604 }
5605 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005606 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005607 mStackSupervisor.goingToSleepLocked();
5608 updateResumedAppTrace(null /* resumed */);
5609 updateOomAdj = true;
5610 }
5611 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005612 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005613 }
5614 }
5615
5616 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005617 mH.removeCallbacks(mUpdateOomAdjRunnable);
5618 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005619 }
5620
Wale Ogunwale53783742018-09-16 10:21:51 -07005621 void updateCpuStats() {
5622 mH.post(mAmInternal::updateCpuStats);
5623 }
5624
Hui Yu03d12402018-12-06 18:00:37 -08005625 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5626 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005627 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5628 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005629 mH.sendMessage(m);
5630 }
5631
Hui Yu03d12402018-12-06 18:00:37 -08005632 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005633 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005634 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005635 if (task != null) {
5636 final ActivityRecord rootActivity = task.getRootActivity();
5637 if (rootActivity != null) {
5638 taskRoot = rootActivity.mActivityComponent;
5639 }
5640 }
5641
Hui Yu03d12402018-12-06 18:00:37 -08005642 final Message m = PooledLambda.obtainMessage(
5643 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005644 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005645 mH.sendMessage(m);
5646 }
5647
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005648 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5649 String hostingType) {
5650 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005651 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5652 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005653 + activity.processName);
5654 }
5655 // Post message to start process to avoid possible deadlock of calling into AMS with the
5656 // ATMS lock held.
5657 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5658 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5659 isTop, hostingType, activity.intent.getComponent());
5660 mH.sendMessage(m);
5661 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005662 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005663 }
5664 }
5665
Wale Ogunwale53783742018-09-16 10:21:51 -07005666 void setBooting(boolean booting) {
5667 mAmInternal.setBooting(booting);
5668 }
5669
5670 boolean isBooting() {
5671 return mAmInternal.isBooting();
5672 }
5673
5674 void setBooted(boolean booted) {
5675 mAmInternal.setBooted(booted);
5676 }
5677
5678 boolean isBooted() {
5679 return mAmInternal.isBooted();
5680 }
5681
5682 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5683 mH.post(() -> {
5684 if (finishBooting) {
5685 mAmInternal.finishBooting();
5686 }
5687 if (enableScreen) {
5688 mInternal.enableScreenAfterBoot(isBooted());
5689 }
5690 });
5691 }
5692
5693 void setHeavyWeightProcess(ActivityRecord root) {
5694 mHeavyWeightProcess = root.app;
5695 final Message m = PooledLambda.obtainMessage(
5696 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005697 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005698 mH.sendMessage(m);
5699 }
5700
5701 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5702 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5703 return;
5704 }
5705
5706 mHeavyWeightProcess = null;
5707 final Message m = PooledLambda.obtainMessage(
5708 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5709 proc.mUserId);
5710 mH.sendMessage(m);
5711 }
5712
5713 private void cancelHeavyWeightProcessNotification(int userId) {
5714 final INotificationManager inm = NotificationManager.getService();
5715 if (inm == null) {
5716 return;
5717 }
5718 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005719 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005720 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5721 } catch (RuntimeException e) {
5722 Slog.w(TAG, "Error canceling notification for service", e);
5723 } catch (RemoteException e) {
5724 }
5725
5726 }
5727
5728 private void postHeavyWeightProcessNotification(
5729 WindowProcessController proc, Intent intent, int userId) {
5730 if (proc == null) {
5731 return;
5732 }
5733
5734 final INotificationManager inm = NotificationManager.getService();
5735 if (inm == null) {
5736 return;
5737 }
5738
5739 try {
5740 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5741 String text = mContext.getString(R.string.heavy_weight_notification,
5742 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5743 Notification notification =
5744 new Notification.Builder(context,
5745 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5746 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5747 .setWhen(0)
5748 .setOngoing(true)
5749 .setTicker(text)
5750 .setColor(mContext.getColor(
5751 com.android.internal.R.color.system_notification_accent_color))
5752 .setContentTitle(text)
5753 .setContentText(
5754 mContext.getText(R.string.heavy_weight_notification_detail))
5755 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5756 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5757 new UserHandle(userId)))
5758 .build();
5759 try {
5760 inm.enqueueNotificationWithTag("android", "android", null,
5761 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5762 } catch (RuntimeException e) {
5763 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5764 } catch (RemoteException e) {
5765 }
5766 } catch (PackageManager.NameNotFoundException e) {
5767 Slog.w(TAG, "Unable to create context for heavy notification", e);
5768 }
5769
5770 }
5771
Philip P. Moltmannee295092020-02-10 08:46:26 -08005772 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5773 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5774 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005775
5776 ActivityRecord activity = null;
5777 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5778 activity = ActivityRecord.isInStackLocked(token);
5779 if (activity == null) {
5780 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5781 return null;
5782 }
5783 if (activity.finishing) {
5784 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5785 return null;
5786 }
5787 }
5788
5789 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005790 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5791 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005792 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5793 if (noCreate) {
5794 return rec;
5795 }
5796 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5797 if (activity.pendingResults == null) {
5798 activity.pendingResults = new HashSet<>();
5799 }
5800 activity.pendingResults.add(rec.ref);
5801 }
5802 return rec;
5803 }
5804
Andrii Kulian52d255c2018-07-13 11:32:19 -07005805 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005806 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005807 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005808 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5809 mCurAppTimeTracker.start(resumedActivity.packageName);
5810 }
5811 }
5812
5813 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5814 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005815 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005816 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5817 }
5818 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005819 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005820 constructResumedTraceName(resumed.packageName), 0);
5821 }
5822 mTracedResumedActivity = resumed;
5823 }
5824
5825 private String constructResumedTraceName(String packageName) {
5826 return "focused app: " + packageName;
5827 }
5828
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005829 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005830 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005831 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005832 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005833 // mainStack is null during startup.
5834 if (mainStack != null) {
5835 if (changes != 0 && starting == null) {
5836 // If the configuration changed, and the caller is not already
5837 // in the process of starting an activity, then find the top
5838 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005839 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005840 }
5841
5842 if (starting != null) {
5843 kept = starting.ensureActivityConfiguration(changes,
5844 false /* preserveWindow */);
5845 // And we need to make sure at this point that all other activities
5846 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005847 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005848 !PRESERVE_WINDOWS);
5849 }
5850 }
5851
5852 return kept;
5853 }
5854
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005855 void scheduleAppGcsLocked() {
5856 mH.post(() -> mAmInternal.scheduleAppGcs());
5857 }
5858
Wale Ogunwale53783742018-09-16 10:21:51 -07005859 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5860 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5861 }
5862
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005863 /**
5864 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5865 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5866 * on demand.
5867 */
5868 IPackageManager getPackageManager() {
5869 return AppGlobals.getPackageManager();
5870 }
5871
5872 PackageManagerInternal getPackageManagerInternalLocked() {
5873 if (mPmInternal == null) {
5874 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5875 }
5876 return mPmInternal;
5877 }
5878
Darryl L Johnsona0982222020-02-18 18:21:51 -08005879 ComponentName getSysUiServiceComponentLocked() {
5880 if (mSysUiServiceComponent == null) {
5881 final PackageManagerInternal pm = getPackageManagerInternalLocked();
5882 mSysUiServiceComponent = pm.getSystemUiServiceComponent();
5883 }
5884 return mSysUiServiceComponent;
5885 }
5886
Hai Zhangf4da9be2019-05-01 13:46:06 +08005887 PermissionPolicyInternal getPermissionPolicyInternal() {
5888 if (mPermissionPolicyInternal == null) {
5889 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5890 }
5891 return mPermissionPolicyInternal;
5892 }
5893
Wale Ogunwale008163e2018-07-23 23:11:08 -07005894 AppWarnings getAppWarningsLocked() {
5895 return mAppWarnings;
5896 }
5897
Wale Ogunwale214f3482018-10-04 11:00:47 -07005898 Intent getHomeIntent() {
5899 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5900 intent.setComponent(mTopComponent);
5901 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5902 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5903 intent.addCategory(Intent.CATEGORY_HOME);
5904 }
5905 return intent;
5906 }
5907
Chilun2ef71f72018-11-16 17:57:15 +08005908 /**
5909 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5910 * activities.
5911 *
Chilun939b05c2020-02-19 14:50:59 +08005912 * @param preferredPackage Specify a preferred package name, otherwise use the package name
5913 * defined in config_secondaryHomePackage.
Chilun2ef71f72018-11-16 17:57:15 +08005914 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5915 */
5916 Intent getSecondaryHomeIntent(String preferredPackage) {
5917 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005918 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5919 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5920 if (preferredPackage == null || useSystemProvidedLauncher) {
Chilun939b05c2020-02-19 14:50:59 +08005921 // Using the package name stored in config if no preferred package name or forced.
5922 final String secondaryHomePackage = mContext.getResources().getString(
5923 com.android.internal.R.string.config_secondaryHomePackage);
5924 intent.setPackage(secondaryHomePackage);
Chilun2ef71f72018-11-16 17:57:15 +08005925 } else {
5926 intent.setPackage(preferredPackage);
5927 }
5928 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5929 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5930 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5931 }
5932 return intent;
5933 }
5934
Wale Ogunwale214f3482018-10-04 11:00:47 -07005935 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5936 if (info == null) return null;
5937 ApplicationInfo newInfo = new ApplicationInfo(info);
5938 newInfo.initForUser(userId);
5939 return newInfo;
5940 }
5941
Wale Ogunwale9c103022018-10-18 07:44:54 -07005942 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005943 if (uid == SYSTEM_UID) {
5944 // The system gets to run in any process. If there are multiple processes with the same
5945 // uid, just pick the first (this should never happen).
5946 final SparseArray<WindowProcessController> procs =
5947 mProcessNames.getMap().get(processName);
5948 if (procs == null) return null;
5949 final int procCount = procs.size();
5950 for (int i = 0; i < procCount; i++) {
5951 final int procUid = procs.keyAt(i);
5952 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5953 // Don't use an app process or different user process for system component.
5954 continue;
5955 }
5956 return procs.valueAt(i);
5957 }
5958 }
5959
5960 return mProcessNames.get(processName, uid);
5961 }
5962
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005963 WindowProcessController getProcessController(IApplicationThread thread) {
5964 if (thread == null) {
5965 return null;
5966 }
5967
5968 final IBinder threadBinder = thread.asBinder();
5969 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5970 for (int i = pmap.size()-1; i >= 0; i--) {
5971 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5972 for (int j = procs.size() - 1; j >= 0; j--) {
5973 final WindowProcessController proc = procs.valueAt(j);
5974 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5975 return proc;
5976 }
5977 }
5978 }
5979
5980 return null;
5981 }
5982
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005983 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005984 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005985 if (proc == null) return null;
5986 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5987 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005988 }
5989 return null;
5990 }
5991
Riddle Hsua0536432019-02-16 00:38:59 +08005992 int getUidState(int uid) {
5993 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005994 }
5995
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005996 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005997 // A uid is considered to be foreground if it has a visible non-toast window.
5998 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005999 }
6000
Ricky Wai96f5c352019-04-10 18:40:17 +01006001 boolean isDeviceOwner(int uid) {
6002 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006003 }
6004
Ricky Wai96f5c352019-04-10 18:40:17 +01006005 void setDeviceOwnerUid(int uid) {
6006 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006007 }
6008
Wale Ogunwale9de19442018-10-18 19:05:03 -07006009 /**
6010 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6011 * the whitelist
6012 */
6013 String getPendingTempWhitelistTagForUidLocked(int uid) {
6014 return mPendingTempWhitelist.get(uid);
6015 }
6016
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006017 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6018 if (true || Build.IS_USER) {
6019 return;
6020 }
6021
6022 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6023 StrictMode.allowThreadDiskWrites();
6024 try {
6025 File tracesDir = new File("/data/anr");
6026 File tracesFile = null;
6027 try {
6028 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6029
6030 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006031 String timeString =
6032 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6033 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006034 sb.append(": ");
6035 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6036 sb.append(" since ");
6037 sb.append(msg);
6038 FileOutputStream fos = new FileOutputStream(tracesFile);
6039 fos.write(sb.toString().getBytes());
6040 if (app == null) {
6041 fos.write("\n*** No application process!".getBytes());
6042 }
6043 fos.close();
6044 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6045 } catch (IOException e) {
6046 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6047 return;
6048 }
6049
6050 if (app != null && app.getPid() > 0) {
6051 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6052 firstPids.add(app.getPid());
6053 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6054 }
6055
6056 File lastTracesFile = null;
6057 File curTracesFile = null;
6058 for (int i=9; i>=0; i--) {
6059 String name = String.format(Locale.US, "slow%02d.txt", i);
6060 curTracesFile = new File(tracesDir, name);
6061 if (curTracesFile.exists()) {
6062 if (lastTracesFile != null) {
6063 curTracesFile.renameTo(lastTracesFile);
6064 } else {
6065 curTracesFile.delete();
6066 }
6067 }
6068 lastTracesFile = curTracesFile;
6069 }
6070 tracesFile.renameTo(curTracesFile);
6071 } finally {
6072 StrictMode.setThreadPolicy(oldPolicy);
6073 }
6074 }
6075
Michal Karpinskida34cd42019-04-02 19:46:52 +01006076 boolean isAssociatedCompanionApp(int userId, int uid) {
6077 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6078 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006079 return false;
6080 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006081 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006082 }
6083
Issei Suzuki734bc942019-06-05 13:59:52 +02006084 void notifySingleTaskDisplayEmpty(int displayId) {
6085 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6086 }
6087
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006088 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006089 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006090
6091
Wale Ogunwale98875612018-10-12 07:53:02 -07006092 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6093 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006094
Riddle Hsud93a6c42018-11-29 21:50:06 +08006095 H(Looper looper) {
6096 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006097 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006098
6099 @Override
6100 public void handleMessage(Message msg) {
6101 switch (msg.what) {
6102 case REPORT_TIME_TRACKER_MSG: {
6103 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6104 tracker.deliverResult(mContext);
6105 } break;
6106 }
6107 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006108 }
6109
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006110 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006111 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006112
6113 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006114 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006115 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006116
6117 @Override
6118 public void handleMessage(Message msg) {
6119 switch (msg.what) {
6120 case DISMISS_DIALOG_UI_MSG: {
6121 final Dialog d = (Dialog) msg.obj;
6122 d.dismiss();
6123 break;
6124 }
6125 }
6126 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006127 }
6128
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006129 final class LocalService extends ActivityTaskManagerInternal {
6130 @Override
6131 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006132 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006133 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006134 }
6135
6136 @Override
6137 public ComponentName getHomeActivityForUser(int userId) {
6138 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006139 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006140 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006141 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006142 }
6143 }
6144
6145 @Override
6146 public void onLocalVoiceInteractionStarted(IBinder activity,
6147 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6148 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006149 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006150 }
6151 }
6152
6153 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006154 public void notifySingleTaskDisplayDrawn(int displayId) {
6155 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6156 }
6157
6158 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006159 public void notifyAppTransitionFinished() {
6160 synchronized (mGlobalLock) {
6161 mStackSupervisor.notifyAppTransitionDone();
6162 }
6163 }
6164
6165 @Override
6166 public void notifyAppTransitionCancelled() {
6167 synchronized (mGlobalLock) {
6168 mStackSupervisor.notifyAppTransitionDone();
6169 }
6170 }
6171
6172 @Override
6173 public List<IBinder> getTopVisibleActivities() {
6174 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006175 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006176 }
6177 }
6178
6179 @Override
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00006180 public boolean hasResumedActivity(int uid) {
6181 synchronized (mGlobalLock) {
6182 final ArraySet<WindowProcessController> processes = mProcessMap.getProcesses(uid);
6183 for (int i = 0, n = processes.size(); i < n; i++) {
6184 final WindowProcessController process = processes.valueAt(i);
6185 if (process.hasResumedActivity()) {
6186 return true;
6187 }
6188 }
6189 }
6190 return false;
6191 }
6192
6193 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006194 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6195 int userId, Intent[] intents, Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006196 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006197 final String[] resolvedTypes = new String[intents.length];
6198
6199 // UID of the package on user userId.
6200 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6201 // packageUid may not be initialized.
6202 int packageUid = 0;
6203 final long ident = Binder.clearCallingIdentity();
6204
6205 try {
6206 for (int i = 0; i < intents.length; i++) {
6207 resolvedTypes[i] =
6208 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6209 }
6210
6211 packageUid = AppGlobals.getPackageManager().getPackageUid(
6212 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6213 } catch (RemoteException e) {
6214 // Shouldn't happen.
6215 } finally {
6216 Binder.restoreCallingIdentity(ident);
6217 }
6218
Riddle Hsu591bf612019-02-14 17:55:31 +08006219 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006220 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006221 intents, resolvedTypes, null /* resultTo */,
6222 SafeActivityOptions.fromBundle(bOptions), userId,
6223 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6224 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006225 }
6226
6227 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006228 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006229 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6230 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6231 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006232 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006233 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006234 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006235 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006236 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6237 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006238 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006239 }
6240 }
6241
6242 @Override
6243 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006244 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6245 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6246 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6247 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006248 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006249 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006250 synchronized (mGlobalLock) {
6251 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006252 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6253 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6254 reason, validateIncomingUser, originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006255 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006256 }
6257 }
6258
6259 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006260 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006261 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6262 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006263 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006264 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006265 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006266 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006267 false /*validateIncomingUser*/);
6268 }
6269
6270 @Override
lumark588a3e82018-07-20 18:53:54 +08006271 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006272 synchronized (mGlobalLock) {
6273
6274 // We might change the visibilities here, so prepare an empty app transition which
6275 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006276 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006277 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006278 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006279 return;
6280 }
Louis Chang677921f2019-12-06 16:44:24 +08006281 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006282 final boolean wasTransitionSet =
6283 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006284 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006285 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006286 }
Louis Chang149d5c82019-12-30 09:47:39 +08006287 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006288
6289 // If there was a transition set already we don't want to interfere with it as we
6290 // might be starting it too early.
6291 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006292 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006293 }
6294 }
6295 if (callback != null) {
6296 callback.run();
6297 }
6298 }
6299
6300 @Override
6301 public void notifyKeyguardTrustedChanged() {
6302 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006303 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006304 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006305 }
6306 }
6307 }
6308
6309 /**
6310 * Called after virtual display Id is updated by
6311 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6312 * {@param vrVr2dDisplayId}.
6313 */
6314 @Override
6315 public void setVr2dDisplayId(int vr2dDisplayId) {
6316 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6317 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006318 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006319 }
6320 }
6321
6322 @Override
6323 public void setFocusedActivity(IBinder token) {
6324 synchronized (mGlobalLock) {
6325 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6326 if (r == null) {
6327 throw new IllegalArgumentException(
6328 "setFocusedActivity: No activity record matching token=" + token);
6329 }
Louis Chang19443452018-10-09 12:10:21 +08006330 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006331 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006332 }
6333 }
6334 }
6335
6336 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006337 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006338 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006339 }
6340
6341 @Override
6342 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006343 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006344 }
6345
6346 @Override
6347 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006348 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006349 }
6350
6351 @Override
6352 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6353 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6354 }
6355
6356 @Override
6357 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006358 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006359 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006360
6361 @Override
6362 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6363 synchronized (mGlobalLock) {
6364 mActiveVoiceInteractionServiceComponent = component;
6365 }
6366 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006367
6368 @Override
6369 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6370 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6371 return;
6372 }
6373 synchronized (mGlobalLock) {
6374 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6375 if (types == null) {
6376 if (uid < 0) {
6377 return;
6378 }
6379 types = new ArrayMap<>();
6380 mAllowAppSwitchUids.put(userId, types);
6381 }
6382 if (uid < 0) {
6383 types.remove(type);
6384 } else {
6385 types.put(type, uid);
6386 }
6387 }
6388 }
6389
6390 @Override
6391 public void onUserStopped(int userId) {
6392 synchronized (mGlobalLock) {
6393 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6394 mAllowAppSwitchUids.remove(userId);
6395 }
6396 }
6397
6398 @Override
6399 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6400 synchronized (mGlobalLock) {
6401 return ActivityTaskManagerService.this.isGetTasksAllowed(
6402 caller, callingPid, callingUid);
6403 }
6404 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006405
Riddle Hsua0536432019-02-16 00:38:59 +08006406 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006407 @Override
6408 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006409 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006410 mProcessNames.put(proc.mName, proc.mUid, proc);
6411 }
6412 }
6413
Riddle Hsua0536432019-02-16 00:38:59 +08006414 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006415 @Override
6416 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006417 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006418 mProcessNames.remove(name, uid);
6419 }
6420 }
6421
Riddle Hsua0536432019-02-16 00:38:59 +08006422 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006423 @Override
6424 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006425 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006426 if (proc == mHomeProcess) {
6427 mHomeProcess = null;
6428 }
6429 if (proc == mPreviousProcess) {
6430 mPreviousProcess = null;
6431 }
6432 }
6433 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006434
Riddle Hsua0536432019-02-16 00:38:59 +08006435 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006436 @Override
6437 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006438 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006439 return mTopProcessState;
6440 }
6441 }
6442
Riddle Hsua0536432019-02-16 00:38:59 +08006443 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006444 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006445 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006446 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006447 return proc == mHeavyWeightProcess;
6448 }
6449 }
6450
Riddle Hsua0536432019-02-16 00:38:59 +08006451 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006452 @Override
6453 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006454 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006455 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6456 }
6457 }
6458
6459 @Override
6460 public void finishHeavyWeightApp() {
6461 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006462 if (mHeavyWeightProcess != null) {
6463 mHeavyWeightProcess.finishActivities();
6464 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006465 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6466 mHeavyWeightProcess);
6467 }
6468 }
6469
Riddle Hsua0536432019-02-16 00:38:59 +08006470 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006471 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006472 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006473 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006474 return isSleepingLocked();
6475 }
6476 }
6477
6478 @Override
6479 public boolean isShuttingDown() {
6480 synchronized (mGlobalLock) {
6481 return mShuttingDown;
6482 }
6483 }
6484
6485 @Override
6486 public boolean shuttingDown(boolean booted, int timeout) {
6487 synchronized (mGlobalLock) {
6488 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006489 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006490 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006491 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006492 return mStackSupervisor.shutdownLocked(timeout);
6493 }
6494 }
6495
6496 @Override
6497 public void enableScreenAfterBoot(boolean booted) {
6498 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006499 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006500 mWindowManager.enableScreenAfterBoot();
6501 updateEventDispatchingLocked(booted);
6502 }
6503 }
6504
6505 @Override
6506 public boolean showStrictModeViolationDialog() {
6507 synchronized (mGlobalLock) {
6508 return mShowDialogs && !mSleeping && !mShuttingDown;
6509 }
6510 }
6511
6512 @Override
6513 public void showSystemReadyErrorDialogsIfNeeded() {
6514 synchronized (mGlobalLock) {
6515 try {
6516 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6517 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6518 + " data partition or your device will be unstable.");
6519 mUiHandler.post(() -> {
6520 if (mShowDialogs) {
6521 AlertDialog d = new BaseErrorDialog(mUiContext);
6522 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6523 d.setCancelable(false);
6524 d.setTitle(mUiContext.getText(R.string.android_system_label));
6525 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6526 d.setButton(DialogInterface.BUTTON_POSITIVE,
6527 mUiContext.getText(R.string.ok),
6528 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6529 d.show();
6530 }
6531 });
6532 }
6533 } catch (RemoteException e) {
6534 }
6535
6536 if (!Build.isBuildConsistent()) {
6537 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6538 mUiHandler.post(() -> {
6539 if (mShowDialogs) {
6540 AlertDialog d = new BaseErrorDialog(mUiContext);
6541 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6542 d.setCancelable(false);
6543 d.setTitle(mUiContext.getText(R.string.android_system_label));
6544 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6545 d.setButton(DialogInterface.BUTTON_POSITIVE,
6546 mUiContext.getText(R.string.ok),
6547 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6548 d.show();
6549 }
6550 });
6551 }
6552 }
6553 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006554
6555 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006556 public void onProcessMapped(int pid, WindowProcessController proc) {
6557 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006558 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006559 }
6560 }
6561
6562 @Override
6563 public void onProcessUnMapped(int pid) {
6564 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006565 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006566 }
6567 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006568
6569 @Override
6570 public void onPackageDataCleared(String name) {
6571 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006572 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006573 mAppWarnings.onPackageDataCleared(name);
6574 }
6575 }
6576
6577 @Override
6578 public void onPackageUninstalled(String name) {
6579 synchronized (mGlobalLock) {
6580 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006581 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006582 }
6583 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006584
6585 @Override
6586 public void onPackageAdded(String name, boolean replacing) {
6587 synchronized (mGlobalLock) {
6588 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6589 }
6590 }
6591
6592 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006593 public void onPackageReplaced(ApplicationInfo aInfo) {
6594 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006595 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006596 }
6597 }
6598
6599 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006600 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6601 synchronized (mGlobalLock) {
6602 return compatibilityInfoForPackageLocked(ai);
6603 }
6604 }
6605
Yunfan Chen75157d72018-07-27 14:47:21 +09006606 /**
6607 * Set the corresponding display information for the process global configuration. To be
6608 * called when we need to show IME on a different display.
6609 *
6610 * @param pid The process id associated with the IME window.
6611 * @param displayId The ID of the display showing the IME.
6612 */
6613 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006614 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006615 // Don't update process-level configuration for Multi-Client IME process since other
6616 // IMEs on other displays will also receive this configuration change due to IME
6617 // services use the same application config/context.
6618 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006619
Yunfan Chen75157d72018-07-27 14:47:21 +09006620 if (pid == MY_PID || pid < 0) {
6621 if (DEBUG_CONFIGURATION) {
6622 Slog.w(TAG,
6623 "Trying to update display configuration for system/invalid process.");
6624 }
6625 return;
6626 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006627 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006628 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006629 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006630 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006631 // Call might come when display is not yet added or has been removed.
6632 if (DEBUG_CONFIGURATION) {
6633 Slog.w(TAG, "Trying to update display configuration for non-existing "
6634 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006635 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006636 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006637 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006638 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006639 if (process == null) {
6640 if (DEBUG_CONFIGURATION) {
6641 Slog.w(TAG, "Trying to update display configuration for invalid "
6642 + "process, pid=" + pid);
6643 }
6644 return;
6645 }
lumarkddc77fb2019-06-27 22:22:23 +08006646 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006647 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006648 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006649 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006650
6651 @Override
6652 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006653 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006654 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006655 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006656 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006657 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006658 }
6659 }
6660 }
6661
6662 @Override
6663 public void clearPendingResultForActivity(IBinder activityToken,
6664 WeakReference<PendingIntentRecord> pir) {
6665 synchronized (mGlobalLock) {
6666 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6667 if (r != null && r.pendingResults != null) {
6668 r.pendingResults.remove(pir);
6669 }
6670 }
6671 }
6672
6673 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006674 public ActivityTokens getTopActivityForTask(int taskId) {
6675 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006676 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006677 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006678 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6679 + " Requested task not found");
6680 return null;
6681 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006682 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006683 if (activity == null) {
6684 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6685 + " Requested activity not found");
6686 return null;
6687 }
6688 if (!activity.attachedToProcess()) {
6689 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6690 + activity);
6691 return null;
6692 }
6693 return new ActivityTokens(activity.appToken, activity.assistToken,
6694 activity.app.getThread());
6695 }
6696 }
6697
6698 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006699 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006700 @Nullable String featureId, int callingUid, int userId, IBinder token,
6701 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6702 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006703 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006704 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6705 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006706 }
6707 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006708
6709 @Override
6710 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6711 synchronized (mGlobalLock) {
6712 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6713 if (r == null) {
6714 return null;
6715 }
6716 if (r.mServiceConnectionsHolder == null) {
6717 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6718 ActivityTaskManagerService.this, r);
6719 }
6720
6721 return r.mServiceConnectionsHolder;
6722 }
6723 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006724
6725 @Override
6726 public Intent getHomeIntent() {
6727 synchronized (mGlobalLock) {
6728 return ActivityTaskManagerService.this.getHomeIntent();
6729 }
6730 }
6731
6732 @Override
6733 public boolean startHomeActivity(int userId, String reason) {
6734 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006735 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006736 }
6737 }
6738
6739 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006740 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006741 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006742 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006743 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006744 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006745 }
Chilun8b1f1be2019-03-13 17:14:36 +08006746 }
6747
6748 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006749 public boolean startHomeOnAllDisplays(int userId, String reason) {
6750 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006751 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006752 }
6753 }
6754
Riddle Hsua0536432019-02-16 00:38:59 +08006755 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006756 @Override
6757 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006758 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006759 if (mFactoryTest == FACTORY_TEST_OFF) {
6760 return false;
6761 }
6762 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6763 && wpc.mName.equals(mTopComponent.getPackageName())) {
6764 return true;
6765 }
6766 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6767 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6768 }
6769 }
6770
6771 @Override
6772 public void updateTopComponentForFactoryTest() {
6773 synchronized (mGlobalLock) {
6774 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6775 return;
6776 }
6777 final ResolveInfo ri = mContext.getPackageManager()
6778 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6779 final CharSequence errorMsg;
6780 if (ri != null) {
6781 final ActivityInfo ai = ri.activityInfo;
6782 final ApplicationInfo app = ai.applicationInfo;
6783 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6784 mTopAction = Intent.ACTION_FACTORY_TEST;
6785 mTopData = null;
6786 mTopComponent = new ComponentName(app.packageName, ai.name);
6787 errorMsg = null;
6788 } else {
6789 errorMsg = mContext.getResources().getText(
6790 com.android.internal.R.string.factorytest_not_system);
6791 }
6792 } else {
6793 errorMsg = mContext.getResources().getText(
6794 com.android.internal.R.string.factorytest_no_action);
6795 }
6796 if (errorMsg == null) {
6797 return;
6798 }
6799
6800 mTopAction = null;
6801 mTopData = null;
6802 mTopComponent = null;
6803 mUiHandler.post(() -> {
6804 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6805 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006806 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006807 });
6808 }
6809 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006810
Riddle Hsua0536432019-02-16 00:38:59 +08006811 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006812 @Override
6813 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6814 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006815 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006816 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006817 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006818
6819 wpc.clearRecentTasks();
6820 wpc.clearActivities();
6821
6822 if (wpc.isInstrumenting()) {
6823 finishInstrumentationCallback.run();
6824 }
6825
Jorim Jaggid0752812018-10-16 16:07:20 +02006826 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006827 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006828 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006829 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006830 // If there was nothing to resume, and we are not already restarting
6831 // this process, but there is a visible activity that is hosted by the
6832 // process...then make sure all visible activities are running, taking
6833 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006834 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006835 !PRESERVE_WINDOWS);
6836 }
6837 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006838 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006839 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006840 }
6841 }
6842 }
6843
6844 @Override
6845 public void closeSystemDialogs(String reason) {
6846 enforceNotIsolatedCaller("closeSystemDialogs");
6847
6848 final int pid = Binder.getCallingPid();
6849 final int uid = Binder.getCallingUid();
6850 final long origId = Binder.clearCallingIdentity();
6851 try {
6852 synchronized (mGlobalLock) {
6853 // Only allow this from foreground processes, so that background
6854 // applications can't abuse it to prevent system UI from being shown.
6855 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006856 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006857 if (!proc.isPerceptible()) {
6858 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6859 + " from background process " + proc);
6860 return;
6861 }
6862 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006863 mWindowManager.closeSystemDialogs(reason);
6864
Louis Chang149d5c82019-12-30 09:47:39 +08006865 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006866 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006867 // Call into AM outside the synchronized block.
6868 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006869 } finally {
6870 Binder.restoreCallingIdentity(origId);
6871 }
6872 }
6873
6874 @Override
6875 public void cleanupDisabledPackageComponents(
6876 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6877 synchronized (mGlobalLock) {
6878 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006879 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006880 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006881 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006882 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006883 }
6884
6885 // Clean-up disabled tasks
6886 getRecentTasks().cleanupDisabledPackageTasksLocked(
6887 packageName, disabledClasses, userId);
6888 }
6889 }
6890
6891 @Override
6892 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6893 int userId) {
6894 synchronized (mGlobalLock) {
6895
6896 boolean didSomething =
6897 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006898 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006899 null, doit, evenPersistent, userId);
6900 return didSomething;
6901 }
6902 }
6903
6904 @Override
6905 public void resumeTopActivities(boolean scheduleIdle) {
6906 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006907 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006908 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006909 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006910 }
6911 }
6912 }
6913
Riddle Hsua0536432019-02-16 00:38:59 +08006914 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006915 @Override
6916 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006917 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006918 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6919 }
6920 }
6921
Riddle Hsua0536432019-02-16 00:38:59 +08006922 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006923 @Override
6924 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006925 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006926 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6927 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6928 }
6929 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006930 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006931 } finally {
6932 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6933 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006934 }
6935 }
6936
6937 @Override
6938 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6939 try {
6940 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6941 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6942 }
6943 } catch (RemoteException ex) {
6944 throw new SecurityException("Fail to check is caller a privileged app", ex);
6945 }
6946
6947 synchronized (mGlobalLock) {
6948 final long ident = Binder.clearCallingIdentity();
6949 try {
6950 if (mAmInternal.shouldConfirmCredentials(userId)) {
6951 if (mKeyguardController.isKeyguardLocked()) {
6952 // Showing launcher to avoid user entering credential twice.
6953 startHomeActivity(currentUserId, "notifyLockedProfile");
6954 }
Louis Chang149d5c82019-12-30 09:47:39 +08006955 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006956 }
6957 } finally {
6958 Binder.restoreCallingIdentity(ident);
6959 }
6960 }
6961 }
6962
6963 @Override
6964 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6965 mAmInternal.enforceCallingPermission(
6966 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6967
6968 synchronized (mGlobalLock) {
6969 final long ident = Binder.clearCallingIdentity();
6970 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006971 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6972 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006973 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006974 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6975 UserHandle.CURRENT);
6976 } finally {
6977 Binder.restoreCallingIdentity(ident);
6978 }
6979 }
6980 }
6981
6982 @Override
6983 public void writeActivitiesToProto(ProtoOutputStream proto) {
6984 synchronized (mGlobalLock) {
6985 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006986 mRootWindowContainer.dumpDebug(
6987 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006988 }
6989 }
6990
6991 @Override
6992 public void saveANRState(String reason) {
6993 synchronized (mGlobalLock) {
6994 final StringWriter sw = new StringWriter();
6995 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6996 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6997 if (reason != null) {
6998 pw.println(" Reason: " + reason);
6999 }
7000 pw.println();
7001 getActivityStartController().dump(pw, " ", null);
7002 pw.println();
7003 pw.println("-------------------------------------------------------------------------------");
7004 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7005 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7006 "" /* header */);
7007 pw.println();
7008 pw.close();
7009
7010 mLastANRState = sw.toString();
7011 }
7012 }
7013
7014 @Override
7015 public void clearSavedANRState() {
7016 synchronized (mGlobalLock) {
7017 mLastANRState = null;
7018 }
7019 }
7020
7021 @Override
7022 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7023 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7024 synchronized (mGlobalLock) {
7025 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7026 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7027 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7028 dumpLastANRLocked(pw);
7029 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7030 dumpLastANRTracesLocked(pw);
7031 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7032 dumpActivityStarterLocked(pw, dumpPackage);
7033 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7034 dumpActivityContainersLocked(pw);
7035 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7036 if (getRecentTasks() != null) {
7037 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7038 }
7039 }
7040 }
7041 }
7042
7043 @Override
7044 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7045 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7046 int wakefulness) {
7047 synchronized (mGlobalLock) {
7048 if (mHomeProcess != null && (dumpPackage == null
7049 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7050 if (needSep) {
7051 pw.println();
7052 needSep = false;
7053 }
7054 pw.println(" mHomeProcess: " + mHomeProcess);
7055 }
7056 if (mPreviousProcess != null && (dumpPackage == null
7057 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7058 if (needSep) {
7059 pw.println();
7060 needSep = false;
7061 }
7062 pw.println(" mPreviousProcess: " + mPreviousProcess);
7063 }
7064 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7065 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7066 StringBuilder sb = new StringBuilder(128);
7067 sb.append(" mPreviousProcessVisibleTime: ");
7068 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7069 pw.println(sb);
7070 }
7071 if (mHeavyWeightProcess != null && (dumpPackage == null
7072 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7073 if (needSep) {
7074 pw.println();
7075 needSep = false;
7076 }
7077 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7078 }
7079 if (dumpPackage == null) {
7080 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007081 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007082 }
7083 if (dumpAll) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007084 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7085 if (dumpPackage == null && topFocusedStack != null) {
7086 pw.println(" mConfigWillChange: " + topFocusedStack.mConfigWillChange);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007087 }
7088 if (mCompatModePackages.getPackages().size() > 0) {
7089 boolean printed = false;
7090 for (Map.Entry<String, Integer> entry
7091 : mCompatModePackages.getPackages().entrySet()) {
7092 String pkg = entry.getKey();
7093 int mode = entry.getValue();
7094 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7095 continue;
7096 }
7097 if (!printed) {
7098 pw.println(" mScreenCompatPackages:");
7099 printed = true;
7100 }
7101 pw.println(" " + pkg + ": " + mode);
7102 }
7103 }
7104 }
7105
7106 if (dumpPackage == null) {
7107 pw.println(" mWakefulness="
7108 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007109 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007110 if (mRunningVoice != null) {
7111 pw.println(" mRunningVoice=" + mRunningVoice);
7112 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7113 }
7114 pw.println(" mSleeping=" + mSleeping);
7115 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7116 pw.println(" mVrController=" + mVrController);
7117 }
7118 if (mCurAppTimeTracker != null) {
7119 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7120 }
7121 if (mAllowAppSwitchUids.size() > 0) {
7122 boolean printed = false;
7123 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7124 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7125 for (int j = 0; j < types.size(); j++) {
7126 if (dumpPackage == null ||
7127 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7128 if (needSep) {
7129 pw.println();
7130 needSep = false;
7131 }
7132 if (!printed) {
7133 pw.println(" mAllowAppSwitchUids:");
7134 printed = true;
7135 }
7136 pw.print(" User ");
7137 pw.print(mAllowAppSwitchUids.keyAt(i));
7138 pw.print(": Type ");
7139 pw.print(types.keyAt(j));
7140 pw.print(" = ");
7141 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7142 pw.println();
7143 }
7144 }
7145 }
7146 }
7147 if (dumpPackage == null) {
7148 if (mController != null) {
7149 pw.println(" mController=" + mController
7150 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7151 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007152 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7153 pw.println(" mLaunchingActivityWakeLock="
7154 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007155 }
7156
7157 return needSep;
7158 }
7159 }
7160
7161 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007162 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7163 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007164 synchronized (mGlobalLock) {
7165 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007166 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007167 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7168 if (topFocusedStack != null) {
7169 proto.write(CONFIG_WILL_CHANGE, topFocusedStack.mConfigWillChange);
7170 }
sanryhuang498e77e2018-12-06 14:57:01 +08007171 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7172 if (mRunningVoice != null) {
7173 final long vrToken = proto.start(
7174 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7175 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7176 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007177 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007178 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7179 proto.end(vrToken);
7180 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007181 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007182 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007183 if (mController != null) {
7184 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007185 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7186 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007187 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7188 proto.end(token);
7189 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007190 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7191 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007192 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007193 }
7194
7195 if (mHomeProcess != null && (dumpPackage == null
7196 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007197 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007198 }
7199
7200 if (mPreviousProcess != null && (dumpPackage == null
7201 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007202 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007203 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7204 }
7205
7206 if (mHeavyWeightProcess != null && (dumpPackage == null
7207 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007208 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007209 }
7210
7211 for (Map.Entry<String, Integer> entry
7212 : mCompatModePackages.getPackages().entrySet()) {
7213 String pkg = entry.getKey();
7214 int mode = entry.getValue();
7215 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7216 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7217 proto.write(PACKAGE, pkg);
7218 proto.write(MODE, mode);
7219 proto.end(compatToken);
7220 }
7221 }
7222
7223 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007224 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007225 }
7226
7227 }
7228 }
7229
7230 @Override
7231 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7232 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7233 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007234 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7235 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007236 }
7237
7238 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007239 public void dumpForOom(PrintWriter pw) {
7240 synchronized (mGlobalLock) {
7241 pw.println(" mHomeProcess: " + mHomeProcess);
7242 pw.println(" mPreviousProcess: " + mPreviousProcess);
7243 if (mHeavyWeightProcess != null) {
7244 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7245 }
7246 }
7247 }
7248
7249 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007250 public boolean canGcNow() {
7251 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007252 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007253 }
7254 }
7255
Riddle Hsua0536432019-02-16 00:38:59 +08007256 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007257 @Override
7258 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007259 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007260 if (mRootWindowContainer == null) {
7261 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007262 // oomadj after AMS created.
7263 return null;
7264 }
Louis Chang149d5c82019-12-30 09:47:39 +08007265 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007266 return top != null ? top.app : null;
7267 }
7268 }
7269
Riddle Hsua0536432019-02-16 00:38:59 +08007270 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007271 @Override
7272 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007273 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007274 if (mRootWindowContainer != null) {
7275 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007276 }
7277 }
7278 }
7279
7280 @Override
7281 public void scheduleDestroyAllActivities(String reason) {
7282 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007283 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007284 }
7285 }
7286
7287 @Override
7288 public void removeUser(int userId) {
7289 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007290 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007291 }
7292 }
7293
7294 @Override
7295 public boolean switchUser(int userId, UserState userState) {
7296 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007297 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007298 }
7299 }
7300
7301 @Override
7302 public void onHandleAppCrash(WindowProcessController wpc) {
7303 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007304 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007305 }
7306 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007307
7308 @Override
7309 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7310 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007311 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007312 }
7313 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007314
Riddle Hsua0536432019-02-16 00:38:59 +08007315 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007316 @Override
7317 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007318 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007319 }
7320
Riddle Hsua0536432019-02-16 00:38:59 +08007321 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007322 @Override
7323 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007324 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007325 }
7326
Riddle Hsua0536432019-02-16 00:38:59 +08007327 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007328 @Override
7329 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007330 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007331 }
7332
Riddle Hsua0536432019-02-16 00:38:59 +08007333 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007334 @Override
7335 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007336 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007337 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007338
7339 @Override
7340 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007341 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007342 mPendingTempWhitelist.put(uid, tag);
7343 }
7344 }
7345
7346 @Override
7347 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007348 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007349 mPendingTempWhitelist.remove(uid);
7350 }
7351 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007352
7353 @Override
7354 public boolean handleAppCrashInActivityController(String processName, int pid,
7355 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7356 Runnable killCrashingAppCallback) {
7357 synchronized (mGlobalLock) {
7358 if (mController == null) {
7359 return false;
7360 }
7361
7362 try {
7363 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7364 stackTrace)) {
7365 killCrashingAppCallback.run();
7366 return true;
7367 }
7368 } catch (RemoteException e) {
7369 mController = null;
7370 Watchdog.getInstance().setActivityController(null);
7371 }
7372 return false;
7373 }
7374 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007375
7376 @Override
7377 public void removeRecentTasksByPackageName(String packageName, int userId) {
7378 synchronized (mGlobalLock) {
7379 mRecentTasks.removeTasksByPackageName(packageName, userId);
7380 }
7381 }
7382
7383 @Override
7384 public void cleanupRecentTasksForUser(int userId) {
7385 synchronized (mGlobalLock) {
7386 mRecentTasks.cleanupLocked(userId);
7387 }
7388 }
7389
7390 @Override
7391 public void loadRecentTasksForUser(int userId) {
7392 synchronized (mGlobalLock) {
7393 mRecentTasks.loadUserRecentsLocked(userId);
7394 }
7395 }
7396
7397 @Override
7398 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7399 synchronized (mGlobalLock) {
7400 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7401 }
7402 }
7403
7404 @Override
7405 public void flushRecentTasks() {
7406 mRecentTasks.flush();
7407 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007408
7409 @Override
7410 public WindowProcessController getHomeProcess() {
7411 synchronized (mGlobalLock) {
7412 return mHomeProcess;
7413 }
7414 }
7415
7416 @Override
7417 public WindowProcessController getPreviousProcess() {
7418 synchronized (mGlobalLock) {
7419 return mPreviousProcess;
7420 }
7421 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007422
7423 @Override
7424 public void clearLockedTasks(String reason) {
7425 synchronized (mGlobalLock) {
7426 getLockTaskController().clearLockedTasks(reason);
7427 }
7428 }
7429
7430 @Override
7431 public void updateUserConfiguration() {
7432 synchronized (mGlobalLock) {
7433 final Configuration configuration = new Configuration(getGlobalConfiguration());
7434 final int currentUserId = mAmInternal.getCurrentUserId();
7435 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7436 configuration, currentUserId, Settings.System.canWrite(mContext));
7437 updateConfigurationLocked(configuration, null /* starting */,
7438 false /* initLocale */, false /* persistent */, currentUserId,
7439 false /* deferResume */);
7440 }
7441 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007442
7443 @Override
7444 public boolean canShowErrorDialogs() {
7445 synchronized (mGlobalLock) {
7446 return mShowDialogs && !mSleeping && !mShuttingDown
7447 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7448 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7449 mAmInternal.getCurrentUserId())
7450 && !(UserManager.isDeviceInDemoMode(mContext)
7451 && mAmInternal.getCurrentUser().isDemo());
7452 }
7453 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007454
7455 @Override
7456 public void setProfileApp(String profileApp) {
7457 synchronized (mGlobalLock) {
7458 mProfileApp = profileApp;
7459 }
7460 }
7461
7462 @Override
7463 public void setProfileProc(WindowProcessController wpc) {
7464 synchronized (mGlobalLock) {
7465 mProfileProc = wpc;
7466 }
7467 }
7468
7469 @Override
7470 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7471 synchronized (mGlobalLock) {
7472 mProfilerInfo = profilerInfo;
7473 }
7474 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007475
7476 @Override
7477 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7478 synchronized (mGlobalLock) {
7479 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7480 }
7481 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007482
7483 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007484 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
Peter Kalauskas4dc04602020-02-12 18:49:03 -08007485 boolean isLowResolution) {
7486 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007487 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007488 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007489
7490 @Override
7491 public boolean isUidForeground(int uid) {
7492 synchronized (mGlobalLock) {
7493 return ActivityTaskManagerService.this.isUidForeground(uid);
7494 }
7495 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007496
7497 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007498 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007499 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007500 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007501 }
7502 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007503
7504 @Override
7505 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007506 // Translate package names into UIDs
7507 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007508 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007509 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7510 if (uid >= 0) {
7511 result.add(uid);
7512 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007513 }
7514 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007515 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007516 }
7517 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007518 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007519}