blob: 41d4ff785f049eababd0e747c587b4e124b03739 [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;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import 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;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import 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;
216import android.service.voice.IVoiceInteractionSession;
217import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900218import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700219import android.telecom.TelecomManager;
220import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100221import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700223import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700224import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700225import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700226import android.util.SparseArray;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700227import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700228import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700229import android.view.IRecentsAnimationRunner;
230import android.view.RemoteAnimationAdapter;
231import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700233
Evan Rosky4505b352018-09-06 11:20:40 -0700234import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700235import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.app.AssistUtils;
Philip P. Moltmanne7421e92020-02-10 16:14:12 +0000237import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700239import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700242import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
243import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700245import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700246import com.android.internal.policy.IKeyguardDismissCallback;
247import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700248import com.android.internal.util.ArrayUtils;
249import com.android.internal.util.FastPrintWriter;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800250import com.android.internal.util.FrameworkStatsLog;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800251import com.android.internal.util.function.pooled.PooledConsumer;
252import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700253import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700254import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700255import com.android.server.LocalServices;
256import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700257import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800258import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700259import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700260import com.android.server.am.ActivityManagerService;
Wale Ogunwale59507092018-10-29 09:00:30 -0700261import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
262import com.android.server.am.AppTimeTracker;
263import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700264import com.android.server.am.PendingIntentController;
265import com.android.server.am.PendingIntentRecord;
266import com.android.server.am.UserState;
Philip P. Moltmanne7421e92020-02-10 16:14:12 +0000267import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700268import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700269import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700270import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800271import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700272import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700276import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700278import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700280import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700281import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700282import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800283import java.lang.annotation.ElementType;
284import java.lang.annotation.Retention;
285import java.lang.annotation.RetentionPolicy;
286import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700287import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700288import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700290import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700291import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400292import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700293import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700295import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700296import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000297import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700298import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700299
300/**
301 * System service for managing activities and their containers (task, stacks, displays,... ).
302 *
303 * {@hide}
304 */
305public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700306 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800307 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000308 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700309 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
310 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
311 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
312 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700313 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700314
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700316 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700318 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100319 // How long we permit background activity starts after an activity in the process
320 // started or finished.
321 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700322
Wale Ogunwale98875612018-10-12 07:53:02 -0700323 /** Used to indicate that an app transition should be animated. */
324 static final boolean ANIMATE = true;
325
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700326 /** Hardware-reported OpenGLES version. */
327 final int GL_ES_VERSION;
328
Wale Ogunwale31913b52018-10-13 08:29:31 -0700329 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
330 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
331 public static final String DUMP_LASTANR_CMD = "lastanr" ;
332 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
333 public static final String DUMP_STARTER_CMD = "starter" ;
334 public static final String DUMP_CONTAINERS_CMD = "containers" ;
335 public static final String DUMP_RECENTS_CMD = "recents" ;
336 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
337
Wale Ogunwale64258362018-10-16 15:13:37 -0700338 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
339 public static final int RELAUNCH_REASON_NONE = 0;
340 /** This activity is being relaunched due to windowing mode change. */
341 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
342 /** This activity is being relaunched due to a free-resize operation. */
343 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
344
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700345 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700346
Wale Ogunwalef6733932018-06-27 05:14:34 -0700347 /**
348 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
349 * change at runtime. Use mContext for non-UI purposes.
350 */
351 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700352 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700353 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700354 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700355 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700356 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700357 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800358 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800359 @VisibleForTesting
360 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700361 PowerManagerInternal mPowerManagerInternal;
362 private UsageStatsManagerInternal mUsageStatsInternal;
363
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700364 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700365 IntentFirewall mIntentFirewall;
366
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700367 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800368 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800369 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700370 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800371 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
372 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
373 *
374 * @see WindowManagerThreadPriorityBooster
375 */
376 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700377 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800378 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700379 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700380 private UserManagerService mUserManager;
Philip P. Moltmanne7421e92020-02-10 16:14:12 +0000381 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700382 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800383 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700384 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700385 /** All processes currently running that might have a window organized by name. */
386 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100387 /** All processes we currently have running mapped by pid and uid */
388 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700389 /** This is the process holding what we currently consider to be the "home" activity. */
390 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700391 /** The currently running heavy-weight process, if any. */
392 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700393 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700394 /**
395 * This is the process holding the activity the user last visited that is in a different process
396 * from the one they are currently in.
397 */
398 WindowProcessController mPreviousProcess;
399 /** The time at which the previous process was last visible. */
400 long mPreviousProcessVisibleTime;
401
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700402 /** List of intents that were used to start the most recent tasks. */
403 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700404 /** State of external calls telling us if the device is awake or asleep. */
405 private boolean mKeyguardShown = false;
406
407 // Wrapper around VoiceInteractionServiceManager
408 private AssistUtils mAssistUtils;
409
410 // VoiceInteraction session ID that changes for each new request except when
411 // being called for multi-window assist in a single session.
412 private int mViSessionId = 1000;
413
414 // How long to wait in getAssistContextExtras for the activity and foreground services
415 // to respond with the result.
416 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
417
418 // How long top wait when going through the modern assist (which doesn't need to block
419 // on getting this result before starting to launch its UI).
420 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
421
422 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
423 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
424
Alison Cichowlas3e340502018-08-07 17:15:01 -0400425 // Permission tokens are used to temporarily granted a trusted app the ability to call
426 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
427 // showing any appropriate error messages to the user.
428 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
429 10 * MINUTE_IN_MILLIS;
430
431 // How long before the service actually expires a token. This is slightly longer than
432 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
433 // expiration exception.
434 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
435 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
436
437 // How long the service will remember expired tokens, for the purpose of providing error
438 // messaging when a client uses an expired token.
439 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
440 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
441
442 // Activity tokens of system activities that are delegating their call to
443 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
444 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
445
446 // Permission tokens that have expired, but we remember for error reporting.
447 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
448
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700449 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
450
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700451 // Keeps track of the active voice interaction service component, notified from
452 // VoiceInteractionManagerService
453 ComponentName mActiveVoiceInteractionServiceComponent;
454
Michal Karpinskida34cd42019-04-02 19:46:52 +0100455 // A map userId and all its companion app uids
456 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000457
Wale Ogunwalee2172292018-10-25 10:11:10 -0700458 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700459 KeyguardController mKeyguardController;
460 private final ClientLifecycleManager mLifecycleManager;
461 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700462 /** The controller for all operations related to locktask. */
463 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700464 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700465
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700466 boolean mSuppressResizeConfigChanges;
467
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700468 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700469 new UpdateConfigurationResult();
470
471 static final class UpdateConfigurationResult {
472 // Configuration changes that were updated.
473 int changes;
474 // If the activity was relaunched to match the new configuration.
475 boolean activityRelaunched;
476
477 void reset() {
478 changes = 0;
479 activityRelaunched = false;
480 }
481 }
482
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700483 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700484 private int mConfigurationSeq;
485 // To cache the list of supported system locales
486 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700487
488 /**
489 * Temp object used when global and/or display override configuration is updated. It is also
490 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
491 * anyone...
492 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700493 private Configuration mTempConfig = new Configuration();
494
Wale Ogunwalef6733932018-06-27 05:14:34 -0700495 /** Temporary to avoid allocations. */
496 final StringBuilder mStringBuilder = new StringBuilder(256);
497
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700498 // Amount of time after a call to stopAppSwitches() during which we will
499 // prevent further untrusted switches from happening.
500 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
501
502 /**
503 * The time at which we will allow normal application switches again,
504 * after a call to {@link #stopAppSwitches()}.
505 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700506 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700507 /**
508 * This is set to true after the first switch after mAppSwitchesAllowedTime
509 * is set; any switches after that will clear the time.
510 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700511 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700512
Ricky Wai906af482019-06-03 17:25:28 +0100513 /**
514 * Last stop app switches time, apps finished before this time cannot start background activity
515 * even if they are in grace period.
516 */
517 private long mLastStopAppSwitchesTime;
518
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700519 IActivityController mController = null;
520 boolean mControllerIsAMonkey = false;
521
Wale Ogunwale214f3482018-10-04 11:00:47 -0700522 final int mFactoryTest;
523
524 /** Used to control how we initialize the service. */
525 ComponentName mTopComponent;
526 String mTopAction = Intent.ACTION_MAIN;
527 String mTopData;
528
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800529 /** Profiling app information. */
530 String mProfileApp = null;
531 WindowProcessController mProfileProc = null;
532 ProfilerInfo mProfilerInfo = null;
533
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700534 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700535 * Dump of the activity state at the time of the last ANR. Cleared after
536 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
537 */
538 String mLastANRState;
539
540 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700541 * Used to retain an update lock when the foreground activity is in
542 * immersive mode.
543 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700544 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700545
546 /**
547 * Packages that are being allowed to perform unrestricted app switches. Mapping is
548 * User -> Type -> uid.
549 */
550 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
551
552 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700553 private int mThumbnailWidth;
554 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700555
556 /**
557 * Flag that indicates if multi-window is enabled.
558 *
559 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
560 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
561 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
562 * At least one of the forms of multi-window must be enabled in order for this flag to be
563 * initialized to 'true'.
564 *
565 * @see #mSupportsSplitScreenMultiWindow
566 * @see #mSupportsFreeformWindowManagement
567 * @see #mSupportsPictureInPicture
568 * @see #mSupportsMultiDisplay
569 */
570 boolean mSupportsMultiWindow;
571 boolean mSupportsSplitScreenMultiWindow;
572 boolean mSupportsFreeformWindowManagement;
573 boolean mSupportsPictureInPicture;
574 boolean mSupportsMultiDisplay;
575 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700576 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700577
578 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
579
580 // VR Vr2d Display Id.
581 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700582
Wale Ogunwalef6733932018-06-27 05:14:34 -0700583 /**
584 * Set while we are wanting to sleep, to prevent any
585 * activities from being started/resumed.
586 *
587 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
588 *
589 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
590 * while in the sleep state until there is a pending transition out of sleep, in which case
591 * mSleeping is set to false, and remains false while awake.
592 *
593 * Whether mSleeping can quickly toggled between true/false without the device actually
594 * display changing states is undefined.
595 */
596 private boolean mSleeping = false;
597
598 /**
599 * The process state used for processes that are running the top activities.
600 * This changes between TOP and TOP_SLEEPING to following mSleeping.
601 */
602 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
603
Riddle Hsua0022cd2019-09-09 21:12:41 +0800604 @Retention(RetentionPolicy.SOURCE)
605 @IntDef({
606 LAYOUT_REASON_CONFIG_CHANGED,
607 LAYOUT_REASON_VISIBILITY_CHANGED,
608 })
609 @interface LayoutReason {}
610 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
611 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
612
613 /** The reasons to perform surface placement. */
614 @LayoutReason
615 private int mLayoutReasons;
616
Wale Ogunwalef6733932018-06-27 05:14:34 -0700617 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
618 // automatically. Important for devices without direct input devices.
619 private boolean mShowDialogs = true;
620
621 /** Set if we are shutting down the system, similar to sleeping. */
622 boolean mShuttingDown = false;
623
624 /**
625 * We want to hold a wake lock while running a voice interaction session, since
626 * this may happen with the screen off and we need to keep the CPU running to
627 * be able to continue to interact with the user.
628 */
629 PowerManager.WakeLock mVoiceWakeLock;
630
631 /**
632 * Set while we are running a voice interaction. This overrides sleeping while it is active.
633 */
634 IVoiceInteractionSession mRunningVoice;
635
636 /**
637 * The last resumed activity. This is identical to the current resumed activity most
638 * of the time but could be different when we're pausing one activity before we resume
639 * another activity.
640 */
641 ActivityRecord mLastResumedActivity;
642
643 /**
644 * The activity that is currently being traced as the active resumed activity.
645 *
646 * @see #updateResumedAppTrace
647 */
648 private @Nullable ActivityRecord mTracedResumedActivity;
649
650 /** If non-null, we are tracking the time the user spends in the currently focused app. */
651 AppTimeTracker mCurAppTimeTracker;
652
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700653 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700654
Wale Ogunwale53783742018-09-16 10:21:51 -0700655 /**
656 * Packages that the user has asked to have run in screen size
657 * compatibility mode instead of filling the screen.
658 */
659 CompatModePackages mCompatModePackages;
660
Wale Ogunwalef6733932018-06-27 05:14:34 -0700661 private FontScaleSettingObserver mFontScaleSettingObserver;
662
Robert Carr8a2f9132019-11-11 15:03:15 -0800663 /**
664 * Stores the registration and state of TaskOrganizers in use.
665 */
Evan Rosky0037e5f2019-11-05 10:26:24 -0800666 TaskOrganizerController mTaskOrganizerController = new TaskOrganizerController(this);
Robert Carr8a2f9132019-11-11 15:03:15 -0800667
Ricky Wai96f5c352019-04-10 18:40:17 +0100668 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000669
Wale Ogunwalef6733932018-06-27 05:14:34 -0700670 private final class FontScaleSettingObserver extends ContentObserver {
671 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
672 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
673
674 public FontScaleSettingObserver() {
675 super(mH);
676 final ContentResolver resolver = mContext.getContentResolver();
677 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
678 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
679 UserHandle.USER_ALL);
680 }
681
682 @Override
683 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
684 if (mFontScaleUri.equals(uri)) {
685 updateFontScaleIfNeeded(userId);
686 } else if (mHideErrorDialogsUri.equals(uri)) {
687 synchronized (mGlobalLock) {
688 updateShouldShowDialogsLocked(getGlobalConfiguration());
689 }
690 }
691 }
692 }
693
Riddle Hsua0536432019-02-16 00:38:59 +0800694 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
695 @Target(ElementType.METHOD)
696 @Retention(RetentionPolicy.SOURCE)
697 @interface HotPath {
698 int NONE = 0;
699 int OOM_ADJUSTMENT = 1;
700 int LRU_UPDATE = 2;
701 int PROCESS_CHANGE = 3;
702 int caller() default NONE;
703 }
704
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800705 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
706 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900707 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800708 mAmInternal.updateOomAdj();
709 }
710 };
711
Charles Chen8d98dd22018-12-26 17:36:54 +0800712 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
713 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700714 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700715 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700716 mSystemThread = ActivityThread.currentActivityThread();
717 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700718 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800719 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700720 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700721 }
722
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700723 public void onSystemReady() {
724 synchronized (mGlobalLock) {
725 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
726 PackageManager.FEATURE_CANT_SAVE_STATE);
727 mAssistUtils = new AssistUtils(mContext);
728 mVrController.onSystemReady();
729 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700730 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700731 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700732 }
733
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700734 public void onInitPowerManagement() {
735 synchronized (mGlobalLock) {
736 mStackSupervisor.initPowerManagement();
737 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
738 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
739 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
740 mVoiceWakeLock.setReferenceCounted(false);
741 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700742 }
743
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700744 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700745 mFontScaleSettingObserver = new FontScaleSettingObserver();
746 }
747
Wale Ogunwale59507092018-10-29 09:00:30 -0700748 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700749 final boolean freeformWindowManagement =
750 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
751 || Settings.Global.getInt(
752 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
753
754 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
755 final boolean supportsPictureInPicture = supportsMultiWindow &&
756 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
757 final boolean supportsSplitScreenMultiWindow =
758 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
759 final boolean supportsMultiDisplay = mContext.getPackageManager()
760 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700761 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
762 final boolean forceResizable = Settings.Global.getInt(
763 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700764 final boolean sizeCompatFreeform = Settings.Global.getInt(
765 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700766
767 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900768 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700769
770 final Configuration configuration = new Configuration();
771 Settings.System.getConfiguration(resolver, configuration);
772 if (forceRtl) {
773 // This will take care of setting the correct layout direction flags
774 configuration.setLayoutDirection(configuration.locale);
775 }
776
777 synchronized (mGlobalLock) {
778 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700779 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700780 final boolean multiWindowFormEnabled = freeformWindowManagement
781 || supportsSplitScreenMultiWindow
782 || supportsPictureInPicture
783 || supportsMultiDisplay;
784 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
785 mSupportsMultiWindow = true;
786 mSupportsFreeformWindowManagement = freeformWindowManagement;
787 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
788 mSupportsPictureInPicture = supportsPictureInPicture;
789 mSupportsMultiDisplay = supportsMultiDisplay;
790 } else {
791 mSupportsMultiWindow = false;
792 mSupportsFreeformWindowManagement = false;
793 mSupportsSplitScreenMultiWindow = false;
794 mSupportsPictureInPicture = false;
795 mSupportsMultiDisplay = false;
796 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700797 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700798 // This happens before any activities are started, so we can change global configuration
799 // in-place.
800 updateConfigurationLocked(configuration, null, true);
801 final Configuration globalConfig = getGlobalConfiguration();
802 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
803
804 // Load resources only after the current configuration has been set.
805 final Resources res = mContext.getResources();
806 mThumbnailWidth = res.getDimensionPixelSize(
807 com.android.internal.R.dimen.thumbnail_width);
808 mThumbnailHeight = res.getDimensionPixelSize(
809 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700810 }
811 }
812
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800813 public WindowManagerGlobalLock getGlobalLock() {
814 return mGlobalLock;
815 }
816
Yunfan Chen585f2932019-01-29 16:04:45 +0900817 /** For test purpose only. */
818 @VisibleForTesting
819 public ActivityTaskManagerInternal getAtmInternal() {
820 return mInternal;
821 }
822
Riddle Hsud93a6c42018-11-29 21:50:06 +0800823 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
824 Looper looper) {
825 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700826 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700827 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700828 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800829 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700830 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700831 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700832 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700833
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700834 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700835 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700836 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700837 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700838 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700839 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700840 mKeyguardController = mStackSupervisor.getKeyguardController();
841 }
842
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700843 public void onActivityManagerInternalAdded() {
844 synchronized (mGlobalLock) {
845 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
846 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
847 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700848 }
849
Yunfan Chen75157d72018-07-27 14:47:21 +0900850 int increaseConfigurationSeqLocked() {
851 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
852 return mConfigurationSeq;
853 }
854
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700855 protected ActivityStackSupervisor createStackSupervisor() {
856 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
857 supervisor.initialize();
858 return supervisor;
859 }
860
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800861 protected AppWarnings createAppWarnings(
862 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
863 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
864 }
865
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700866 public void setWindowManager(WindowManagerService wm) {
867 synchronized (mGlobalLock) {
868 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800869 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800870 mTempConfig.setToDefaults();
871 mTempConfig.setLocales(LocaleList.getDefault());
872 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800873 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700874 mLockTaskController.setWindowManager(wm);
875 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800876 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700877 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700878 }
879
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700880 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
881 synchronized (mGlobalLock) {
882 mUsageStatsInternal = usageStatsManager;
883 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700884 }
885
Wale Ogunwalef6733932018-06-27 05:14:34 -0700886 UserManagerService getUserManager() {
887 if (mUserManager == null) {
888 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
889 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
890 }
891 return mUserManager;
892 }
893
Philip P. Moltmanne7421e92020-02-10 16:14:12 +0000894 AppOpsService getAppOpsService() {
895 if (mAppOpsService == null) {
896 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
897 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
Wale Ogunwalef6733932018-06-27 05:14:34 -0700898 }
Philip P. Moltmanne7421e92020-02-10 16:14:12 +0000899 return mAppOpsService;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700900 }
901
902 boolean hasUserRestriction(String restriction, int userId) {
903 return getUserManager().hasUserRestriction(restriction, userId);
904 }
905
Michal Karpinski15486842019-04-25 17:33:42 +0100906 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
Philip P. Moltmanne7421e92020-02-10 16:14:12 +0000907 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
908 callingUid, callingPackage, /* featureId */ null, false, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100909 if (mode == AppOpsManager.MODE_DEFAULT) {
910 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
911 == PERMISSION_GRANTED;
912 }
913 return mode == AppOpsManager.MODE_ALLOWED;
914 }
915
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700916 @VisibleForTesting
917 protected void setRecentTasks(RecentTasks recentTasks) {
918 mRecentTasks = recentTasks;
919 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700920 }
921
922 RecentTasks getRecentTasks() {
923 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700924 }
925
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700926 ClientLifecycleManager getLifecycleManager() {
927 return mLifecycleManager;
928 }
929
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700930 ActivityStartController getActivityStartController() {
931 return mActivityStartController;
932 }
933
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700934 TaskChangeNotificationController getTaskChangeNotificationController() {
935 return mTaskChangeNotificationController;
936 }
937
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700938 LockTaskController getLockTaskController() {
939 return mLockTaskController;
940 }
941
Yunfan Chen75157d72018-07-27 14:47:21 +0900942 /**
943 * Return the global configuration used by the process corresponding to the input pid. This is
944 * usually the global configuration with some overrides specific to that process.
945 */
946 Configuration getGlobalConfigurationForCallingPid() {
947 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800948 return getGlobalConfigurationForPid(pid);
949 }
950
951 /**
952 * Return the global configuration used by the process corresponding to the given pid.
953 */
954 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900955 if (pid == MY_PID || pid < 0) {
956 return getGlobalConfiguration();
957 }
958 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100959 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900960 return app != null ? app.getConfiguration() : getGlobalConfiguration();
961 }
962 }
963
964 /**
965 * Return the device configuration info used by the process corresponding to the input pid.
966 * The value is consistent with the global configuration for the process.
967 */
968 @Override
969 public ConfigurationInfo getDeviceConfigurationInfo() {
970 ConfigurationInfo config = new ConfigurationInfo();
971 synchronized (mGlobalLock) {
972 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
973 config.reqTouchScreen = globalConfig.touchscreen;
974 config.reqKeyboardType = globalConfig.keyboard;
975 config.reqNavigation = globalConfig.navigation;
976 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
977 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
978 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
979 }
980 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
981 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
982 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
983 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700984 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900985 }
986 return config;
987 }
988
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700989 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700990 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700991 }
992
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700993 public static final class Lifecycle extends SystemService {
994 private final ActivityTaskManagerService mService;
995
996 public Lifecycle(Context context) {
997 super(context);
998 mService = new ActivityTaskManagerService(context);
999 }
1000
1001 @Override
1002 public void onStart() {
1003 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001004 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001005 }
1006
Garfield Tan891146c2018-10-09 12:14:00 -07001007 @Override
1008 public void onUnlockUser(int userId) {
1009 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001010 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001011 }
1012 }
1013
1014 @Override
1015 public void onCleanupUser(int userId) {
1016 synchronized (mService.getGlobalLock()) {
1017 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1018 }
1019 }
1020
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001021 public ActivityTaskManagerService getService() {
1022 return mService;
1023 }
1024 }
1025
1026 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001027 public final int startActivity(IApplicationThread caller, String callingPackage,
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00001028 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1029 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1030 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1031 resultWho, requestCode, startFlags, profilerInfo, bOptions,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001032 UserHandle.getCallingUserId());
1033 }
1034
1035 @Override
1036 public final int startActivities(IApplicationThread caller, String callingPackage,
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00001037 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1038 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001039 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001041 enforceNotIsolatedCaller(reason);
1042 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001044 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00001045 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1046 reason, null /* originatingPendingIntent */,
1047 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001048 }
1049
1050 @Override
1051 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00001052 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1053 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1054 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1055 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001056 true /*validateIncomingUser*/);
1057 }
1058
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001059 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00001060 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1061 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1062 boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001063 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001064 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001065
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001066 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001067 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1068
1069 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001070 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001071 .setCaller(caller)
1072 .setCallingPackage(callingPackage)
1073 .setResolvedType(resolvedType)
1074 .setResultTo(resultTo)
1075 .setResultWho(resultWho)
1076 .setRequestCode(requestCode)
1077 .setStartFlags(startFlags)
1078 .setProfilerInfo(profilerInfo)
1079 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001080 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001081 .execute();
1082
1083 }
1084
1085 @Override
1086 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1087 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001088 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1089 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001090 // Refuse possible leaked file descriptors
1091 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1092 throw new IllegalArgumentException("File descriptors passed in Intent");
1093 }
1094
1095 if (!(target instanceof PendingIntentRecord)) {
1096 throw new IllegalArgumentException("Bad PendingIntent object");
1097 }
1098
1099 PendingIntentRecord pir = (PendingIntentRecord)target;
1100
1101 synchronized (mGlobalLock) {
1102 // If this is coming from the currently resumed activity, it is
1103 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001104 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001105 if (stack.mResumedActivity != null &&
1106 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001107 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001108 }
1109 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001110 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001111 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001112 }
1113
1114 @Override
1115 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1116 Bundle bOptions) {
1117 // Refuse possible leaked file descriptors
1118 if (intent != null && intent.hasFileDescriptors()) {
1119 throw new IllegalArgumentException("File descriptors passed in Intent");
1120 }
1121 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1122
1123 synchronized (mGlobalLock) {
1124 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1125 if (r == null) {
1126 SafeActivityOptions.abort(options);
1127 return false;
1128 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001129 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001130 // The caller is not running... d'oh!
1131 SafeActivityOptions.abort(options);
1132 return false;
1133 }
1134 intent = new Intent(intent);
1135 // The caller is not allowed to change the data.
1136 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1137 // And we are resetting to find the next component...
1138 intent.setComponent(null);
1139
1140 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1141
1142 ActivityInfo aInfo = null;
1143 try {
1144 List<ResolveInfo> resolves =
1145 AppGlobals.getPackageManager().queryIntentActivities(
1146 intent, r.resolvedType,
1147 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1148 UserHandle.getCallingUserId()).getList();
1149
1150 // Look for the original activity in the list...
1151 final int N = resolves != null ? resolves.size() : 0;
1152 for (int i=0; i<N; i++) {
1153 ResolveInfo rInfo = resolves.get(i);
1154 if (rInfo.activityInfo.packageName.equals(r.packageName)
1155 && rInfo.activityInfo.name.equals(r.info.name)) {
1156 // We found the current one... the next matching is
1157 // after it.
1158 i++;
1159 if (i<N) {
1160 aInfo = resolves.get(i).activityInfo;
1161 }
1162 if (debug) {
1163 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1164 + "/" + r.info.name);
1165 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1166 ? "null" : aInfo.packageName + "/" + aInfo.name));
1167 }
1168 break;
1169 }
1170 }
1171 } catch (RemoteException e) {
1172 }
1173
1174 if (aInfo == null) {
1175 // Nobody who is next!
1176 SafeActivityOptions.abort(options);
1177 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1178 return false;
1179 }
1180
1181 intent.setComponent(new ComponentName(
1182 aInfo.applicationInfo.packageName, aInfo.name));
1183 intent.setFlags(intent.getFlags()&~(
1184 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1185 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1186 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1187 FLAG_ACTIVITY_NEW_TASK));
1188
1189 // Okay now we need to start the new activity, replacing the currently running activity.
1190 // This is a little tricky because we want to start the new one as if the current one is
1191 // finished, but not finish the current one first so that there is no flicker.
1192 // And thus...
1193 final boolean wasFinishing = r.finishing;
1194 r.finishing = true;
1195
1196 // Propagate reply information over to the new activity.
1197 final ActivityRecord resultTo = r.resultTo;
1198 final String resultWho = r.resultWho;
1199 final int requestCode = r.requestCode;
1200 r.resultTo = null;
1201 if (resultTo != null) {
1202 resultTo.removeResultsLocked(r, resultWho, requestCode);
1203 }
1204
1205 final long origId = Binder.clearCallingIdentity();
1206 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001207 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001208 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001209 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001210 .setResolvedType(r.resolvedType)
1211 .setActivityInfo(aInfo)
1212 .setResultTo(resultTo != null ? resultTo.appToken : null)
1213 .setResultWho(resultWho)
1214 .setRequestCode(requestCode)
1215 .setCallingPid(-1)
1216 .setCallingUid(r.launchedFromUid)
1217 .setCallingPackage(r.launchedFromPackage)
1218 .setRealCallingPid(-1)
1219 .setRealCallingUid(r.launchedFromUid)
1220 .setActivityOptions(options)
1221 .execute();
1222 Binder.restoreCallingIdentity(origId);
1223
1224 r.finishing = wasFinishing;
1225 if (res != ActivityManager.START_SUCCESS) {
1226 return false;
1227 }
1228 return true;
1229 }
1230 }
1231
1232 @Override
1233 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00001234 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1235 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001236 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001238 enforceNotIsolatedCaller("startActivityAndWait");
1239 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1240 userId, "startActivityAndWait");
1241 // TODO: Switch to user app stacks here.
1242 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1243 .setCaller(caller)
1244 .setCallingPackage(callingPackage)
1245 .setResolvedType(resolvedType)
1246 .setResultTo(resultTo)
1247 .setResultWho(resultWho)
1248 .setRequestCode(requestCode)
1249 .setStartFlags(startFlags)
1250 .setActivityOptions(bOptions)
1251 .setUserId(userId)
1252 .setProfilerInfo(profilerInfo)
1253 .setWaitResult(res)
1254 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001255 return res;
1256 }
1257
1258 @Override
1259 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00001260 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1261 int startFlags, Configuration config, Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001262 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001263 enforceNotIsolatedCaller("startActivityWithConfig");
1264 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1265 "startActivityWithConfig");
1266 // TODO: Switch to user app stacks here.
1267 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1268 .setCaller(caller)
1269 .setCallingPackage(callingPackage)
1270 .setResolvedType(resolvedType)
1271 .setResultTo(resultTo)
1272 .setResultWho(resultWho)
1273 .setRequestCode(requestCode)
1274 .setStartFlags(startFlags)
1275 .setGlobalConfiguration(config)
1276 .setActivityOptions(bOptions)
1277 .setUserId(userId)
1278 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001279 }
1280
Robert Carr8a2f9132019-11-11 15:03:15 -08001281 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001282 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1283 int callingUid = Binder.getCallingUid();
1284 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1285 throw new SecurityException("Only the system process can request a permission token, "
1286 + "received request from uid: " + callingUid);
1287 }
1288 IBinder permissionToken = new Binder();
1289 synchronized (mGlobalLock) {
1290 mStartActivitySources.put(permissionToken, delegatorToken);
1291 }
1292
1293 Message expireMsg = PooledLambda.obtainMessage(
1294 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1295 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1296
1297 Message forgetMsg = PooledLambda.obtainMessage(
1298 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1299 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1300
1301 return permissionToken;
1302 }
1303
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001304 @Override
1305 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1306 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001307 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1308 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001309 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001310 // permission grants) as any app that may launch one of your own activities. So we only
1311 // allow this in two cases:
1312 // 1) The caller is an activity that is part of the core framework, and then only when it
1313 // is running as the system.
1314 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1315 // can only be requested by a system activity, which may then delegate this call to
1316 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001317 final ActivityRecord sourceRecord;
1318 final int targetUid;
1319 final String targetPackage;
1320 final boolean isResolver;
1321 synchronized (mGlobalLock) {
1322 if (resultTo == null) {
1323 throw new SecurityException("Must be called from an activity");
1324 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001325 final IBinder sourceToken;
1326 if (permissionToken != null) {
1327 // To even attempt to use a permissionToken, an app must also have this signature
1328 // permission.
1329 mAmInternal.enforceCallingPermission(
1330 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1331 "startActivityAsCaller");
1332 // If called with a permissionToken, we want the sourceRecord from the delegator
1333 // activity that requested this token.
1334 sourceToken = mStartActivitySources.remove(permissionToken);
1335 if (sourceToken == null) {
1336 // Invalid permissionToken, check if it recently expired.
1337 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1338 throw new SecurityException("Called with expired permission token: "
1339 + permissionToken);
1340 } else {
1341 throw new SecurityException("Called with invalid permission token: "
1342 + permissionToken);
1343 }
1344 }
1345 } else {
1346 // This method was called directly by the source.
1347 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001348 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001349
Louis Chang149d5c82019-12-30 09:47:39 +08001350 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001351 if (sourceRecord == null) {
1352 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001353 }
1354 if (sourceRecord.app == null) {
1355 throw new SecurityException("Called without a process attached to activity");
1356 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001357
1358 // Whether called directly or from a delegate, the source activity must be from the
1359 // android package.
1360 if (!sourceRecord.info.packageName.equals("android")) {
1361 throw new SecurityException("Must be called from an activity that is "
1362 + "declared in the android package");
1363 }
1364
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001365 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001366 // This is still okay, as long as this activity is running under the
1367 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001368 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001369 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001370 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001371 + " must be system uid or original calling uid "
1372 + sourceRecord.launchedFromUid);
1373 }
1374 }
1375 if (ignoreTargetSecurity) {
1376 if (intent.getComponent() == null) {
1377 throw new SecurityException(
1378 "Component must be specified with ignoreTargetSecurity");
1379 }
1380 if (intent.getSelector() != null) {
1381 throw new SecurityException(
1382 "Selector not allowed with ignoreTargetSecurity");
1383 }
1384 }
1385 targetUid = sourceRecord.launchedFromUid;
1386 targetPackage = sourceRecord.launchedFromPackage;
1387 isResolver = sourceRecord.isResolverOrChildActivity();
1388 }
1389
1390 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001391 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001392 }
1393
1394 // TODO: Switch to user app stacks here.
1395 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001396 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001397 .setCallingUid(targetUid)
1398 .setCallingPackage(targetPackage)
1399 .setResolvedType(resolvedType)
1400 .setResultTo(resultTo)
1401 .setResultWho(resultWho)
1402 .setRequestCode(requestCode)
1403 .setStartFlags(startFlags)
1404 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001405 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001406 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1407 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001408 // The target may well be in the background, which would normally prevent it
1409 // from starting an activity. Here we definitely want the start to succeed.
1410 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001411 .execute();
1412 } catch (SecurityException e) {
1413 // XXX need to figure out how to propagate to original app.
1414 // A SecurityException here is generally actually a fault of the original
1415 // calling activity (such as a fairly granting permissions), so propagate it
1416 // back to them.
1417 /*
1418 StringBuilder msg = new StringBuilder();
1419 msg.append("While launching");
1420 msg.append(intent.toString());
1421 msg.append(": ");
1422 msg.append(e.getMessage());
1423 */
1424 throw e;
1425 }
1426 }
1427
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001428 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1429 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001430 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001431 }
1432
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001433 @Override
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00001434 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1435 Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001436 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1437 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001438 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001439 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001440 if (session == null || interactor == null) {
1441 throw new NullPointerException("null session or interactor");
1442 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001443 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001444 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001445 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001446 .setCallingUid(callingUid)
1447 .setCallingPackage(callingPackage)
1448 .setResolvedType(resolvedType)
1449 .setVoiceSession(session)
1450 .setVoiceInteractor(interactor)
1451 .setStartFlags(startFlags)
1452 .setProfilerInfo(profilerInfo)
1453 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001454 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001455 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456 .execute();
1457 }
1458
1459 @Override
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00001460 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1461 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001462 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001463 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1464 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001466 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001467 .setCallingUid(callingUid)
1468 .setCallingPackage(callingPackage)
1469 .setResolvedType(resolvedType)
1470 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001471 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001472 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 .execute();
1474 }
1475
Riddle Hsu609a8e22019-06-27 16:46:29 -06001476 /**
1477 * Start the recents activity to perform the recents animation.
1478 *
1479 * @param intent The intent to start the recents activity.
1480 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1481 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001482 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001483 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1484 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001485 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001486 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001487 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001488 final long origId = Binder.clearCallingIdentity();
1489 try {
1490 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001491 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1492 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001493 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001494
1495 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001496 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001497 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00001498 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001499 if (recentsAnimationRunner == null) {
1500 anim.preloadRecentsActivity();
1501 } else {
1502 anim.startRecentsActivity(recentsAnimationRunner);
1503 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001504 }
1505 } finally {
1506 Binder.restoreCallingIdentity(origId);
1507 }
1508 }
1509
1510 @Override
1511 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001512 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001513 "startActivityFromRecents()");
1514
1515 final int callingPid = Binder.getCallingPid();
1516 final int callingUid = Binder.getCallingUid();
1517 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1518 final long origId = Binder.clearCallingIdentity();
1519 try {
1520 synchronized (mGlobalLock) {
1521 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1522 safeOptions);
1523 }
1524 } finally {
1525 Binder.restoreCallingIdentity(origId);
1526 }
1527 }
1528
1529 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001530 * Public API to check if the client is allowed to start an activity on specified display.
1531 *
1532 * If the target display is private or virtual, some restrictions will apply.
1533 *
1534 * @param displayId Target display id.
1535 * @param intent Intent used to launch the activity.
1536 * @param resolvedType The MIME type of the intent.
1537 * @param userId The id of the user for whom the call is made.
1538 * @return {@code true} if a call to start an activity on the target display should succeed and
1539 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1540 */
1541 @Override
1542 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1543 String resolvedType, int userId) {
1544 final int callingUid = Binder.getCallingUid();
1545 final int callingPid = Binder.getCallingPid();
1546 final long origId = Binder.clearCallingIdentity();
1547
1548 try {
1549 // Collect information about the target of the Intent.
1550 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1551 0 /* startFlags */, null /* profilerInfo */, userId,
1552 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1553 UserHandle.USER_NULL));
1554 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1555
1556 synchronized (mGlobalLock) {
1557 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1558 aInfo);
1559 }
1560 } finally {
1561 Binder.restoreCallingIdentity(origId);
1562 }
1563 }
1564
1565 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001566 * This is the internal entry point for handling Activity.finish().
1567 *
1568 * @param token The Binder token referencing the Activity we want to finish.
1569 * @param resultCode Result code, if any, from this Activity.
1570 * @param resultData Result data (Intent), if any, from this Activity.
1571 * @param finishTask Whether to finish the task associated with this Activity.
1572 *
1573 * @return Returns true if the activity successfully finished, or false if it is still running.
1574 */
1575 @Override
1576 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1577 int finishTask) {
1578 // Refuse possible leaked file descriptors
1579 if (resultData != null && resultData.hasFileDescriptors()) {
1580 throw new IllegalArgumentException("File descriptors passed in Intent");
1581 }
1582
1583 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001584 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001585 if (r == null) {
1586 return true;
1587 }
1588 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001589 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001590 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001591 if (rootR == null) {
1592 Slog.w(TAG, "Finishing task with all activities already finished");
1593 }
1594 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1595 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001596 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 return false;
1598 }
1599
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001600 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1601 // We should consolidate.
1602 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001603 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001604 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001605 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001606 if (next != null) {
1607 // ask watcher if this is allowed
1608 boolean resumeOK = true;
1609 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001610 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001611 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001612 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001613 Watchdog.getInstance().setActivityController(null);
1614 }
1615
1616 if (!resumeOK) {
1617 Slog.i(TAG, "Not finishing activity because controller resumed");
1618 return false;
1619 }
1620 }
1621 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001622
1623 // note down that the process has finished an activity and is in background activity
1624 // starts grace period
1625 if (r.app != null) {
1626 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1627 }
1628
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001629 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001630 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001631 try {
1632 boolean res;
1633 final boolean finishWithRootActivity =
1634 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1635 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1636 || (finishWithRootActivity && r == rootR)) {
1637 // If requested, remove the task that is associated to this activity only if it
1638 // was the root activity in the task. The result code and data is ignored
1639 // because we don't support returning them across task boundaries. Also, to
1640 // keep backwards compatibility we remove the task from recents when finishing
1641 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001642 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001643 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001644 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001645 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001646 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001647 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001648 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001649 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001650 if (!res) {
1651 Slog.i(TAG, "Failed to finish by app-request");
1652 }
1653 }
1654 return res;
1655 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001656 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001657 Binder.restoreCallingIdentity(origId);
1658 }
1659 }
1660 }
1661
1662 @Override
1663 public boolean finishActivityAffinity(IBinder token) {
1664 synchronized (mGlobalLock) {
1665 final long origId = Binder.clearCallingIdentity();
1666 try {
1667 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1668 if (r == null) {
1669 return false;
1670 }
1671
1672 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1673 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001674 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001675 return false;
1676 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001677
1678 final PooledFunction p = PooledLambda.obtainFunction(
1679 ActivityRecord::finishIfSameAffinity, r,
1680 PooledLambda.__(ActivityRecord.class));
1681 r.getTask().forAllActivities(
1682 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1683 p.recycle();
1684
Andrii Kuliande93eff2019-07-12 12:21:27 -07001685 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001686 } finally {
1687 Binder.restoreCallingIdentity(origId);
1688 }
1689 }
1690 }
1691
1692 @Override
1693 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1694 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001695 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001696 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001697 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001698 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1699 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001700 return;
1701 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001702 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1703 false /* processPausingActivities */, config);
1704 if (stopProfiling && r.hasProcess()) {
1705 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001706 }
1707 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001708 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001709 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001710 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001711 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001712 }
1713
1714 @Override
1715 public final void activityResumed(IBinder token) {
1716 final long origId = Binder.clearCallingIdentity();
1717 synchronized (mGlobalLock) {
1718 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001719 }
1720 Binder.restoreCallingIdentity(origId);
1721 }
1722
1723 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001724 public final void activityTopResumedStateLost() {
1725 final long origId = Binder.clearCallingIdentity();
1726 synchronized (mGlobalLock) {
1727 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1728 }
1729 Binder.restoreCallingIdentity(origId);
1730 }
1731
1732 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001733 public final void activityPaused(IBinder token) {
1734 final long origId = Binder.clearCallingIdentity();
1735 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001736 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001737 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1738 if (r != null) {
1739 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001740 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001741 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001742 }
1743 Binder.restoreCallingIdentity(origId);
1744 }
1745
1746 @Override
1747 public final void activityStopped(IBinder token, Bundle icicle,
1748 PersistableBundle persistentState, CharSequence description) {
1749 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1750
1751 // Refuse possible leaked file descriptors
1752 if (icicle != null && icicle.hasFileDescriptors()) {
1753 throw new IllegalArgumentException("File descriptors passed in Bundle");
1754 }
1755
1756 final long origId = Binder.clearCallingIdentity();
1757
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001758 String restartingName = null;
1759 int restartingUid = 0;
1760 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001761 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001762 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001763 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001764 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001765 if (r.attachedToProcess()
1766 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1767 // The activity was requested to restart from
1768 // {@link #restartActivityProcessIfVisible}.
1769 restartingName = r.app.mName;
1770 restartingUid = r.app.mUid;
1771 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001772 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001773 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001774 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001775 }
1776
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001777 if (restartingName != null) {
1778 // In order to let the foreground activity can be restarted with its saved state from
1779 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1780 // until the activity reports stopped with the state. And the activity record will be
1781 // kept because the record state is restarting, then the activity will be restarted
1782 // immediately if it is still the top one.
1783 mStackSupervisor.removeRestartTimeouts(r);
1784 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1785 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001786 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001787
1788 Binder.restoreCallingIdentity(origId);
1789 }
1790
1791 @Override
1792 public final void activityDestroyed(IBinder token) {
1793 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1794 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001795 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001796 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001797 try {
1798 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1799 if (activity != null) {
1800 activity.destroyed("activityDestroyed");
1801 }
1802 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001803 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001804 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001805 }
1806 }
1807 }
1808
1809 @Override
1810 public final void activityRelaunched(IBinder token) {
1811 final long origId = Binder.clearCallingIdentity();
1812 synchronized (mGlobalLock) {
1813 mStackSupervisor.activityRelaunchedLocked(token);
1814 }
1815 Binder.restoreCallingIdentity(origId);
1816 }
1817
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001818 @Override
1819 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1820 synchronized (mGlobalLock) {
1821 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1822 if (r == null) {
1823 return;
1824 }
1825 final long origId = Binder.clearCallingIdentity();
1826 try {
1827 r.setRequestedOrientation(requestedOrientation);
1828 } finally {
1829 Binder.restoreCallingIdentity(origId);
1830 }
1831 }
1832 }
1833
1834 @Override
1835 public int getRequestedOrientation(IBinder token) {
1836 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001837 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1838 return (r != null)
1839 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001840 }
1841 }
1842
1843 @Override
1844 public void setImmersive(IBinder token, boolean immersive) {
1845 synchronized (mGlobalLock) {
1846 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1847 if (r == null) {
1848 throw new IllegalArgumentException();
1849 }
1850 r.immersive = immersive;
1851
1852 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001853 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001854 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001855 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001856 }
1857 }
1858 }
1859
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001860 void applyUpdateLockStateLocked(ActivityRecord r) {
1861 // Modifications to the UpdateLock state are done on our handler, outside
1862 // the activity manager's locks. The new state is determined based on the
1863 // state *now* of the relevant activity record. The object is passed to
1864 // the handler solely for logging detail, not to be consulted/modified.
1865 final boolean nextState = r != null && r.immersive;
1866 mH.post(() -> {
1867 if (mUpdateLock.isHeld() != nextState) {
1868 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1869 "Applying new update lock state '" + nextState + "' for " + r);
1870 if (nextState) {
1871 mUpdateLock.acquire();
1872 } else {
1873 mUpdateLock.release();
1874 }
1875 }
1876 });
1877 }
1878
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001879 @Override
1880 public boolean isImmersive(IBinder token) {
1881 synchronized (mGlobalLock) {
1882 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1883 if (r == null) {
1884 throw new IllegalArgumentException();
1885 }
1886 return r.immersive;
1887 }
1888 }
1889
1890 @Override
1891 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001892 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001894 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001895 return (r != null) ? r.immersive : false;
1896 }
1897 }
1898
1899 @Override
1900 public void overridePendingTransition(IBinder token, String packageName,
1901 int enterAnim, int exitAnim) {
1902 synchronized (mGlobalLock) {
1903 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1904 if (self == null) {
1905 return;
1906 }
1907
1908 final long origId = Binder.clearCallingIdentity();
1909
1910 if (self.isState(
1911 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001912 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001913 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001914 }
1915
1916 Binder.restoreCallingIdentity(origId);
1917 }
1918 }
1919
1920 @Override
1921 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001922 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001923 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001924 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001925 if (r == null) {
1926 return ActivityManager.COMPAT_MODE_UNKNOWN;
1927 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001928 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001929 }
1930 }
1931
1932 @Override
1933 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001934 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001936 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001937 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001938 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001939 if (r == null) {
1940 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1941 return;
1942 }
1943 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001944 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 }
1946 }
1947
1948 @Override
1949 public int getLaunchedFromUid(IBinder activityToken) {
1950 ActivityRecord srec;
1951 synchronized (mGlobalLock) {
1952 srec = ActivityRecord.forTokenLocked(activityToken);
1953 }
1954 if (srec == null) {
1955 return -1;
1956 }
1957 return srec.launchedFromUid;
1958 }
1959
1960 @Override
1961 public String getLaunchedFromPackage(IBinder activityToken) {
1962 ActivityRecord srec;
1963 synchronized (mGlobalLock) {
1964 srec = ActivityRecord.forTokenLocked(activityToken);
1965 }
1966 if (srec == null) {
1967 return null;
1968 }
1969 return srec.launchedFromPackage;
1970 }
1971
1972 @Override
1973 public boolean convertFromTranslucent(IBinder token) {
1974 final long origId = Binder.clearCallingIdentity();
1975 try {
1976 synchronized (mGlobalLock) {
1977 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1978 if (r == null) {
1979 return false;
1980 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001981 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001982 }
1983 } finally {
1984 Binder.restoreCallingIdentity(origId);
1985 }
1986 }
1987
1988 @Override
1989 public boolean convertToTranslucent(IBinder token, Bundle options) {
1990 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1991 final long origId = Binder.clearCallingIdentity();
1992 try {
1993 synchronized (mGlobalLock) {
1994 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1995 if (r == null) {
1996 return false;
1997 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001998 final ActivityRecord under = r.getTask().getActivityBelow(r);
1999 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002000 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2001 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002002 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002003 }
2004 } finally {
2005 Binder.restoreCallingIdentity(origId);
2006 }
2007 }
2008
2009 @Override
2010 public void notifyActivityDrawn(IBinder token) {
2011 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2012 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002013 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002014 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002015 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002016 }
2017 }
2018 }
2019
2020 @Override
2021 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2022 synchronized (mGlobalLock) {
2023 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2024 if (r == null) {
2025 return;
2026 }
2027 r.reportFullyDrawnLocked(restoredFromBundle);
2028 }
2029 }
2030
2031 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002032 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002033 synchronized (mGlobalLock) {
2034 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002035 if (stack != null) {
2036 final int displayId = stack.getDisplayId();
2037 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002038 }
2039 return DEFAULT_DISPLAY;
2040 }
2041 }
2042
2043 @Override
2044 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002045 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002046 long ident = Binder.clearCallingIdentity();
2047 try {
2048 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002049 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002050 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002051 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002052 }
2053 return null;
2054 }
2055 } finally {
2056 Binder.restoreCallingIdentity(ident);
2057 }
2058 }
2059
2060 @Override
2061 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002062 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002063 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2064 final long callingId = Binder.clearCallingIdentity();
2065 try {
2066 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002067 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002068 if (stack == null) {
2069 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2070 return;
2071 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002072 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002073 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002074 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002075 }
2076 }
2077 } finally {
2078 Binder.restoreCallingIdentity(callingId);
2079 }
2080 }
2081
2082 @Override
2083 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002084 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2086 final long callingId = Binder.clearCallingIdentity();
2087 try {
2088 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002089 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002090 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002091 if (task == null) {
2092 return;
2093 }
2094 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002095 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002096 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002097 }
2098 }
2099 } finally {
2100 Binder.restoreCallingIdentity(callingId);
2101 }
2102 }
2103
2104 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002105 public void restartActivityProcessIfVisible(IBinder activityToken) {
2106 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2107 final long callingId = Binder.clearCallingIdentity();
2108 try {
2109 synchronized (mGlobalLock) {
2110 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2111 if (r == null) {
2112 return;
2113 }
2114 r.restartProcessIfVisible();
2115 }
2116 } finally {
2117 Binder.restoreCallingIdentity(callingId);
2118 }
2119 }
2120
2121 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002122 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002123 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002124 synchronized (mGlobalLock) {
2125 final long ident = Binder.clearCallingIdentity();
2126 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002127 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002128 "remove-task");
2129 } finally {
2130 Binder.restoreCallingIdentity(ident);
2131 }
2132 }
2133 }
2134
2135 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002136 public void removeAllVisibleRecentTasks() {
2137 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2138 synchronized (mGlobalLock) {
2139 final long ident = Binder.clearCallingIdentity();
2140 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002141 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002142 } finally {
2143 Binder.restoreCallingIdentity(ident);
2144 }
2145 }
2146 }
2147
2148 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002149 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2150 synchronized (mGlobalLock) {
2151 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2152 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002153 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002154 }
2155 }
2156 return false;
2157 }
2158
2159 @Override
2160 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2161 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002162
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002163 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002164 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2165 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002166 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002167 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002168 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002169 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002170 }
2171 }
2172
2173 /**
2174 * Attempts to move a task backwards in z-order (the order of activities within the task is
2175 * unchanged).
2176 *
2177 * There are several possible results of this call:
2178 * - if the task is locked, then we will show the lock toast
2179 * - if there is a task behind the provided task, then that task is made visible and resumed as
2180 * this task is moved to the back
2181 * - otherwise, if there are no other tasks in the stack:
2182 * - if this task is in the pinned stack, then we remove the stack completely, which will
2183 * have the effect of moving the task to the top or bottom of the fullscreen stack
2184 * (depending on whether it is visible)
2185 * - otherwise, we simply return home and hide this task
2186 *
2187 * @param token A reference to the activity we wish to move
2188 * @param nonRoot If false then this only works if the activity is the root
2189 * of a task; if true it will work for any activity in a task.
2190 * @return Returns true if the move completed, false if not.
2191 */
2192 @Override
2193 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002194 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002195 synchronized (mGlobalLock) {
2196 final long origId = Binder.clearCallingIdentity();
2197 try {
2198 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002199 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002200 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002201 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002202 }
2203 } finally {
2204 Binder.restoreCallingIdentity(origId);
2205 }
2206 }
2207 return false;
2208 }
2209
2210 @Override
2211 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002212 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002213 long ident = Binder.clearCallingIdentity();
2214 Rect rect = new Rect();
2215 try {
2216 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002217 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002218 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2219 if (task == null) {
2220 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2221 return rect;
2222 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002223 if (task.getParent() != null) {
2224 rect.set(task.getBounds());
2225 } else if (task.mLastNonFullscreenBounds != null) {
2226 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 }
2228 }
2229 } finally {
2230 Binder.restoreCallingIdentity(ident);
2231 }
2232 return rect;
2233 }
2234
2235 @Override
2236 public ActivityManager.TaskDescription getTaskDescription(int id) {
2237 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002238 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002239 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002240 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002241 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2242 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002243 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002244 }
2245 }
2246 return null;
2247 }
2248
2249 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002250 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002251 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Winson Chung7ccc6812020-01-23 16:15:10 -08002252 return setTaskWindowingModeSplitScreenPrimary(taskId,
2253 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002254 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002255 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002256 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002257 synchronized (mGlobalLock) {
2258 final long ident = Binder.clearCallingIdentity();
2259 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002260 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002261 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002262 if (task == null) {
2263 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002264 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002265 }
2266
2267 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2268 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2269
2270 if (!task.isActivityTypeStandardOrUndefined()) {
2271 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2272 + " non-standard task " + taskId + " to windowing mode="
2273 + windowingMode);
2274 }
2275
2276 final ActivityStack stack = task.getStack();
2277 if (toTop) {
2278 stack.moveToFront("setTaskWindowingMode", task);
2279 }
2280 stack.setWindowingMode(windowingMode);
Winson Chung7ccc6812020-01-23 16:15:10 -08002281 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002282 } finally {
2283 Binder.restoreCallingIdentity(ident);
2284 }
2285 }
2286 }
2287
2288 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002289 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002290 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002291 ActivityRecord r = getCallingRecordLocked(token);
2292 return r != null ? r.info.packageName : null;
2293 }
2294 }
2295
2296 @Override
2297 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002298 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002299 ActivityRecord r = getCallingRecordLocked(token);
2300 return r != null ? r.intent.getComponent() : null;
2301 }
2302 }
2303
2304 private ActivityRecord getCallingRecordLocked(IBinder token) {
2305 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2306 if (r == null) {
2307 return null;
2308 }
2309 return r.resultTo;
2310 }
2311
2312 @Override
2313 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002314 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002315
2316 synchronized (mGlobalLock) {
2317 final long origId = Binder.clearCallingIdentity();
2318 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002319 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002320 } finally {
2321 Binder.restoreCallingIdentity(origId);
2322 }
2323 }
2324 }
2325
Mark Renouf446251d2019-04-26 10:22:41 -04002326 @Override
2327 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2328 synchronized (mGlobalLock) {
2329 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2330 if (r == null) {
2331 return;
2332 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002333 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002334 if (stack != null && stack.isSingleTaskInstance()) {
2335 // Single-task stacks are used for activities which are presented in floating
2336 // windows above full screen activities. Instead of directly finishing the
2337 // task, a task change listener is used to notify SystemUI so the action can be
2338 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002339 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002340 mTaskChangeNotificationController
2341 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2342 } else {
2343 try {
2344 callback.requestFinish();
2345 } catch (RemoteException e) {
2346 Slog.e(TAG, "Failed to invoke request finish callback", e);
2347 }
2348 }
2349 }
2350 }
2351
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002352 /**
2353 * TODO: Add mController hook
2354 */
2355 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002356 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2357 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002358 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002359
2360 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2361 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002362 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2363 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002364 }
2365 }
2366
Ricky Waiaca8a772019-04-04 16:01:06 +01002367 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2368 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002369 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002370 final int callingPid = Binder.getCallingPid();
2371 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002372 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002373 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002374 SafeActivityOptions.abort(options);
2375 return;
2376 }
2377 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002378 WindowProcessController callerApp = null;
2379 if (appThread != null) {
2380 callerApp = getProcessController(appThread);
2381 }
2382 final ActivityStarter starter = getActivityStartController().obtainStarter(
2383 null /* intent */, "moveTaskToFront");
2384 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2385 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002386 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002387 return;
2388 }
2389 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002390 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002391 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002392 if (task == null) {
2393 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002394 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002395 return;
2396 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002397 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002398 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002399 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002400 return;
2401 }
2402 ActivityOptions realOptions = options != null
2403 ? options.getOptions(mStackSupervisor)
2404 : null;
2405 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2406 false /* forceNonResizable */);
2407
Wale Ogunwale21e06482019-11-18 05:14:15 -08002408 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002409 if (topActivity != null) {
2410
2411 // We are reshowing a task, use a starting window to hide the initial draw delay
2412 // so the transition can start earlier.
2413 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2414 true /* taskSwitch */, fromRecents);
2415 }
2416 } finally {
2417 Binder.restoreCallingIdentity(origId);
2418 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002419 }
2420
Ricky Waiaca8a772019-04-04 16:01:06 +01002421 /**
2422 * Return true if callingUid is system, or packageName belongs to that callingUid.
2423 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002424 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002425 try {
2426 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2427 if (packageName == null) {
2428 return false;
2429 }
2430 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2431 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2432 UserHandle.getUserId(callingUid));
2433 return UserHandle.isSameApp(callingUid, uid);
2434 }
2435 } catch (RemoteException e) {
2436 // Should not happen
2437 }
2438 return true;
2439 }
2440
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002441 /**
2442 * Checks that the provided package name matches the current calling UID, throws a security
2443 * exception if it doesn't.
2444 */
2445 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2446 final int callingUid = Binder.getCallingUid();
2447 if (isSameApp(callingUid, packageName)) {
2448 return;
2449 }
2450 final String msg = "Permission Denial: package=" + packageName
2451 + " does not belong to uid=" + callingUid;
2452 Slog.w(TAG, msg);
2453 throw new SecurityException(msg);
2454 }
2455
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002456 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2457 int callingPid, int callingUid, String name) {
2458 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2459 return true;
2460 }
2461
2462 if (getRecentTasks().isCallerRecents(sourceUid)) {
2463 return true;
2464 }
2465
2466 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2467 if (perm == PackageManager.PERMISSION_GRANTED) {
2468 return true;
2469 }
2470 if (checkAllowAppSwitchUid(sourceUid)) {
2471 return true;
2472 }
2473
2474 // If the actual IPC caller is different from the logical source, then
2475 // also see if they are allowed to control app switches.
2476 if (callingUid != -1 && callingUid != sourceUid) {
2477 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2478 if (perm == PackageManager.PERMISSION_GRANTED) {
2479 return true;
2480 }
2481 if (checkAllowAppSwitchUid(callingUid)) {
2482 return true;
2483 }
2484 }
2485
2486 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2487 return false;
2488 }
2489
2490 private boolean checkAllowAppSwitchUid(int uid) {
2491 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2492 if (types != null) {
2493 for (int i = types.size() - 1; i >= 0; i--) {
2494 if (types.valueAt(i).intValue() == uid) {
2495 return true;
2496 }
2497 }
2498 }
2499 return false;
2500 }
2501
2502 @Override
2503 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2504 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2505 "setActivityController()");
2506 synchronized (mGlobalLock) {
2507 mController = controller;
2508 mControllerIsAMonkey = imAMonkey;
2509 Watchdog.getInstance().setActivityController(controller);
2510 }
2511 }
2512
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002513 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002514 synchronized (mGlobalLock) {
2515 return mController != null && mControllerIsAMonkey;
2516 }
2517 }
2518
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002519 @Override
2520 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2521 synchronized (mGlobalLock) {
2522 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2523 }
2524 }
2525
2526 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002527 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2528 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2529 }
2530
2531 @Override
2532 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2533 @WindowConfiguration.ActivityType int ignoreActivityType,
2534 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2535 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002536 final int callingPid = Binder.getCallingPid();
2537 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002538 final int[] profileIds = getUserManager().getProfileIds(
2539 UserHandle.getUserId(callingUid), true);
2540 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2541 for (int i = 0; i < profileIds.length; i++) {
2542 callingProfileIds.add(profileIds[i]);
2543 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002544 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2545
2546 synchronized (mGlobalLock) {
2547 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2548
Nicholas Sauer0259e532019-08-30 08:24:55 -07002549 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002550 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002551 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002552 }
2553
2554 return list;
2555 }
2556
2557 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002558 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2559 synchronized (mGlobalLock) {
2560 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002561 try {
2562 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2563 if (r == null) return;
2564
2565 final PooledConsumer c = PooledLambda.obtainConsumer(
2566 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2567 r, resultWho, requestCode);
2568 // TODO: This should probably only loop over the task since you need to be in the
2569 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002570 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002571 c.recycle();
2572
2573 updateOomAdj();
2574 } finally {
2575 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002576 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002577 }
2578 }
2579
2580 @Override
2581 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002582 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002583 ActivityStack stack = ActivityRecord.getStackLocked(token);
2584 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002585 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002586 }
2587 return false;
2588 }
2589 }
2590
2591 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002592 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002593 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002594 synchronized (mGlobalLock) {
2595 final long ident = Binder.clearCallingIdentity();
2596 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002597 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002598 if (task == null) {
2599 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2600 return;
2601 }
2602
2603 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2604 + " to stackId=" + stackId + " toTop=" + toTop);
2605
Louis Chang149d5c82019-12-30 09:47:39 +08002606 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002607 if (stack == null) {
2608 throw new IllegalStateException(
2609 "moveTaskToStack: No stack for stackId=" + stackId);
2610 }
2611 if (!stack.isActivityTypeStandardOrUndefined()) {
2612 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2613 + taskId + " to stack " + stackId);
2614 }
2615 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002616 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002617 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2618 }
2619 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2620 "moveTaskToStack");
2621 } finally {
2622 Binder.restoreCallingIdentity(ident);
2623 }
2624 }
2625 }
2626
2627 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002628 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2629 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002630
2631 final long ident = Binder.clearCallingIdentity();
2632 try {
2633 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002634 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Evan Roskydbe2ce52019-07-18 11:13:17 -07002635 if (stack == null) {
2636 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2637 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002638 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002639 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2640 throw new IllegalArgumentException("Stack: " + stackId
2641 + " doesn't support animated resize.");
2642 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002643 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002644 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002645 }
2646 } finally {
2647 Binder.restoreCallingIdentity(ident);
2648 }
2649 }
2650
wilsonshih5c4cf522019-01-25 09:03:47 +08002651 @Override
2652 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2653 int animationDuration) {
2654 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2655
2656 final long ident = Binder.clearCallingIdentity();
2657 try {
2658 synchronized (mGlobalLock) {
2659 if (xOffset == 0 && yOffset == 0) {
2660 return;
2661 }
Louis Chang149d5c82019-12-30 09:47:39 +08002662 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
wilsonshih5c4cf522019-01-25 09:03:47 +08002663 if (stack == null) {
2664 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2665 return;
2666 }
2667 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2668 throw new IllegalArgumentException("Stack: " + stackId
2669 + " doesn't support animated resize.");
2670 }
2671 final Rect destBounds = new Rect();
2672 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002673 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002674 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2675 return;
2676 }
2677 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002678 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002679 animationDuration, false /* fromFullscreen */);
2680 }
2681 } finally {
2682 Binder.restoreCallingIdentity(ident);
2683 }
2684 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002685 /**
2686 * Moves the specified task to the primary-split-screen stack.
2687 *
2688 * @param taskId Id of task to move.
2689 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2690 * exist already. See
2691 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2692 * and
2693 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2694 * @param toTop If the task and stack should be moved to the top.
2695 * @param animate Whether we should play an animation for the moving the task.
2696 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2697 * stack. Pass {@code null} to use default bounds.
2698 * @param showRecents If the recents activity should be shown on the other side of the task
2699 * going into split-screen mode.
Winson Chung7ccc6812020-01-23 16:15:10 -08002700 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002701 */
2702 @Override
2703 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2704 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002705 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002706 "setTaskWindowingModeSplitScreenPrimary()");
2707 synchronized (mGlobalLock) {
2708 final long ident = Binder.clearCallingIdentity();
2709 try {
Winson Chung7ccc6812020-01-23 16:15:10 -08002710 if (isInLockTaskMode()) {
2711 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: Is in lock task mode="
2712 + getLockTaskModeState());
2713 return false;
2714 }
2715
Louis Chang149d5c82019-12-30 09:47:39 +08002716 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002717 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002718 if (task == null) {
2719 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2720 return false;
2721 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002722 if (!task.isActivityTypeStandardOrUndefined()) {
2723 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2724 + " non-standard task " + taskId + " to split-screen windowing mode");
2725 }
2726
Winson Chung7ccc6812020-01-23 16:15:10 -08002727 if (DEBUG_STACK) Slog.d(TAG_STACK,
2728 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2729 + " to createMode=" + createMode + " toTop=" + toTop);
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002730 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002731 final int windowingMode = task.getWindowingMode();
2732 final ActivityStack stack = task.getStack();
2733 if (toTop) {
2734 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2735 }
2736 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002737 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2738 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002739 return windowingMode != task.getWindowingMode();
2740 } finally {
2741 Binder.restoreCallingIdentity(ident);
2742 }
2743 }
2744 }
2745
2746 /**
2747 * Removes stacks in the input windowing modes from the system if they are of activity type
2748 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2749 */
2750 @Override
2751 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002752 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002753 "removeStacksInWindowingModes()");
2754
2755 synchronized (mGlobalLock) {
2756 final long ident = Binder.clearCallingIdentity();
2757 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002758 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002759 } finally {
2760 Binder.restoreCallingIdentity(ident);
2761 }
2762 }
2763 }
2764
2765 @Override
2766 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002767 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002768 "removeStacksWithActivityTypes()");
2769
2770 synchronized (mGlobalLock) {
2771 final long ident = Binder.clearCallingIdentity();
2772 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002773 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002774 } finally {
2775 Binder.restoreCallingIdentity(ident);
2776 }
2777 }
2778 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779
2780 @Override
2781 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2782 int userId) {
2783 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002784 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2785 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002786 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002787 final boolean detailed = checkGetTasksPermission(
2788 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2789 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002790 == PackageManager.PERMISSION_GRANTED;
2791
2792 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002793 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002794 callingUid);
2795 }
2796 }
2797
2798 @Override
2799 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002800 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002801 long ident = Binder.clearCallingIdentity();
2802 try {
2803 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002804 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002805 }
2806 } finally {
2807 Binder.restoreCallingIdentity(ident);
2808 }
2809 }
2810
2811 @Override
2812 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002813 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002814 long ident = Binder.clearCallingIdentity();
2815 try {
2816 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002817 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002818 }
2819 } finally {
2820 Binder.restoreCallingIdentity(ident);
2821 }
2822 }
2823
2824 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002825 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2826 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2827 long ident = Binder.clearCallingIdentity();
2828 try {
2829 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002830 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002831 }
2832 } finally {
2833 Binder.restoreCallingIdentity(ident);
2834 }
2835 }
2836
2837 @Override
2838 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2839 int displayId) {
2840 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2841 long ident = Binder.clearCallingIdentity();
2842 try {
2843 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002844 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002845 }
2846 } finally {
2847 Binder.restoreCallingIdentity(ident);
2848 }
2849 }
2850
2851 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002852 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002853 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002854 final long callingUid = Binder.getCallingUid();
2855 final long origId = Binder.clearCallingIdentity();
2856 try {
2857 synchronized (mGlobalLock) {
2858 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002859 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002860 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2861 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2862 }
2863 } finally {
2864 Binder.restoreCallingIdentity(origId);
2865 }
2866 }
2867
2868 @Override
2869 public void startLockTaskModeByToken(IBinder token) {
2870 synchronized (mGlobalLock) {
2871 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2872 if (r == null) {
2873 return;
2874 }
Louis Changcdec0802019-11-11 11:45:07 +08002875 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002876 }
2877 }
2878
2879 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002880 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002881 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002882 // This makes inner call to look as if it was initiated by system.
2883 long ident = Binder.clearCallingIdentity();
2884 try {
2885 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002886 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002887 MATCH_TASK_IN_STACKS_ONLY);
2888 if (task == null) {
2889 return;
2890 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002891
2892 // When starting lock task mode the stack must be in front and focused
2893 task.getStack().moveToFront("startSystemLockTaskMode");
2894 startLockTaskModeLocked(task, true /* isSystemCaller */);
2895 }
2896 } finally {
2897 Binder.restoreCallingIdentity(ident);
2898 }
2899 }
2900
2901 @Override
2902 public void stopLockTaskModeByToken(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 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002909 }
2910 }
2911
2912 /**
2913 * This API should be called by SystemUI only when user perform certain action to dismiss
2914 * lock task mode. We should only dismiss pinned lock task mode in this case.
2915 */
2916 @Override
2917 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002918 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002919 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2920 }
2921
Louis Changcdec0802019-11-11 11:45:07 +08002922 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002923 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2924 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2925 return;
2926 }
2927
Louis Chang149d5c82019-12-30 09:47:39 +08002928 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002929 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002930 throw new IllegalArgumentException("Invalid task, not in foreground");
2931 }
2932
2933 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2934 // system or a specific app.
2935 // * System-initiated requests will only start the pinned mode (screen pinning)
2936 // * App-initiated requests
2937 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2938 // - will start the pinned mode, otherwise
2939 final int callingUid = Binder.getCallingUid();
2940 long ident = Binder.clearCallingIdentity();
2941 try {
2942 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002943 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002944
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002945 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002946 } finally {
2947 Binder.restoreCallingIdentity(ident);
2948 }
2949 }
2950
Louis Changcdec0802019-11-11 11:45:07 +08002951 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952 final int callingUid = Binder.getCallingUid();
2953 long ident = Binder.clearCallingIdentity();
2954 try {
2955 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002956 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002957 }
2958 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2959 // task and jumping straight into a call in the case of emergency call back.
2960 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2961 if (tm != null) {
2962 tm.showInCallScreen(false);
2963 }
2964 } finally {
2965 Binder.restoreCallingIdentity(ident);
2966 }
2967 }
2968
2969 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002970 public void updateLockTaskPackages(int userId, String[] packages) {
2971 final int callingUid = Binder.getCallingUid();
2972 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2973 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2974 "updateLockTaskPackages()");
2975 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002976 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002977 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2978 + Arrays.toString(packages));
2979 getLockTaskController().updateLockTaskPackages(userId, packages);
2980 }
2981 }
2982
2983 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002984 public boolean isInLockTaskMode() {
2985 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2986 }
2987
2988 @Override
2989 public int getLockTaskModeState() {
2990 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002991 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002992 }
2993 }
2994
2995 @Override
2996 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2997 synchronized (mGlobalLock) {
2998 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2999 if (r != null) {
3000 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003001 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003002 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003003 }
3004 }
3005 }
3006
3007 @Override
3008 public Bundle getActivityOptions(IBinder token) {
3009 final long origId = Binder.clearCallingIdentity();
3010 try {
3011 synchronized (mGlobalLock) {
3012 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3013 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003014 final ActivityOptions activityOptions = r.takeOptionsLocked(
3015 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003016 return activityOptions == null ? null : activityOptions.toBundle();
3017 }
3018 return null;
3019 }
3020 } finally {
3021 Binder.restoreCallingIdentity(origId);
3022 }
3023 }
3024
3025 @Override
3026 public List<IBinder> getAppTasks(String callingPackage) {
3027 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003028 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003029 long ident = Binder.clearCallingIdentity();
3030 try {
3031 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003032 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003033 }
3034 } finally {
3035 Binder.restoreCallingIdentity(ident);
3036 }
3037 }
3038
3039 @Override
3040 public void finishVoiceTask(IVoiceInteractionSession session) {
3041 synchronized (mGlobalLock) {
3042 final long origId = Binder.clearCallingIdentity();
3043 try {
3044 // TODO: VI Consider treating local voice interactions and voice tasks
3045 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003046 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003047 } finally {
3048 Binder.restoreCallingIdentity(origId);
3049 }
3050 }
3051
3052 }
3053
3054 @Override
3055 public boolean isTopOfTask(IBinder token) {
3056 synchronized (mGlobalLock) {
3057 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003058 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003059 }
3060 }
3061
3062 @Override
3063 public void notifyLaunchTaskBehindComplete(IBinder token) {
3064 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3065 }
3066
3067 @Override
3068 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003069 mH.post(() -> {
3070 synchronized (mGlobalLock) {
3071 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003072 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003073 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003074 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003075 } catch (RemoteException e) {
3076 }
3077 }
3078 }
3079
3080 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003081 }
3082
3083 /** Called from an app when assist data is ready. */
3084 @Override
3085 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3086 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003087 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003088 synchronized (pae) {
3089 pae.result = extras;
3090 pae.structure = structure;
3091 pae.content = content;
3092 if (referrer != null) {
3093 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3094 }
3095 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003096 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003097 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003098 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003099 structure.setHomeActivity(pae.isHome);
3100 }
3101 pae.haveResult = true;
3102 pae.notifyAll();
3103 if (pae.intent == null && pae.receiver == null) {
3104 // Caller is just waiting for the result.
3105 return;
3106 }
3107 }
3108 // We are now ready to launch the assist activity.
3109 IAssistDataReceiver sendReceiver = null;
3110 Bundle sendBundle = null;
3111 synchronized (mGlobalLock) {
3112 buildAssistBundleLocked(pae, extras);
3113 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003114 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003115 if (!exists) {
3116 // Timed out.
3117 return;
3118 }
3119
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003120 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003121 // Caller wants result sent back to them.
3122 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003123 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003124 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003125 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3126 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003127 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3128 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3129 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3130 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3131 }
3132 }
3133 if (sendReceiver != null) {
3134 try {
3135 sendReceiver.onHandleAssistData(sendBundle);
3136 } catch (RemoteException e) {
3137 }
3138 return;
3139 }
3140
3141 final long ident = Binder.clearCallingIdentity();
3142 try {
3143 if (TextUtils.equals(pae.intent.getAction(),
3144 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003145 // Start voice interaction through VoiceInteractionManagerService.
3146 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3147 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003148 } else {
3149 pae.intent.replaceExtras(pae.extras);
3150 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3151 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3152 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003153 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003154
3155 try {
3156 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3157 } catch (ActivityNotFoundException e) {
3158 Slog.w(TAG, "No activity to handle assist action.", e);
3159 }
3160 }
3161 } finally {
3162 Binder.restoreCallingIdentity(ident);
3163 }
3164 }
3165
3166 @Override
3167 public int addAppTask(IBinder activityToken, Intent intent,
3168 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3169 final int callingUid = Binder.getCallingUid();
3170 final long callingIdent = Binder.clearCallingIdentity();
3171
3172 try {
3173 synchronized (mGlobalLock) {
3174 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3175 if (r == null) {
3176 throw new IllegalArgumentException("Activity does not exist; token="
3177 + activityToken);
3178 }
3179 ComponentName comp = intent.getComponent();
3180 if (comp == null) {
3181 throw new IllegalArgumentException("Intent " + intent
3182 + " must specify explicit component");
3183 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003184 if (thumbnail.getWidth() != mThumbnailWidth
3185 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003186 throw new IllegalArgumentException("Bad thumbnail size: got "
3187 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003188 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 }
3190 if (intent.getSelector() != null) {
3191 intent.setSelector(null);
3192 }
3193 if (intent.getSourceBounds() != null) {
3194 intent.setSourceBounds(null);
3195 }
3196 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3197 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3198 // The caller has added this as an auto-remove task... that makes no
3199 // sense, so turn off auto-remove.
3200 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3201 }
3202 }
3203 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3204 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3205 if (ainfo.applicationInfo.uid != callingUid) {
3206 throw new SecurityException(
3207 "Can't add task for another application: target uid="
3208 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3209 }
3210
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003211 final ActivityStack stack = r.getRootTask();
Louis Changcdec0802019-11-11 11:45:07 +08003212 final Task task = stack.createTask(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08003213 mStackSupervisor.getNextTaskIdForUser(r.mUserId), ainfo, intent, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003214 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003215 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003216 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003217 return INVALID_TASK_ID;
3218 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003219 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003220
3221 // TODO: Send the thumbnail to WM to store it.
3222
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003223 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003224 }
3225 } finally {
3226 Binder.restoreCallingIdentity(callingIdent);
3227 }
3228 }
3229
3230 @Override
3231 public Point getAppTaskThumbnailSize() {
3232 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003233 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003234 }
3235 }
3236
3237 @Override
3238 public void setTaskResizeable(int taskId, int resizeableMode) {
3239 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003240 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003241 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3242 if (task == null) {
3243 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3244 return;
3245 }
3246 task.setResizeMode(resizeableMode);
3247 }
3248 }
3249
3250 @Override
3251 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003252 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003253 long ident = Binder.clearCallingIdentity();
3254 try {
3255 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003256 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003257 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003258 if (task == null) {
3259 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3260 return;
3261 }
3262 // Place the task in the right stack if it isn't there already based on
3263 // the requested bounds.
3264 // The stack transition logic is:
3265 // - a null bounds on a freeform task moves that task to fullscreen
3266 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3267 // that task to freeform
3268 // - otherwise the task is not moved
3269 ActivityStack stack = task.getStack();
3270 if (!task.getWindowConfiguration().canResizeTask()) {
3271 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3272 }
3273 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3274 stack = stack.getDisplay().getOrCreateStack(
3275 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3276 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3277 stack = stack.getDisplay().getOrCreateStack(
3278 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3279 }
3280
3281 // Reparent the task to the right stack if necessary
3282 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3283 if (stack != task.getStack()) {
3284 // Defer resume until the task is resized below
3285 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3286 DEFER_RESUME, "resizeTask");
3287 preserveWindow = false;
3288 }
3289
3290 // After reparenting (which only resizes the task to the stack bounds), resize the
3291 // task to the actual bounds provided
3292 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3293 }
3294 } finally {
3295 Binder.restoreCallingIdentity(ident);
3296 }
3297 }
3298
3299 @Override
3300 public boolean releaseActivityInstance(IBinder token) {
3301 synchronized (mGlobalLock) {
3302 final long origId = Binder.clearCallingIdentity();
3303 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003304 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3305 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003306 return false;
3307 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003308 r.destroyImmediately(true /* removeFromApp */, "app-req");
3309 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003310 } finally {
3311 Binder.restoreCallingIdentity(origId);
3312 }
3313 }
3314 }
3315
3316 @Override
3317 public void releaseSomeActivities(IApplicationThread appInt) {
3318 synchronized (mGlobalLock) {
3319 final long origId = Binder.clearCallingIdentity();
3320 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003321 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003322 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003323 } finally {
3324 Binder.restoreCallingIdentity(origId);
3325 }
3326 }
3327 }
3328
3329 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003330 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003331 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003332 != PackageManager.PERMISSION_GRANTED) {
3333 throw new SecurityException("Requires permission "
3334 + android.Manifest.permission.DEVICE_POWER);
3335 }
3336
3337 synchronized (mGlobalLock) {
3338 long ident = Binder.clearCallingIdentity();
3339 if (mKeyguardShown != keyguardShowing) {
3340 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003341 final Message msg = PooledLambda.obtainMessage(
3342 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3343 keyguardShowing);
3344 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003345 }
3346 try {
wilsonshih177261f2019-02-22 12:02:18 +08003347 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003348 } finally {
3349 Binder.restoreCallingIdentity(ident);
3350 }
3351 }
3352
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003353 mH.post(() -> {
3354 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3355 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3356 }
3357 });
3358 }
3359
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003360 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003361 mH.post(() -> {
3362 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3363 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3364 }
3365 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003366 }
3367
3368 @Override
3369 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003370 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3371 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003372
3373 final File passedIconFile = new File(filePath);
3374 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3375 passedIconFile.getName());
3376 if (!legitIconFile.getPath().equals(filePath)
3377 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3378 throw new IllegalArgumentException("Bad file path: " + filePath
3379 + " passed for userId " + userId);
3380 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003381 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003382 }
3383
3384 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003385 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003386 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003387 synchronized (mGlobalLock) {
3388 final long ident = Binder.clearCallingIdentity();
3389 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003390 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003391 if (stack == null) {
3392 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3393 return;
3394 }
3395 if (!stack.isActivityTypeStandardOrUndefined()) {
3396 throw new IllegalArgumentException(
3397 "Removing non-standard stack is not allowed.");
3398 }
3399 mStackSupervisor.removeStack(stack);
3400 } finally {
3401 Binder.restoreCallingIdentity(ident);
3402 }
3403 }
3404 }
3405
3406 @Override
3407 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003408 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003409
3410 synchronized (mGlobalLock) {
3411 final long ident = Binder.clearCallingIdentity();
3412 try {
3413 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3414 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003415 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416 } finally {
3417 Binder.restoreCallingIdentity(ident);
3418 }
3419 }
3420 }
3421
3422 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003423 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 synchronized (mGlobalLock) {
3425 long ident = Binder.clearCallingIdentity();
3426 try {
3427 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3428 if (r == null) {
3429 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003430 "toggleFreeformWindowingMode: No activity record matching token="
3431 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003432 }
3433
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003434 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003435 if (stack == null) {
3436 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3437 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003438 }
3439
Yunfan Chend967af82019-01-17 18:30:18 +09003440 if (!stack.inFreeformWindowingMode()
3441 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3442 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3443 + "toggle between fullscreen and freeform.");
3444 }
3445
3446 if (stack.inFreeformWindowingMode()) {
3447 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003448 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003449 throw new IllegalStateException("Size-compat windows are currently not"
3450 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003451 } else if (stack.getParent().inFreeformWindowingMode()) {
3452 // If the window is on a freeform display, set it to undefined. It will be
3453 // resolved to freeform and it can adjust windowing mode when the display mode
3454 // changes in runtime.
3455 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003456 } else {
3457 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3458 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003459 } finally {
3460 Binder.restoreCallingIdentity(ident);
3461 }
3462 }
3463 }
3464
3465 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3466 @Override
3467 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003468 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003469 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003470 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003471 }
3472
3473 /** Unregister a task stack listener so that it stops receiving callbacks. */
3474 @Override
3475 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003476 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003477 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003478 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003479 }
3480
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003481 @Override
3482 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3483 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3484 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3485 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3486 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3487 }
3488
3489 @Override
3490 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3491 IBinder activityToken, int flags) {
3492 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3493 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3494 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3495 }
3496
3497 @Override
3498 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3499 Bundle args) {
3500 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3501 true /* focused */, true /* newSessionId */, userHandle, args,
3502 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3503 }
3504
3505 @Override
3506 public Bundle getAssistContextExtras(int requestType) {
3507 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3508 null, null, true /* focused */, true /* newSessionId */,
3509 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3510 if (pae == null) {
3511 return null;
3512 }
3513 synchronized (pae) {
3514 while (!pae.haveResult) {
3515 try {
3516 pae.wait();
3517 } catch (InterruptedException e) {
3518 }
3519 }
3520 }
3521 synchronized (mGlobalLock) {
3522 buildAssistBundleLocked(pae, pae.result);
3523 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003524 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003525 }
3526 return pae.extras;
3527 }
3528
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003529 /**
3530 * Binder IPC calls go through the public entry point.
3531 * This can be called with or without the global lock held.
3532 */
3533 private static int checkCallingPermission(String permission) {
3534 return checkPermission(
3535 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3536 }
3537
3538 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003539 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003540 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3541 mAmInternal.enforceCallingPermission(permission, func);
3542 }
3543 }
3544
3545 @VisibleForTesting
3546 int checkGetTasksPermission(String permission, int pid, int uid) {
3547 return checkPermission(permission, pid, uid);
3548 }
3549
3550 static int checkPermission(String permission, int pid, int uid) {
3551 if (permission == null) {
3552 return PackageManager.PERMISSION_DENIED;
3553 }
3554 return checkComponentPermission(permission, pid, uid, -1, true);
3555 }
3556
Wale Ogunwale214f3482018-10-04 11:00:47 -07003557 public static int checkComponentPermission(String permission, int pid, int uid,
3558 int owningUid, boolean exported) {
3559 return ActivityManagerService.checkComponentPermission(
3560 permission, pid, uid, owningUid, exported);
3561 }
3562
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003563 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3564 if (getRecentTasks().isCallerRecents(callingUid)) {
3565 // Always allow the recents component to get tasks
3566 return true;
3567 }
3568
3569 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3570 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3571 if (!allowed) {
3572 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3573 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3574 // Temporary compatibility: some existing apps on the system image may
3575 // still be requesting the old permission and not switched to the new
3576 // one; if so, we'll still allow them full access. This means we need
3577 // to see if they are holding the old permission and are a system app.
3578 try {
3579 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3580 allowed = true;
3581 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3582 + " is using old GET_TASKS but privileged; allowing");
3583 }
3584 } catch (RemoteException e) {
3585 }
3586 }
3587 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3588 + " does not hold REAL_GET_TASKS; limiting output");
3589 }
3590 return allowed;
3591 }
3592
Nicholas Sauer0259e532019-08-30 08:24:55 -07003593 boolean isCrossUserAllowed(int pid, int uid) {
3594 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3595 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3596 }
3597
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003598 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3599 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3600 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3601 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003602 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003603 "enqueueAssistContext()");
3604
3605 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003606 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003607 if (activity == null) {
3608 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3609 return null;
3610 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003611 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003612 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3613 return null;
3614 }
3615 if (focused) {
3616 if (activityToken != null) {
3617 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3618 if (activity != caller) {
3619 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3620 + " is not current top " + activity);
3621 return null;
3622 }
3623 }
3624 } else {
3625 activity = ActivityRecord.forTokenLocked(activityToken);
3626 if (activity == null) {
3627 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3628 + " couldn't be found");
3629 return null;
3630 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003631 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003632 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3633 return null;
3634 }
3635 }
3636
3637 PendingAssistExtras pae;
3638 Bundle extras = new Bundle();
3639 if (args != null) {
3640 extras.putAll(args);
3641 }
3642 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003643 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003644
3645 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3646 userHandle);
3647 pae.isHome = activity.isActivityTypeHome();
3648
3649 // Increment the sessionId if necessary
3650 if (newSessionId) {
3651 mViSessionId++;
3652 }
3653 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003654 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3655 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003656 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003657 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003658 } catch (RemoteException e) {
3659 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3660 return null;
3661 }
3662 return pae;
3663 }
3664 }
3665
3666 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3667 if (result != null) {
3668 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3669 }
3670 if (pae.hint != null) {
3671 pae.extras.putBoolean(pae.hint, true);
3672 }
3673 }
3674
3675 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3676 IAssistDataReceiver receiver;
3677 synchronized (mGlobalLock) {
3678 mPendingAssistExtras.remove(pae);
3679 receiver = pae.receiver;
3680 }
3681 if (receiver != null) {
3682 // Caller wants result sent back to them.
3683 Bundle sendBundle = new Bundle();
3684 // At least return the receiver extras
3685 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3686 try {
3687 pae.receiver.onHandleAssistData(sendBundle);
3688 } catch (RemoteException e) {
3689 }
3690 }
3691 }
3692
3693 public class PendingAssistExtras extends Binder implements Runnable {
3694 public final ActivityRecord activity;
3695 public boolean isHome;
3696 public final Bundle extras;
3697 public final Intent intent;
3698 public final String hint;
3699 public final IAssistDataReceiver receiver;
3700 public final int userHandle;
3701 public boolean haveResult = false;
3702 public Bundle result = null;
3703 public AssistStructure structure = null;
3704 public AssistContent content = null;
3705 public Bundle receiverExtras;
3706
3707 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3708 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3709 int _userHandle) {
3710 activity = _activity;
3711 extras = _extras;
3712 intent = _intent;
3713 hint = _hint;
3714 receiver = _receiver;
3715 receiverExtras = _receiverExtras;
3716 userHandle = _userHandle;
3717 }
3718
3719 @Override
3720 public void run() {
3721 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3722 synchronized (this) {
3723 haveResult = true;
3724 notifyAll();
3725 }
3726 pendingAssistExtrasTimedOut(this);
3727 }
3728 }
3729
3730 @Override
3731 public boolean isAssistDataAllowedOnCurrentActivity() {
3732 int userId;
3733 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003734 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003735 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3736 return false;
3737 }
3738
Wale Ogunwale21e06482019-11-18 05:14:15 -08003739 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003740 if (activity == null) {
3741 return false;
3742 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003743 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003744 }
3745 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3746 }
3747
3748 @Override
3749 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3750 long ident = Binder.clearCallingIdentity();
3751 try {
3752 synchronized (mGlobalLock) {
3753 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003754 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003755 if (top != caller) {
3756 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3757 + " is not current top " + top);
3758 return false;
3759 }
3760 if (!top.nowVisible) {
3761 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3762 + " is not visible");
3763 return false;
3764 }
3765 }
3766 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3767 token);
3768 } finally {
3769 Binder.restoreCallingIdentity(ident);
3770 }
3771 }
3772
3773 @Override
3774 public boolean isRootVoiceInteraction(IBinder token) {
3775 synchronized (mGlobalLock) {
3776 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3777 if (r == null) {
3778 return false;
3779 }
3780 return r.rootVoiceInteraction;
3781 }
3782 }
3783
Wale Ogunwalef6733932018-06-27 05:14:34 -07003784 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3785 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3786 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3787 if (activityToCallback == null) return;
3788 activityToCallback.setVoiceSessionLocked(voiceSession);
3789
3790 // Inform the activity
3791 try {
3792 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3793 voiceInteractor);
3794 long token = Binder.clearCallingIdentity();
3795 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003796 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003797 } finally {
3798 Binder.restoreCallingIdentity(token);
3799 }
3800 // TODO: VI Should we cache the activity so that it's easier to find later
3801 // rather than scan through all the stacks and activities?
3802 } catch (RemoteException re) {
3803 activityToCallback.clearVoiceSessionLocked();
3804 // TODO: VI Should this terminate the voice session?
3805 }
3806 }
3807
3808 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3809 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3810 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3811 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3812 boolean wasRunningVoice = mRunningVoice != null;
3813 mRunningVoice = session;
3814 if (!wasRunningVoice) {
3815 mVoiceWakeLock.acquire();
3816 updateSleepIfNeededLocked();
3817 }
3818 }
3819 }
3820
3821 void finishRunningVoiceLocked() {
3822 if (mRunningVoice != null) {
3823 mRunningVoice = null;
3824 mVoiceWakeLock.release();
3825 updateSleepIfNeededLocked();
3826 }
3827 }
3828
3829 @Override
3830 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3831 synchronized (mGlobalLock) {
3832 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3833 if (keepAwake) {
3834 mVoiceWakeLock.acquire();
3835 } else {
3836 mVoiceWakeLock.release();
3837 }
3838 }
3839 }
3840 }
3841
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003842 @Override
3843 public ComponentName getActivityClassForToken(IBinder token) {
3844 synchronized (mGlobalLock) {
3845 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3846 if (r == null) {
3847 return null;
3848 }
3849 return r.intent.getComponent();
3850 }
3851 }
3852
3853 @Override
3854 public String getPackageForToken(IBinder token) {
3855 synchronized (mGlobalLock) {
3856 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3857 if (r == null) {
3858 return null;
3859 }
3860 return r.packageName;
3861 }
3862 }
3863
3864 @Override
3865 public void showLockTaskEscapeMessage(IBinder token) {
3866 synchronized (mGlobalLock) {
3867 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3868 if (r == null) {
3869 return;
3870 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003871 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003872 }
3873 }
3874
3875 @Override
3876 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003877 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003878 final long token = Binder.clearCallingIdentity();
3879 try {
3880 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003881 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003882 }
3883 } finally {
3884 Binder.restoreCallingIdentity(token);
3885 }
3886 }
3887
3888 /**
3889 * Try to place task to provided position. The final position might be different depending on
3890 * current user and stacks state. The task will be moved to target stack if it's currently in
3891 * different stack.
3892 */
3893 @Override
3894 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003895 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003896 synchronized (mGlobalLock) {
3897 long ident = Binder.clearCallingIdentity();
3898 try {
3899 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3900 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003901 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003902 if (task == null) {
3903 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3904 + taskId);
3905 }
3906
Louis Chang149d5c82019-12-30 09:47:39 +08003907 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003908
3909 if (stack == null) {
3910 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3911 + stackId);
3912 }
3913 if (!stack.isActivityTypeStandardOrUndefined()) {
3914 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3915 + " the position of task " + taskId + " in/to non-standard stack");
3916 }
3917
3918 // TODO: Have the callers of this API call a separate reparent method if that is
3919 // what they intended to do vs. having this method also do reparenting.
3920 if (task.getStack() == stack) {
3921 // Change position in current stack.
3922 stack.positionChildAt(task, position);
3923 } else {
3924 // Reparent to new stack.
3925 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3926 !DEFER_RESUME, "positionTaskInStack");
3927 }
3928 } finally {
3929 Binder.restoreCallingIdentity(ident);
3930 }
3931 }
3932 }
3933
3934 @Override
3935 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3936 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3937 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003938 + Arrays.toString(horizontalSizeConfiguration) + " "
3939 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003940 synchronized (mGlobalLock) {
3941 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3942 if (record == null) {
3943 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3944 + "found for: " + token);
3945 }
3946 record.setSizeConfigurations(horizontalSizeConfiguration,
3947 verticalSizeConfigurations, smallestSizeConfigurations);
3948 }
3949 }
3950
3951 /**
3952 * Dismisses split-screen multi-window mode.
3953 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3954 */
3955 @Override
3956 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003957 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003958 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3959 final long ident = Binder.clearCallingIdentity();
3960 try {
3961 synchronized (mGlobalLock) {
3962 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08003963 mRootWindowContainer.getDefaultDisplay().getRootSplitScreenPrimaryTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003964 if (stack == null) {
3965 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3966 return;
3967 }
3968
3969 if (toTop) {
3970 // Caller wants the current split-screen primary stack to be the top stack after
3971 // it goes fullscreen, so move it to the front.
3972 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003973 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003974 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003975 // stack after it goes fullscreen, so we move the focus to the top-most
3976 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003977 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3978 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3979 if (otherStack != null) {
3980 otherStack.moveToFront("dismissSplitScreenMode_other");
3981 }
3982 }
3983
Evan Rosky10475742018-09-05 19:02:48 -07003984 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003985 }
3986 } finally {
3987 Binder.restoreCallingIdentity(ident);
3988 }
3989 }
3990
3991 /**
3992 * Dismisses Pip
3993 * @param animate True if the dismissal should be animated.
3994 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3995 * default animation duration should be used.
3996 */
3997 @Override
3998 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003999 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004000 final long ident = Binder.clearCallingIdentity();
4001 try {
4002 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004003 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08004004 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004005 if (stack == null) {
4006 Slog.w(TAG, "dismissPip: pinned stack not found.");
4007 return;
4008 }
4009 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4010 throw new IllegalArgumentException("Stack: " + stack
4011 + " doesn't support animated resize.");
4012 }
Robert Carr8a2f9132019-11-11 15:03:15 -08004013 /**
4014 * TODO(b/146594635): Remove all PIP animation code from WM
4015 * once SysUI handles animation. Don't even try to animate TaskOrganized tasks.
4016 */
4017 if (animate && !stack.isControlledByTaskOrganizer()) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004018 stack.animateResizePinnedStack(null /* destBounds */,
4019 null /* sourceHintBounds */, animationDuration,
4020 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004021 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004022 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004023 }
4024 }
4025 } finally {
4026 Binder.restoreCallingIdentity(ident);
4027 }
4028 }
4029
4030 @Override
4031 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004032 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004033 synchronized (mGlobalLock) {
4034 mSuppressResizeConfigChanges = suppress;
4035 }
4036 }
4037
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004038 @Override
4039 // TODO: API should just be about changing windowing modes...
4040 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004041 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004042 "moveTasksToFullscreenStack()");
4043 synchronized (mGlobalLock) {
4044 final long origId = Binder.clearCallingIdentity();
4045 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004046 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004047 if (stack != null){
4048 if (!stack.isActivityTypeStandardOrUndefined()) {
4049 throw new IllegalArgumentException(
4050 "You can't move tasks from non-standard stacks.");
4051 }
4052 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4053 }
4054 } finally {
4055 Binder.restoreCallingIdentity(origId);
4056 }
4057 }
4058 }
4059
4060 /**
4061 * Moves the top activity in the input stackId to the pinned stack.
4062 *
4063 * @param stackId Id of stack to move the top activity to pinned stack.
4064 * @param bounds Bounds to use for pinned stack.
4065 *
4066 * @return True if the top activity of the input stack was successfully moved to the pinned
4067 * stack.
4068 */
4069 @Override
4070 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004071 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004072 "moveTopActivityToPinnedStack()");
4073 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004074 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004075 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4076 + "Device doesn't support picture-in-picture mode");
4077 }
4078
4079 long ident = Binder.clearCallingIdentity();
4080 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004081 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004082 } finally {
4083 Binder.restoreCallingIdentity(ident);
4084 }
4085 }
4086 }
4087
4088 @Override
4089 public boolean isInMultiWindowMode(IBinder token) {
4090 final long origId = Binder.clearCallingIdentity();
4091 try {
4092 synchronized (mGlobalLock) {
4093 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4094 if (r == null) {
4095 return false;
4096 }
4097 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4098 return r.inMultiWindowMode();
4099 }
4100 } finally {
4101 Binder.restoreCallingIdentity(origId);
4102 }
4103 }
4104
4105 @Override
4106 public boolean isInPictureInPictureMode(IBinder token) {
4107 final long origId = Binder.clearCallingIdentity();
4108 try {
4109 synchronized (mGlobalLock) {
4110 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4111 }
4112 } finally {
4113 Binder.restoreCallingIdentity(origId);
4114 }
4115 }
4116
4117 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004118 if (r == null || r.getRootTask() == null || !r.inPinnedWindowingMode()
4119 || r.getRootTask().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004120 return false;
4121 }
4122
4123 // If we are animating to fullscreen then we have already dispatched the PIP mode
4124 // changed, so we should reflect that check here as well.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004125 final ActivityStack taskStack = r.getRootTask();
Yunfan Chen279f5582018-12-12 15:24:50 -08004126 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004127 }
4128
4129 @Override
4130 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4131 final long origId = Binder.clearCallingIdentity();
4132 try {
4133 synchronized (mGlobalLock) {
4134 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4135 "enterPictureInPictureMode", token, params);
4136
4137 // If the activity is already in picture in picture mode, then just return early
4138 if (isInPictureInPictureMode(r)) {
4139 return true;
4140 }
4141
4142 // Activity supports picture-in-picture, now check that we can enter PiP at this
4143 // point, if it is
4144 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4145 false /* beforeStopping */)) {
4146 return false;
4147 }
4148
4149 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004150 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004151 if (r.getParent() == null) {
4152 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4153 return;
4154 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004155 // Only update the saved args from the args that are set
4156 r.pictureInPictureArgs.copyOnlySet(params);
4157 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4158 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4159 // Adjust the source bounds by the insets for the transition down
4160 final Rect sourceBounds = new Rect(
4161 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004162 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004163 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004164 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004165 stack.setPictureInPictureAspectRatio(aspectRatio);
4166 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004167 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4168 r.info.applicationInfo.uid, r.shortComponentName,
4169 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004170 logPictureInPictureArgs(params);
4171 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004172 };
4173
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004174 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004175 // If the keyguard is showing or occluded, then try and dismiss it before
4176 // entering picture-in-picture (this will prompt the user to authenticate if the
4177 // device is currently locked).
4178 dismissKeyguard(token, new KeyguardDismissCallback() {
4179 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004180 public void onDismissSucceeded() {
4181 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004182 }
4183 }, null /* message */);
4184 } else {
4185 // Enter picture in picture immediately otherwise
4186 enterPipRunnable.run();
4187 }
4188 return true;
4189 }
4190 } finally {
4191 Binder.restoreCallingIdentity(origId);
4192 }
4193 }
4194
4195 @Override
4196 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4197 final long origId = Binder.clearCallingIdentity();
4198 try {
4199 synchronized (mGlobalLock) {
4200 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4201 "setPictureInPictureParams", token, params);
4202
4203 // Only update the saved args from the args that are set
4204 r.pictureInPictureArgs.copyOnlySet(params);
4205 if (r.inPinnedWindowingMode()) {
4206 // If the activity is already in picture-in-picture, update the pinned stack now
4207 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4208 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004209 final ActivityStack stack = r.getRootTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004210 if (!stack.isAnimatingBoundsToFullscreen()) {
4211 stack.setPictureInPictureAspectRatio(
4212 r.pictureInPictureArgs.getAspectRatio());
4213 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4214 }
4215 }
4216 logPictureInPictureArgs(params);
4217 }
4218 } finally {
4219 Binder.restoreCallingIdentity(origId);
4220 }
4221 }
4222
4223 @Override
4224 public int getMaxNumPictureInPictureActions(IBinder token) {
4225 // Currently, this is a static constant, but later, we may change this to be dependent on
4226 // the context of the activity
4227 return 3;
4228 }
4229
4230 private void logPictureInPictureArgs(PictureInPictureParams params) {
4231 if (params.hasSetActions()) {
4232 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4233 params.getActions().size());
4234 }
4235 if (params.hasSetAspectRatio()) {
4236 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4237 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4238 MetricsLogger.action(lm);
4239 }
4240 }
4241
4242 /**
4243 * Checks the state of the system and the activity associated with the given {@param token} to
4244 * verify that picture-in-picture is supported for that activity.
4245 *
4246 * @return the activity record for the given {@param token} if all the checks pass.
4247 */
4248 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4249 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004250 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004251 throw new IllegalStateException(caller
4252 + ": Device doesn't support picture-in-picture mode.");
4253 }
4254
4255 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4256 if (r == null) {
4257 throw new IllegalStateException(caller
4258 + ": Can't find activity for token=" + token);
4259 }
4260
4261 if (!r.supportsPictureInPicture()) {
4262 throw new IllegalStateException(caller
4263 + ": Current activity does not support picture-in-picture.");
4264 }
4265
4266 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004267 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004268 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004269 final float minAspectRatio = mContext.getResources().getFloat(
4270 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4271 final float maxAspectRatio = mContext.getResources().getFloat(
4272 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4273 throw new IllegalArgumentException(String.format(caller
4274 + ": Aspect ratio is too extreme (must be between %f and %f).",
4275 minAspectRatio, maxAspectRatio));
4276 }
4277
4278 // Truncate the number of actions if necessary
4279 params.truncateActions(getMaxNumPictureInPictureActions(token));
4280
4281 return r;
4282 }
4283
4284 @Override
4285 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004286 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004287 synchronized (mGlobalLock) {
4288 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4289 if (r == null) {
4290 throw new IllegalArgumentException("Activity does not exist; token="
4291 + activityToken);
4292 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004293 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004294 }
4295 }
4296
4297 @Override
4298 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4299 Rect tempDockedTaskInsetBounds,
4300 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004301 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004302 long ident = Binder.clearCallingIdentity();
4303 try {
4304 synchronized (mGlobalLock) {
4305 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4306 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4307 PRESERVE_WINDOWS);
4308 }
4309 } finally {
4310 Binder.restoreCallingIdentity(ident);
4311 }
4312 }
4313
4314 @Override
4315 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004316 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004317 final long ident = Binder.clearCallingIdentity();
4318 try {
4319 synchronized (mGlobalLock) {
4320 mStackSupervisor.setSplitScreenResizing(resizing);
4321 }
4322 } finally {
4323 Binder.restoreCallingIdentity(ident);
4324 }
4325 }
4326
Evan Rosky0037e5f2019-11-05 10:26:24 -08004327 @Override
4328 public ITaskOrganizerController getTaskOrganizerController() {
4329 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
4330 "getTaskOrganizerController()");
4331 return mTaskOrganizerController;
4332 }
4333
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004334 /**
4335 * Check that we have the features required for VR-related API calls, and throw an exception if
4336 * not.
4337 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004338 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004339 if (!mContext.getPackageManager().hasSystemFeature(
4340 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4341 throw new UnsupportedOperationException("VR mode not supported on this device!");
4342 }
4343 }
4344
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004345 @Override
4346 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004347 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004348
4349 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4350
4351 ActivityRecord r;
4352 synchronized (mGlobalLock) {
4353 r = ActivityRecord.isInStackLocked(token);
4354 }
4355
4356 if (r == null) {
4357 throw new IllegalArgumentException();
4358 }
4359
4360 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004361 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004362 VrManagerInternal.NO_ERROR) {
4363 return err;
4364 }
4365
4366 // Clear the binder calling uid since this path may call moveToTask().
4367 final long callingId = Binder.clearCallingIdentity();
4368 try {
4369 synchronized (mGlobalLock) {
4370 r.requestedVrComponent = (enabled) ? packageName : null;
4371
4372 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004373 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004374 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004375 }
4376 return 0;
4377 }
4378 } finally {
4379 Binder.restoreCallingIdentity(callingId);
4380 }
4381 }
4382
4383 @Override
4384 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4385 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4386 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004387 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004388 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4389 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4390 }
Louis Changcdec0802019-11-11 11:45:07 +08004391 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004392 || activity.voiceSession != null) {
4393 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4394 return;
4395 }
4396 if (activity.pendingVoiceInteractionStart) {
4397 Slog.w(TAG, "Pending start of voice interaction already.");
4398 return;
4399 }
4400 activity.pendingVoiceInteractionStart = true;
4401 }
4402 LocalServices.getService(VoiceInteractionManagerInternal.class)
4403 .startLocalVoiceInteraction(callingActivity, options);
4404 }
4405
4406 @Override
4407 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4408 LocalServices.getService(VoiceInteractionManagerInternal.class)
4409 .stopLocalVoiceInteraction(callingActivity);
4410 }
4411
4412 @Override
4413 public boolean supportsLocalVoiceInteraction() {
4414 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4415 .supportsLocalVoiceInteraction();
4416 }
4417
4418 /** Notifies all listeners when the pinned stack animation starts. */
4419 @Override
4420 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004421 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004422 }
4423
4424 /** Notifies all listeners when the pinned stack animation ends. */
4425 @Override
4426 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004427 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004428 }
4429
4430 @Override
4431 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004432 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004433 final long ident = Binder.clearCallingIdentity();
4434 try {
4435 synchronized (mGlobalLock) {
4436 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4437 }
4438 } finally {
4439 Binder.restoreCallingIdentity(ident);
4440 }
4441 }
4442
4443 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004445 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004446
4447 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004448 if (mWindowManager == null) {
4449 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4450 return false;
4451 }
4452
4453 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004455 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004456 }
4457
Riddle Hsua0022cd2019-09-09 21:12:41 +08004458 mH.sendMessage(PooledLambda.obtainMessage(
4459 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4460 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004461
4462 final long origId = Binder.clearCallingIdentity();
4463 try {
4464 if (values != null) {
4465 Settings.System.clearConfiguration(values);
4466 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004467 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004468 UserHandle.USER_NULL, false /* deferResume */,
4469 mTmpUpdateConfigurationResult);
4470 return mTmpUpdateConfigurationResult.changes != 0;
4471 } finally {
4472 Binder.restoreCallingIdentity(origId);
4473 }
4474 }
4475 }
4476
4477 @Override
4478 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4479 CharSequence message) {
4480 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004481 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004482 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4483 }
4484 final long callingId = Binder.clearCallingIdentity();
4485 try {
4486 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004487 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004488 }
4489 } finally {
4490 Binder.restoreCallingIdentity(callingId);
4491 }
4492 }
4493
4494 @Override
4495 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004496 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004497 "cancelTaskWindowTransition()");
4498 final long ident = Binder.clearCallingIdentity();
4499 try {
4500 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004501 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004502 MATCH_TASK_IN_STACKS_ONLY);
4503 if (task == null) {
4504 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4505 return;
4506 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004507 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004508 }
4509 } finally {
4510 Binder.restoreCallingIdentity(ident);
4511 }
4512 }
4513
4514 @Override
4515 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004516 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004517 final long ident = Binder.clearCallingIdentity();
4518 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004519 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004520 } finally {
4521 Binder.restoreCallingIdentity(ident);
4522 }
4523 }
4524
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004525 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4526 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004527 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004528 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004529 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004530 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4531 if (task == null) {
4532 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4533 return null;
4534 }
4535 }
4536 // Don't call this while holding the lock as this operation might hit the disk.
4537 return task.getSnapshot(reducedResolution, restoreFromDisk);
4538 }
4539
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004540 @Override
4541 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4542 synchronized (mGlobalLock) {
4543 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4544 if (r == null) {
4545 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4546 + token);
4547 return;
4548 }
4549 final long origId = Binder.clearCallingIdentity();
4550 try {
4551 r.setDisablePreviewScreenshots(disable);
4552 } finally {
4553 Binder.restoreCallingIdentity(origId);
4554 }
4555 }
4556 }
4557
Riddle Hsu440f88b2019-11-06 22:17:35 +08004558 @Override
4559 public void invalidateHomeTaskSnapshot(IBinder token) {
4560 synchronized (mGlobalLock) {
4561 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4562 if (r == null || !r.isActivityTypeHome()) {
4563 return;
4564 }
4565 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4566 }
4567 }
4568
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004569 /** Return the user id of the last resumed activity. */
4570 @Override
4571 public @UserIdInt
4572 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004573 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004574 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4575 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004576 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004577 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004578 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004579 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004580 }
4581 }
4582
4583 @Override
4584 public void updateLockTaskFeatures(int userId, int flags) {
4585 final int callingUid = Binder.getCallingUid();
4586 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004587 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004588 "updateLockTaskFeatures()");
4589 }
4590 synchronized (mGlobalLock) {
4591 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4592 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004593 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004594 }
4595 }
4596
4597 @Override
4598 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4599 synchronized (mGlobalLock) {
4600 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4601 if (r == null) {
4602 return;
4603 }
4604 final long origId = Binder.clearCallingIdentity();
4605 try {
4606 r.setShowWhenLocked(showWhenLocked);
4607 } finally {
4608 Binder.restoreCallingIdentity(origId);
4609 }
4610 }
4611 }
4612
4613 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004614 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4615 synchronized (mGlobalLock) {
4616 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4617 if (r == null) {
4618 return;
4619 }
4620 final long origId = Binder.clearCallingIdentity();
4621 try {
4622 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4623 } finally {
4624 Binder.restoreCallingIdentity(origId);
4625 }
4626 }
4627 }
4628
4629 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004630 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4631 synchronized (mGlobalLock) {
4632 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4633 if (r == null) {
4634 return;
4635 }
4636 final long origId = Binder.clearCallingIdentity();
4637 try {
4638 r.setTurnScreenOn(turnScreenOn);
4639 } finally {
4640 Binder.restoreCallingIdentity(origId);
4641 }
4642 }
4643 }
4644
4645 @Override
4646 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004647 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004648 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004649 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004650 synchronized (mGlobalLock) {
4651 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4652 if (r == null) {
4653 return;
4654 }
4655 final long origId = Binder.clearCallingIdentity();
4656 try {
4657 r.registerRemoteAnimations(definition);
4658 } finally {
4659 Binder.restoreCallingIdentity(origId);
4660 }
4661 }
4662 }
4663
4664 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004665 public void unregisterRemoteAnimations(IBinder token) {
4666 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4667 "unregisterRemoteAnimations");
4668 synchronized (mGlobalLock) {
4669 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4670 if (r == null) {
4671 return;
4672 }
4673 final long origId = Binder.clearCallingIdentity();
4674 try {
4675 r.unregisterRemoteAnimations();
4676 } finally {
4677 Binder.restoreCallingIdentity(origId);
4678 }
4679 }
4680 }
4681
4682 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004683 public void registerRemoteAnimationForNextActivityStart(String packageName,
4684 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004685 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004686 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004687 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004688 synchronized (mGlobalLock) {
4689 final long origId = Binder.clearCallingIdentity();
4690 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004691 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004692 packageName, adapter);
4693 } finally {
4694 Binder.restoreCallingIdentity(origId);
4695 }
4696 }
4697 }
4698
Evan Rosky966759f2019-01-15 10:33:58 -08004699 @Override
4700 public void registerRemoteAnimationsForDisplay(int displayId,
4701 RemoteAnimationDefinition definition) {
4702 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4703 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004704 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004705 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004706 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004707 if (display == null) {
4708 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4709 return;
4710 }
4711 final long origId = Binder.clearCallingIdentity();
4712 try {
4713 display.mDisplayContent.registerRemoteAnimations(definition);
4714 } finally {
4715 Binder.restoreCallingIdentity(origId);
4716 }
4717 }
4718 }
4719
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004720 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4721 @Override
4722 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4723 synchronized (mGlobalLock) {
4724 final long origId = Binder.clearCallingIdentity();
4725 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004726 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004727 } finally {
4728 Binder.restoreCallingIdentity(origId);
4729 }
4730 }
4731 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004732
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004733 @Override
4734 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004735 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004736 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004737 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004738 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004739 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004740 }
4741 }
4742
4743 @Override
4744 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004745 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004746 != PERMISSION_GRANTED) {
4747 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4748 + Binder.getCallingPid()
4749 + ", uid=" + Binder.getCallingUid()
4750 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4751 Slog.w(TAG, msg);
4752 throw new SecurityException(msg);
4753 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004754 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004755 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004756 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004757 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004758 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004759 }
4760 }
4761
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004762 @Override
4763 public void stopAppSwitches() {
4764 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4765 synchronized (mGlobalLock) {
4766 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004767 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004768 mDidAppSwitch = false;
4769 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4770 }
4771 }
4772
4773 @Override
4774 public void resumeAppSwitches() {
4775 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4776 synchronized (mGlobalLock) {
4777 // Note that we don't execute any pending app switches... we will
4778 // let those wait until either the timeout, or the next start
4779 // activity request.
4780 mAppSwitchesAllowedTime = 0;
4781 }
4782 }
4783
Ricky Wai906af482019-06-03 17:25:28 +01004784 long getLastStopAppSwitchesTime() {
4785 return mLastStopAppSwitchesTime;
4786 }
4787
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004788 void onStartActivitySetDidAppSwitch() {
4789 if (mDidAppSwitch) {
4790 // This is the second allowed switch since we stopped switches, so now just generally
4791 // allow switches. Use case:
4792 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4793 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4794 // anyone to switch again).
4795 mAppSwitchesAllowedTime = 0;
4796 } else {
4797 mDidAppSwitch = true;
4798 }
4799 }
4800
4801 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004802 boolean shouldDisableNonVrUiLocked() {
4803 return mVrController.shouldDisableNonVrUiLocked();
4804 }
4805
Wale Ogunwale53783742018-09-16 10:21:51 -07004806 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004807 // 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 +00004808 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004809 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004810 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4811 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004812 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004813 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004814 }
4815 mH.post(() -> {
4816 if (!mVrController.onVrModeChanged(r)) {
4817 return;
4818 }
4819 synchronized (mGlobalLock) {
4820 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4821 mWindowManager.disableNonVrUi(disableNonVrUi);
4822 if (disableNonVrUi) {
4823 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4824 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004825 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004826 }
4827 }
4828 });
4829 }
4830
Wale Ogunwale53783742018-09-16 10:21:51 -07004831 @Override
4832 public int getPackageScreenCompatMode(String packageName) {
4833 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4834 synchronized (mGlobalLock) {
4835 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4836 }
4837 }
4838
4839 @Override
4840 public void setPackageScreenCompatMode(String packageName, int mode) {
4841 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4842 "setPackageScreenCompatMode");
4843 synchronized (mGlobalLock) {
4844 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4845 }
4846 }
4847
4848 @Override
4849 public boolean getPackageAskScreenCompat(String packageName) {
4850 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4851 synchronized (mGlobalLock) {
4852 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4853 }
4854 }
4855
4856 @Override
4857 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4858 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4859 "setPackageAskScreenCompat");
4860 synchronized (mGlobalLock) {
4861 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4862 }
4863 }
4864
Wale Ogunwale64258362018-10-16 15:13:37 -07004865 public static String relaunchReasonToString(int relaunchReason) {
4866 switch (relaunchReason) {
4867 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4868 return "window_resize";
4869 case RELAUNCH_REASON_FREE_RESIZE:
4870 return "free_resize";
4871 default:
4872 return null;
4873 }
4874 }
4875
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004876 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004877 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004878 }
4879
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004880 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004881 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004882 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4883 }
4884
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004885 boolean isKeyguardLocked() {
4886 return mKeyguardController.isKeyguardLocked();
4887 }
4888
Garfield Tan01548632018-11-27 10:15:48 -08004889 /**
4890 * Clears launch params for the given package.
4891 * @param packageNames the names of the packages of which the launch params are to be cleared
4892 */
4893 @Override
4894 public void clearLaunchParamsForPackages(List<String> packageNames) {
4895 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4896 "clearLaunchParamsForPackages");
4897 synchronized (mGlobalLock) {
4898 for (int i = 0; i < packageNames.size(); ++i) {
4899 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4900 }
4901 }
4902 }
4903
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004904 /**
4905 * Makes the display with the given id a single task instance display. I.e the display can only
4906 * contain one task.
4907 */
4908 @Override
4909 public void setDisplayToSingleTaskInstance(int displayId) {
4910 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4911 "setDisplayToSingleTaskInstance");
4912 final long origId = Binder.clearCallingIdentity();
4913 try {
Louis Chang677921f2019-12-06 16:44:24 +08004914 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004915 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004916 if (display != null) {
4917 display.setDisplayToSingleTaskInstance();
4918 }
4919 } finally {
4920 Binder.restoreCallingIdentity(origId);
4921 }
4922 }
4923
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004924 /**
4925 * Requests that an activity should enter picture-in-picture mode if possible.
4926 */
4927 @Override
4928 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4929 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4930 "requestPictureInPictureMode");
4931 final long origId = Binder.clearCallingIdentity();
4932 try {
4933 synchronized (mGlobalLock) {
4934 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4935 if (activity == null) {
4936 return;
4937 }
4938
4939 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4940 "requestPictureInPictureMode", /* beforeStopping */ false);
4941 if (!canEnterPictureInPicture) {
4942 throw new IllegalStateException(
4943 "Requested PIP on an activity that doesn't support it");
4944 }
4945
4946 try {
4947 final ClientTransaction transaction = ClientTransaction.obtain(
4948 activity.app.getThread(),
4949 activity.token);
4950 transaction.addCallback(EnterPipRequestedItem.obtain());
4951 getLifecycleManager().scheduleTransaction(transaction);
4952 } catch (Exception e) {
4953 Slog.w(TAG, "Failed to send enter pip requested item: "
4954 + activity.intent.getComponent(), e);
4955 }
4956 }
4957 } finally {
4958 Binder.restoreCallingIdentity(origId);
4959 }
4960 }
4961
Wale Ogunwale31913b52018-10-13 08:29:31 -07004962 void dumpLastANRLocked(PrintWriter pw) {
4963 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4964 if (mLastANRState == null) {
4965 pw.println(" <no ANR has occurred since boot>");
4966 } else {
4967 pw.println(mLastANRState);
4968 }
4969 }
4970
4971 void dumpLastANRTracesLocked(PrintWriter pw) {
4972 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4973
4974 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4975 if (ArrayUtils.isEmpty(files)) {
4976 pw.println(" <no ANR has occurred since boot>");
4977 return;
4978 }
4979 // Find the latest file.
4980 File latest = null;
4981 for (File f : files) {
4982 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4983 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004984 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004985 }
4986 pw.print("File: ");
4987 pw.print(latest.getName());
4988 pw.println();
4989 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4990 String line;
4991 while ((line = in.readLine()) != null) {
4992 pw.println(line);
4993 }
4994 } catch (IOException e) {
4995 pw.print("Unable to read: ");
4996 pw.print(e);
4997 pw.println();
4998 }
4999 }
5000
5001 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5002 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
5003 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
5004 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
5005 }
5006
5007 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5008 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5009 pw.println(header);
5010
Louis Chang149d5c82019-12-30 09:47:39 +08005011 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005012 dumpPackage);
5013 boolean needSep = printedAnything;
5014
5015 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08005016 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005017 " ResumedActivity: ");
5018 if (printed) {
5019 printedAnything = true;
5020 needSep = false;
5021 }
5022
5023 if (dumpPackage == null) {
5024 if (needSep) {
5025 pw.println();
5026 }
5027 printedAnything = true;
5028 mStackSupervisor.dump(pw, " ");
5029 }
5030
5031 if (!printedAnything) {
5032 pw.println(" (nothing)");
5033 }
5034 }
5035
5036 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005037 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005038 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005039 pw.println(" ");
5040 }
5041
5042 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5043 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5044 getActivityStartController().dump(pw, "", dumpPackage);
5045 }
5046
5047 /**
5048 * There are three things that cmd can be:
5049 * - a flattened component name that matches an existing activity
5050 * - the cmd arg isn't the flattened component name of an existing activity:
5051 * dump all activity whose component contains the cmd as a substring
5052 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005053 * <p>
5054 * The caller should not hold lock when calling this method because it will wait for the
5055 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005056 *
5057 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5058 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5059 */
5060 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5061 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5062 ArrayList<ActivityRecord> activities;
5063
5064 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005065 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005066 dumpFocusedStackOnly);
5067 }
5068
5069 if (activities.size() <= 0) {
5070 return false;
5071 }
5072
5073 String[] newArgs = new String[args.length - opti];
5074 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5075
Louis Changcdec0802019-11-11 11:45:07 +08005076 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005077 boolean needSep = false;
5078 for (int i = activities.size() - 1; i >= 0; i--) {
5079 ActivityRecord r = activities.get(i);
5080 if (needSep) {
5081 pw.println();
5082 }
5083 needSep = true;
5084 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005085 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005086 if (lastTask != task) {
5087 lastTask = task;
5088 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005089 pw.print(" id="); pw.print(lastTask.mTaskId);
5090 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005091 if (dumpAll) {
5092 lastTask.dump(pw, " ");
5093 }
5094 }
5095 }
5096 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5097 }
5098 return true;
5099 }
5100
5101 /**
5102 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5103 * there is a thread associated with the activity.
5104 */
5105 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5106 final ActivityRecord r, String[] args, boolean dumpAll) {
5107 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005108 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005109 synchronized (mGlobalLock) {
5110 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5111 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5112 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005113 if (r.hasProcess()) {
5114 pw.println(r.app.getPid());
5115 appThread = r.app.getThread();
5116 } else {
5117 pw.println("(not running)");
5118 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005119 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005120 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005121 }
5122 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005123 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005124 // flush anything that is already in the PrintWriter since the thread is going
5125 // to write to the file descriptor directly
5126 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005127 try (TransferPipe tp = new TransferPipe()) {
5128 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5129 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005130 } catch (IOException e) {
5131 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5132 } catch (RemoteException e) {
5133 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5134 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005135 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005136 }
5137
sanryhuang498e77e2018-12-06 14:57:01 +08005138 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5139 boolean testPssMode) {
5140 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5141 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5142 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005143 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005144 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5145 st.toString());
5146 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005147 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5148 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5149 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005150 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5151 testPssMode);
5152 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005153 }
5154
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005155 int getCurrentUserId() {
5156 return mAmInternal.getCurrentUserId();
5157 }
5158
5159 private void enforceNotIsolatedCaller(String caller) {
5160 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5161 throw new SecurityException("Isolated process not allowed to call " + caller);
5162 }
5163 }
5164
Wale Ogunwalef6733932018-06-27 05:14:34 -07005165 public Configuration getConfiguration() {
5166 Configuration ci;
5167 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005168 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005169 ci.userSetLocale = false;
5170 }
5171 return ci;
5172 }
5173
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005174 /**
5175 * Current global configuration information. Contains general settings for the entire system,
5176 * also corresponds to the merged configuration of the default display.
5177 */
5178 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005179 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005180 // while initializing process record for system, see {@link
5181 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005182 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005183 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005184 }
5185
5186 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5187 boolean initLocale) {
5188 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5189 }
5190
5191 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5192 boolean initLocale, boolean deferResume) {
5193 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5194 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5195 UserHandle.USER_NULL, deferResume);
5196 }
5197
Wale Ogunwale59507092018-10-29 09:00:30 -07005198 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005199 final long origId = Binder.clearCallingIdentity();
5200 try {
5201 synchronized (mGlobalLock) {
5202 updateConfigurationLocked(values, null, false, true, userId,
5203 false /* deferResume */);
5204 }
5205 } finally {
5206 Binder.restoreCallingIdentity(origId);
5207 }
5208 }
5209
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005210 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5211 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5212 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5213 deferResume, null /* result */);
5214 }
5215
5216 /**
5217 * Do either or both things: (1) change the current configuration, and (2)
5218 * make sure the given activity is running with the (now) current
5219 * configuration. Returns true if the activity has been left running, or
5220 * false if <var>starting</var> is being destroyed to match the new
5221 * configuration.
5222 *
5223 * @param userId is only used when persistent parameter is set to true to persist configuration
5224 * for that particular user
5225 */
5226 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5227 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5228 ActivityTaskManagerService.UpdateConfigurationResult result) {
5229 int changes = 0;
5230 boolean kept = true;
5231
Riddle Hsua0022cd2019-09-09 21:12:41 +08005232 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005233 try {
5234 if (values != null) {
5235 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5236 deferResume);
5237 }
5238
5239 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5240 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005241 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005242 }
5243
5244 if (result != null) {
5245 result.changes = changes;
5246 result.activityRelaunched = !kept;
5247 }
5248 return kept;
5249 }
5250
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005251 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005252 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005253 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005254
Louis Chang677921f2019-12-06 16:44:24 +08005255 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005256 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005257
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005258 mTempConfig.setTo(getGlobalConfiguration());
5259 final int changes = mTempConfig.updateFrom(values);
5260 if (changes == 0) {
5261 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5262 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5263 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5264 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005265 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005266 return 0;
5267 }
5268
5269 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5270 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005271 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005272 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005273 values.colorMode,
5274 values.densityDpi,
5275 values.fontScale,
5276 values.hardKeyboardHidden,
5277 values.keyboard,
5278 values.keyboardHidden,
5279 values.mcc,
5280 values.mnc,
5281 values.navigation,
5282 values.navigationHidden,
5283 values.orientation,
5284 values.screenHeightDp,
5285 values.screenLayout,
5286 values.screenWidthDp,
5287 values.smallestScreenWidthDp,
5288 values.touchscreen,
5289 values.uiMode);
5290
5291
5292 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5293 final LocaleList locales = values.getLocales();
5294 int bestLocaleIndex = 0;
5295 if (locales.size() > 1) {
5296 if (mSupportedSystemLocales == null) {
5297 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5298 }
5299 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5300 }
5301 SystemProperties.set("persist.sys.locale",
5302 locales.get(bestLocaleIndex).toLanguageTag());
5303 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005304
5305 final Message m = PooledLambda.obtainMessage(
5306 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5307 locales.get(bestLocaleIndex));
5308 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005309 }
5310
Yunfan Chen75157d72018-07-27 14:47:21 +09005311 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005312
5313 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005314 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005315
5316 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5317 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005318 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005319
5320 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005321 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005322
5323 AttributeCache ac = AttributeCache.instance();
5324 if (ac != null) {
5325 ac.updateConfiguration(mTempConfig);
5326 }
5327
5328 // Make sure all resources in our process are updated right now, so that anyone who is going
5329 // to retrieve resource values after we return will be sure to get the new ones. This is
5330 // especially important during boot, where the first config change needs to guarantee all
5331 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005332 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005333
5334 // We need another copy of global config because we're scheduling some calls instead of
5335 // running them in place. We need to be sure that object we send will be handled unchanged.
5336 final Configuration configCopy = new Configuration(mTempConfig);
5337 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005338 final Message msg = PooledLambda.obtainMessage(
5339 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5340 this, userId, configCopy);
5341 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005342 }
5343
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005344 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5345 for (int i = pidMap.size() - 1; i >= 0; i--) {
5346 final int pid = pidMap.keyAt(i);
5347 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005348 if (DEBUG_CONFIGURATION) {
5349 Slog.v(TAG_CONFIGURATION, "Update process config of "
5350 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005351 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005352 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005353 }
5354
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005355 final Message msg = PooledLambda.obtainMessage(
5356 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5357 mAmInternal, changes, initLocale);
5358 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005359
5360 // Override configuration of the default display duplicates global config, so we need to
5361 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005362 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005363 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005364
5365 return changes;
5366 }
5367
Riddle Hsua0022cd2019-09-09 21:12:41 +08005368 /** @see WindowSurfacePlacer#deferLayout */
5369 void deferWindowLayout() {
5370 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5371 // Reset the reasons at the first entrance because we only care about the changes in the
5372 // deferred scope.
5373 mLayoutReasons = 0;
5374 }
5375
5376 mWindowManager.mWindowPlacerLocked.deferLayout();
5377 }
5378
5379 /** @see WindowSurfacePlacer#continueLayout */
5380 void continueWindowLayout() {
5381 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5382 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5383 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5384 }
5385 }
5386
5387 /**
5388 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5389 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5390 * defer count is gone.
5391 */
5392 void addWindowLayoutReasons(@LayoutReason int reasons) {
5393 mLayoutReasons |= reasons;
5394 }
5395
Wale Ogunwalef6733932018-06-27 05:14:34 -07005396 private void updateEventDispatchingLocked(boolean booted) {
5397 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5398 }
5399
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005400 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5401 final ContentResolver resolver = mContext.getContentResolver();
5402 Settings.System.putConfigurationForUser(resolver, config, userId);
5403 }
5404
5405 private void sendLocaleToMountDaemonMsg(Locale l) {
5406 try {
5407 IBinder service = ServiceManager.getService("mount");
5408 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5409 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5410 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5411 } catch (RemoteException e) {
5412 Log.e(TAG, "Error storing locale for decryption UI", e);
5413 }
5414 }
5415
Alison Cichowlas3e340502018-08-07 17:15:01 -04005416 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5417 mStartActivitySources.remove(permissionToken);
5418 mExpiredStartAsCallerTokens.add(permissionToken);
5419 }
5420
5421 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5422 mExpiredStartAsCallerTokens.remove(permissionToken);
5423 }
5424
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005425 boolean isActivityStartsLoggingEnabled() {
5426 return mAmInternal.isActivityStartsLoggingEnabled();
5427 }
5428
Michal Karpinski8596ded2018-11-14 14:43:48 +00005429 boolean isBackgroundActivityStartsEnabled() {
5430 return mAmInternal.isBackgroundActivityStartsEnabled();
5431 }
5432
Wale Ogunwalef6733932018-06-27 05:14:34 -07005433 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005434 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005435 mWindowManager.enableScreenAfterBoot();
5436
5437 synchronized (mGlobalLock) {
5438 updateEventDispatchingLocked(booted);
5439 }
5440 }
5441
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005442 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5443 if (r == null || !r.hasProcess()) {
5444 return KEY_DISPATCHING_TIMEOUT_MS;
5445 }
5446 return getInputDispatchingTimeoutLocked(r.app);
5447 }
5448
5449 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005450 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005451 }
5452
Wale Ogunwalef6733932018-06-27 05:14:34 -07005453 /**
5454 * Decide based on the configuration whether we should show the ANR,
5455 * crash, etc dialogs. The idea is that if there is no affordance to
5456 * press the on-screen buttons, or the user experience would be more
5457 * greatly impacted than the crash itself, we shouldn't show the dialog.
5458 *
5459 * A thought: SystemUI might also want to get told about this, the Power
5460 * dialog / global actions also might want different behaviors.
5461 */
5462 private void updateShouldShowDialogsLocked(Configuration config) {
5463 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5464 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5465 && config.navigation == Configuration.NAVIGATION_NONAV);
5466 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5467 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5468 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5469 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5470 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5471 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5472 HIDE_ERROR_DIALOGS, 0) != 0;
5473 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5474 }
5475
5476 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5477 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5478 FONT_SCALE, 1.0f, userId);
5479
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005480 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005481 if (getGlobalConfiguration().fontScale == scaleFactor) {
5482 return;
5483 }
5484
5485 final Configuration configuration
5486 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5487 configuration.fontScale = scaleFactor;
5488 updatePersistentConfiguration(configuration, userId);
5489 }
5490 }
5491
5492 // Actually is sleeping or shutting down or whatever else in the future
5493 // is an inactive state.
5494 boolean isSleepingOrShuttingDownLocked() {
5495 return isSleepingLocked() || mShuttingDown;
5496 }
5497
5498 boolean isSleepingLocked() {
5499 return mSleeping;
5500 }
5501
Riddle Hsu16567132018-08-16 21:37:47 +08005502 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005503 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005504 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005505 if (task.isActivityTypeStandard()) {
5506 if (mCurAppTimeTracker != r.appTimeTracker) {
5507 // We are switching app tracking. Complete the current one.
5508 if (mCurAppTimeTracker != null) {
5509 mCurAppTimeTracker.stop();
5510 mH.obtainMessage(
5511 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005512 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005513 mCurAppTimeTracker = null;
5514 }
5515 if (r.appTimeTracker != null) {
5516 mCurAppTimeTracker = r.appTimeTracker;
5517 startTimeTrackingFocusedActivityLocked();
5518 }
5519 } else {
5520 startTimeTrackingFocusedActivityLocked();
5521 }
5522 } else {
5523 r.appTimeTracker = null;
5524 }
5525 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5526 // TODO: Probably not, because we don't want to resume voice on switching
5527 // back to this activity
5528 if (task.voiceInteractor != null) {
5529 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5530 } else {
5531 finishRunningVoiceLocked();
5532
5533 if (mLastResumedActivity != null) {
5534 final IVoiceInteractionSession session;
5535
Louis Changcdec0802019-11-11 11:45:07 +08005536 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005537 if (lastResumedActivityTask != null
5538 && lastResumedActivityTask.voiceSession != null) {
5539 session = lastResumedActivityTask.voiceSession;
5540 } else {
5541 session = mLastResumedActivity.voiceSession;
5542 }
5543
5544 if (session != null) {
5545 // We had been in a voice interaction session, but now focused has
5546 // move to something different. Just finish the session, we can't
5547 // return to it and retain the proper state and synchronization with
5548 // the voice interaction service.
5549 finishVoiceTask(session);
5550 }
5551 }
5552 }
5553
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005554 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5555 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005556 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005557 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5558
Wale Ogunwalef6733932018-06-27 05:14:34 -07005559 updateResumedAppTrace(r);
5560 mLastResumedActivity = r;
5561
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005562 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005563
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005564 if (prevTask == null || task != prevTask) {
5565 if (prevTask != null) {
5566 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5567 }
5568 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5569 }
5570
Wale Ogunwalef6733932018-06-27 05:14:34 -07005571 applyUpdateLockStateLocked(r);
5572 applyUpdateVrModeLocked(r);
5573
Jeff Changd136e772019-11-05 20:33:52 +08005574 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005575 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005576 r == null ? "NULL" : r.shortComponentName,
5577 reason);
5578 }
5579
5580 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5581 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005582 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005583 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005584 updateSleepIfNeededLocked();
5585 return token;
5586 }
5587 }
5588
5589 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005590 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005591 final boolean wasSleeping = mSleeping;
5592 boolean updateOomAdj = false;
5593
5594 if (!shouldSleep) {
5595 // If wasSleeping is true, we need to wake up activity manager state from when
5596 // we started sleeping. In either case, we need to apply the sleep tokens, which
5597 // will wake up stacks or put them to sleep as appropriate.
5598 if (wasSleeping) {
5599 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005600 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5601 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005602 startTimeTrackingFocusedActivityLocked();
5603 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005604 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005605 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5606 }
Louis Chang149d5c82019-12-30 09:47:39 +08005607 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005608 if (wasSleeping) {
5609 updateOomAdj = true;
5610 }
5611 } else if (!mSleeping && shouldSleep) {
5612 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005613 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5614 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005615 if (mCurAppTimeTracker != null) {
5616 mCurAppTimeTracker.stop();
5617 }
5618 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005619 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005620 mStackSupervisor.goingToSleepLocked();
5621 updateResumedAppTrace(null /* resumed */);
5622 updateOomAdj = true;
5623 }
5624 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005625 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005626 }
5627 }
5628
5629 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005630 mH.removeCallbacks(mUpdateOomAdjRunnable);
5631 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005632 }
5633
Wale Ogunwale53783742018-09-16 10:21:51 -07005634 void updateCpuStats() {
5635 mH.post(mAmInternal::updateCpuStats);
5636 }
5637
Hui Yu03d12402018-12-06 18:00:37 -08005638 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5639 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005640 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5641 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005642 mH.sendMessage(m);
5643 }
5644
Hui Yu03d12402018-12-06 18:00:37 -08005645 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005646 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005647 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005648 if (task != null) {
5649 final ActivityRecord rootActivity = task.getRootActivity();
5650 if (rootActivity != null) {
5651 taskRoot = rootActivity.mActivityComponent;
5652 }
5653 }
5654
Hui Yu03d12402018-12-06 18:00:37 -08005655 final Message m = PooledLambda.obtainMessage(
5656 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005657 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005658 mH.sendMessage(m);
5659 }
5660
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005661 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5662 String hostingType) {
5663 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005664 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5665 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005666 + activity.processName);
5667 }
5668 // Post message to start process to avoid possible deadlock of calling into AMS with the
5669 // ATMS lock held.
5670 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5671 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5672 isTop, hostingType, activity.intent.getComponent());
5673 mH.sendMessage(m);
5674 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005675 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005676 }
5677 }
5678
Wale Ogunwale53783742018-09-16 10:21:51 -07005679 void setBooting(boolean booting) {
5680 mAmInternal.setBooting(booting);
5681 }
5682
5683 boolean isBooting() {
5684 return mAmInternal.isBooting();
5685 }
5686
5687 void setBooted(boolean booted) {
5688 mAmInternal.setBooted(booted);
5689 }
5690
5691 boolean isBooted() {
5692 return mAmInternal.isBooted();
5693 }
5694
5695 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5696 mH.post(() -> {
5697 if (finishBooting) {
5698 mAmInternal.finishBooting();
5699 }
5700 if (enableScreen) {
5701 mInternal.enableScreenAfterBoot(isBooted());
5702 }
5703 });
5704 }
5705
5706 void setHeavyWeightProcess(ActivityRecord root) {
5707 mHeavyWeightProcess = root.app;
5708 final Message m = PooledLambda.obtainMessage(
5709 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005710 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005711 mH.sendMessage(m);
5712 }
5713
5714 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5715 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5716 return;
5717 }
5718
5719 mHeavyWeightProcess = null;
5720 final Message m = PooledLambda.obtainMessage(
5721 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5722 proc.mUserId);
5723 mH.sendMessage(m);
5724 }
5725
5726 private void cancelHeavyWeightProcessNotification(int userId) {
5727 final INotificationManager inm = NotificationManager.getService();
5728 if (inm == null) {
5729 return;
5730 }
5731 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005732 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005733 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5734 } catch (RuntimeException e) {
5735 Slog.w(TAG, "Error canceling notification for service", e);
5736 } catch (RemoteException e) {
5737 }
5738
5739 }
5740
5741 private void postHeavyWeightProcessNotification(
5742 WindowProcessController proc, Intent intent, int userId) {
5743 if (proc == null) {
5744 return;
5745 }
5746
5747 final INotificationManager inm = NotificationManager.getService();
5748 if (inm == null) {
5749 return;
5750 }
5751
5752 try {
5753 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5754 String text = mContext.getString(R.string.heavy_weight_notification,
5755 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5756 Notification notification =
5757 new Notification.Builder(context,
5758 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5759 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5760 .setWhen(0)
5761 .setOngoing(true)
5762 .setTicker(text)
5763 .setColor(mContext.getColor(
5764 com.android.internal.R.color.system_notification_accent_color))
5765 .setContentTitle(text)
5766 .setContentText(
5767 mContext.getText(R.string.heavy_weight_notification_detail))
5768 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5769 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5770 new UserHandle(userId)))
5771 .build();
5772 try {
5773 inm.enqueueNotificationWithTag("android", "android", null,
5774 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5775 } catch (RuntimeException e) {
5776 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5777 } catch (RemoteException e) {
5778 }
5779 } catch (PackageManager.NameNotFoundException e) {
5780 Slog.w(TAG, "Unable to create context for heavy notification", e);
5781 }
5782
5783 }
5784
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00005785 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5786 IBinder token, String resultWho, int requestCode, Intent[] intents,
5787 String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005788
5789 ActivityRecord activity = null;
5790 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5791 activity = ActivityRecord.isInStackLocked(token);
5792 if (activity == null) {
5793 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5794 return null;
5795 }
5796 if (activity.finishing) {
5797 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5798 return null;
5799 }
5800 }
5801
5802 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00005803 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5804 bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005805 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5806 if (noCreate) {
5807 return rec;
5808 }
5809 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5810 if (activity.pendingResults == null) {
5811 activity.pendingResults = new HashSet<>();
5812 }
5813 activity.pendingResults.add(rec.ref);
5814 }
5815 return rec;
5816 }
5817
Andrii Kulian52d255c2018-07-13 11:32:19 -07005818 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005819 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005820 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005821 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5822 mCurAppTimeTracker.start(resumedActivity.packageName);
5823 }
5824 }
5825
5826 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5827 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005828 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005829 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5830 }
5831 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005832 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005833 constructResumedTraceName(resumed.packageName), 0);
5834 }
5835 mTracedResumedActivity = resumed;
5836 }
5837
5838 private String constructResumedTraceName(String packageName) {
5839 return "focused app: " + packageName;
5840 }
5841
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005842 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005843 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005844 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005845 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005846 // mainStack is null during startup.
5847 if (mainStack != null) {
5848 if (changes != 0 && starting == null) {
5849 // If the configuration changed, and the caller is not already
5850 // in the process of starting an activity, then find the top
5851 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005852 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005853 }
5854
5855 if (starting != null) {
5856 kept = starting.ensureActivityConfiguration(changes,
5857 false /* preserveWindow */);
5858 // And we need to make sure at this point that all other activities
5859 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005860 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005861 !PRESERVE_WINDOWS);
5862 }
5863 }
5864
5865 return kept;
5866 }
5867
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005868 void scheduleAppGcsLocked() {
5869 mH.post(() -> mAmInternal.scheduleAppGcs());
5870 }
5871
Wale Ogunwale53783742018-09-16 10:21:51 -07005872 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5873 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5874 }
5875
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005876 /**
5877 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5878 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5879 * on demand.
5880 */
5881 IPackageManager getPackageManager() {
5882 return AppGlobals.getPackageManager();
5883 }
5884
5885 PackageManagerInternal getPackageManagerInternalLocked() {
5886 if (mPmInternal == null) {
5887 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5888 }
5889 return mPmInternal;
5890 }
5891
Hai Zhangf4da9be2019-05-01 13:46:06 +08005892 PermissionPolicyInternal getPermissionPolicyInternal() {
5893 if (mPermissionPolicyInternal == null) {
5894 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5895 }
5896 return mPermissionPolicyInternal;
5897 }
5898
Wale Ogunwale008163e2018-07-23 23:11:08 -07005899 AppWarnings getAppWarningsLocked() {
5900 return mAppWarnings;
5901 }
5902
Wale Ogunwale214f3482018-10-04 11:00:47 -07005903 Intent getHomeIntent() {
5904 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5905 intent.setComponent(mTopComponent);
5906 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5907 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5908 intent.addCategory(Intent.CATEGORY_HOME);
5909 }
5910 return intent;
5911 }
5912
Chilun2ef71f72018-11-16 17:57:15 +08005913 /**
5914 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5915 * activities.
5916 *
5917 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5918 * component defined in config_secondaryHomeComponent.
5919 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5920 */
5921 Intent getSecondaryHomeIntent(String preferredPackage) {
5922 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005923 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5924 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5925 if (preferredPackage == null || useSystemProvidedLauncher) {
5926 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005927 final String secondaryHomeComponent = mContext.getResources().getString(
5928 com.android.internal.R.string.config_secondaryHomeComponent);
5929 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5930 } else {
5931 intent.setPackage(preferredPackage);
5932 }
5933 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5934 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5935 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5936 }
5937 return intent;
5938 }
5939
Wale Ogunwale214f3482018-10-04 11:00:47 -07005940 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5941 if (info == null) return null;
5942 ApplicationInfo newInfo = new ApplicationInfo(info);
5943 newInfo.initForUser(userId);
5944 return newInfo;
5945 }
5946
Wale Ogunwale9c103022018-10-18 07:44:54 -07005947 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005948 if (uid == SYSTEM_UID) {
5949 // The system gets to run in any process. If there are multiple processes with the same
5950 // uid, just pick the first (this should never happen).
5951 final SparseArray<WindowProcessController> procs =
5952 mProcessNames.getMap().get(processName);
5953 if (procs == null) return null;
5954 final int procCount = procs.size();
5955 for (int i = 0; i < procCount; i++) {
5956 final int procUid = procs.keyAt(i);
5957 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5958 // Don't use an app process or different user process for system component.
5959 continue;
5960 }
5961 return procs.valueAt(i);
5962 }
5963 }
5964
5965 return mProcessNames.get(processName, uid);
5966 }
5967
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005968 WindowProcessController getProcessController(IApplicationThread thread) {
5969 if (thread == null) {
5970 return null;
5971 }
5972
5973 final IBinder threadBinder = thread.asBinder();
5974 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5975 for (int i = pmap.size()-1; i >= 0; i--) {
5976 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5977 for (int j = procs.size() - 1; j >= 0; j--) {
5978 final WindowProcessController proc = procs.valueAt(j);
5979 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5980 return proc;
5981 }
5982 }
5983 }
5984
5985 return null;
5986 }
5987
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005988 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005989 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005990 if (proc == null) return null;
5991 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5992 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005993 }
5994 return null;
5995 }
5996
Riddle Hsua0536432019-02-16 00:38:59 +08005997 int getUidState(int uid) {
5998 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005999 }
6000
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006001 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01006002 // A uid is considered to be foreground if it has a visible non-toast window.
6003 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006004 }
6005
Ricky Wai96f5c352019-04-10 18:40:17 +01006006 boolean isDeviceOwner(int uid) {
6007 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006008 }
6009
Ricky Wai96f5c352019-04-10 18:40:17 +01006010 void setDeviceOwnerUid(int uid) {
6011 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006012 }
6013
Wale Ogunwale9de19442018-10-18 19:05:03 -07006014 /**
6015 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6016 * the whitelist
6017 */
6018 String getPendingTempWhitelistTagForUidLocked(int uid) {
6019 return mPendingTempWhitelist.get(uid);
6020 }
6021
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006022 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6023 if (true || Build.IS_USER) {
6024 return;
6025 }
6026
6027 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6028 StrictMode.allowThreadDiskWrites();
6029 try {
6030 File tracesDir = new File("/data/anr");
6031 File tracesFile = null;
6032 try {
6033 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6034
6035 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006036 String timeString =
6037 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6038 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006039 sb.append(": ");
6040 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6041 sb.append(" since ");
6042 sb.append(msg);
6043 FileOutputStream fos = new FileOutputStream(tracesFile);
6044 fos.write(sb.toString().getBytes());
6045 if (app == null) {
6046 fos.write("\n*** No application process!".getBytes());
6047 }
6048 fos.close();
6049 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6050 } catch (IOException e) {
6051 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6052 return;
6053 }
6054
6055 if (app != null && app.getPid() > 0) {
6056 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6057 firstPids.add(app.getPid());
6058 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6059 }
6060
6061 File lastTracesFile = null;
6062 File curTracesFile = null;
6063 for (int i=9; i>=0; i--) {
6064 String name = String.format(Locale.US, "slow%02d.txt", i);
6065 curTracesFile = new File(tracesDir, name);
6066 if (curTracesFile.exists()) {
6067 if (lastTracesFile != null) {
6068 curTracesFile.renameTo(lastTracesFile);
6069 } else {
6070 curTracesFile.delete();
6071 }
6072 }
6073 lastTracesFile = curTracesFile;
6074 }
6075 tracesFile.renameTo(curTracesFile);
6076 } finally {
6077 StrictMode.setThreadPolicy(oldPolicy);
6078 }
6079 }
6080
Michal Karpinskida34cd42019-04-02 19:46:52 +01006081 boolean isAssociatedCompanionApp(int userId, int uid) {
6082 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6083 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006084 return false;
6085 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006086 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006087 }
6088
Issei Suzuki734bc942019-06-05 13:59:52 +02006089 void notifySingleTaskDisplayEmpty(int displayId) {
6090 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6091 }
6092
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006093 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006094 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006095
6096
Wale Ogunwale98875612018-10-12 07:53:02 -07006097 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6098 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006099
Riddle Hsud93a6c42018-11-29 21:50:06 +08006100 H(Looper looper) {
6101 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006102 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006103
6104 @Override
6105 public void handleMessage(Message msg) {
6106 switch (msg.what) {
6107 case REPORT_TIME_TRACKER_MSG: {
6108 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6109 tracker.deliverResult(mContext);
6110 } break;
6111 }
6112 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006113 }
6114
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006115 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006116 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006117
6118 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006119 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006120 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006121
6122 @Override
6123 public void handleMessage(Message msg) {
6124 switch (msg.what) {
6125 case DISMISS_DIALOG_UI_MSG: {
6126 final Dialog d = (Dialog) msg.obj;
6127 d.dismiss();
6128 break;
6129 }
6130 }
6131 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006132 }
6133
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006134 final class LocalService extends ActivityTaskManagerInternal {
6135 @Override
6136 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006137 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006138 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006139 }
6140
6141 @Override
6142 public ComponentName getHomeActivityForUser(int userId) {
6143 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006144 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006145 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006146 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006147 }
6148 }
6149
6150 @Override
6151 public void onLocalVoiceInteractionStarted(IBinder activity,
6152 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6153 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006154 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006155 }
6156 }
6157
6158 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006159 public void notifySingleTaskDisplayDrawn(int displayId) {
6160 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6161 }
6162
6163 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006164 public void notifyAppTransitionFinished() {
6165 synchronized (mGlobalLock) {
6166 mStackSupervisor.notifyAppTransitionDone();
6167 }
6168 }
6169
6170 @Override
6171 public void notifyAppTransitionCancelled() {
6172 synchronized (mGlobalLock) {
6173 mStackSupervisor.notifyAppTransitionDone();
6174 }
6175 }
6176
6177 @Override
6178 public List<IBinder> getTopVisibleActivities() {
6179 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006180 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006181 }
6182 }
6183
6184 @Override
6185 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6186 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006187 mRootWindowContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006188 }
6189 }
6190
6191 @Override
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00006192 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6193 Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006194 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006195 final String[] resolvedTypes = new String[intents.length];
6196
6197 // UID of the package on user userId.
6198 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6199 // packageUid may not be initialized.
6200 int packageUid = 0;
6201 final long ident = Binder.clearCallingIdentity();
6202
6203 try {
6204 for (int i = 0; i < intents.length; i++) {
6205 resolvedTypes[i] =
6206 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6207 }
6208
6209 packageUid = AppGlobals.getPackageManager().getPackageUid(
6210 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6211 } catch (RemoteException e) {
6212 // Shouldn't happen.
6213 } finally {
6214 Binder.restoreCallingIdentity(ident);
6215 }
6216
Riddle Hsu591bf612019-02-14 17:55:31 +08006217 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00006218 packageUid, packageName,
Riddle Hsu591bf612019-02-14 17:55:31 +08006219 intents, resolvedTypes, null /* resultTo */,
6220 SafeActivityOptions.fromBundle(bOptions), userId,
6221 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6222 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006223 }
6224
6225 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006226 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00006227 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6228 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6229 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006230 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006231 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006232 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006233 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00006234 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6235 userId, validateIncomingUser, originatingPendingIntent,
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006236 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006237 }
6238 }
6239
6240 @Override
6241 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00006242 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6243 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6244 int userId, Task inTask, String reason, boolean validateIncomingUser,
6245 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006246 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006247 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006248 synchronized (mGlobalLock) {
6249 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00006250 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6251 requestCode, startFlags, options, userId, inTask, reason,
6252 validateIncomingUser, originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006253 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006254 }
6255 }
6256
6257 @Override
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00006258 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6259 Intent intent, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006260 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00006261 caller, callerPacakge, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006262 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6263 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6264 false /*validateIncomingUser*/);
6265 }
6266
6267 @Override
lumark588a3e82018-07-20 18:53:54 +08006268 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006269 synchronized (mGlobalLock) {
6270
6271 // We might change the visibilities here, so prepare an empty app transition which
6272 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006273 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006274 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006275 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006276 return;
6277 }
Louis Chang677921f2019-12-06 16:44:24 +08006278 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006279 final boolean wasTransitionSet =
6280 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006281 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006282 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006283 }
Louis Chang149d5c82019-12-30 09:47:39 +08006284 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006285
6286 // If there was a transition set already we don't want to interfere with it as we
6287 // might be starting it too early.
6288 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006289 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006290 }
6291 }
6292 if (callback != null) {
6293 callback.run();
6294 }
6295 }
6296
6297 @Override
6298 public void notifyKeyguardTrustedChanged() {
6299 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006300 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006301 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006302 }
6303 }
6304 }
6305
6306 /**
6307 * Called after virtual display Id is updated by
6308 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6309 * {@param vrVr2dDisplayId}.
6310 */
6311 @Override
6312 public void setVr2dDisplayId(int vr2dDisplayId) {
6313 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6314 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006315 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006316 }
6317 }
6318
6319 @Override
6320 public void setFocusedActivity(IBinder token) {
6321 synchronized (mGlobalLock) {
6322 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6323 if (r == null) {
6324 throw new IllegalArgumentException(
6325 "setFocusedActivity: No activity record matching token=" + token);
6326 }
Louis Chang19443452018-10-09 12:10:21 +08006327 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006328 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006329 }
6330 }
6331 }
6332
6333 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006334 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006335 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006336 }
6337
6338 @Override
6339 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006340 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006341 }
6342
6343 @Override
6344 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006345 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006346 }
6347
6348 @Override
6349 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6350 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6351 }
6352
6353 @Override
6354 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006355 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006356 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006357
6358 @Override
6359 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6360 synchronized (mGlobalLock) {
6361 mActiveVoiceInteractionServiceComponent = component;
6362 }
6363 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006364
6365 @Override
6366 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6367 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6368 return;
6369 }
6370 synchronized (mGlobalLock) {
6371 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6372 if (types == null) {
6373 if (uid < 0) {
6374 return;
6375 }
6376 types = new ArrayMap<>();
6377 mAllowAppSwitchUids.put(userId, types);
6378 }
6379 if (uid < 0) {
6380 types.remove(type);
6381 } else {
6382 types.put(type, uid);
6383 }
6384 }
6385 }
6386
6387 @Override
6388 public void onUserStopped(int userId) {
6389 synchronized (mGlobalLock) {
6390 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6391 mAllowAppSwitchUids.remove(userId);
6392 }
6393 }
6394
6395 @Override
6396 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6397 synchronized (mGlobalLock) {
6398 return ActivityTaskManagerService.this.isGetTasksAllowed(
6399 caller, callingPid, callingUid);
6400 }
6401 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006402
Riddle Hsua0536432019-02-16 00:38:59 +08006403 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006404 @Override
6405 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006406 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006407 mProcessNames.put(proc.mName, proc.mUid, proc);
6408 }
6409 }
6410
Riddle Hsua0536432019-02-16 00:38:59 +08006411 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006412 @Override
6413 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006414 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006415 mProcessNames.remove(name, uid);
6416 }
6417 }
6418
Riddle Hsua0536432019-02-16 00:38:59 +08006419 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006420 @Override
6421 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006422 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006423 if (proc == mHomeProcess) {
6424 mHomeProcess = null;
6425 }
6426 if (proc == mPreviousProcess) {
6427 mPreviousProcess = null;
6428 }
6429 }
6430 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006431
Riddle Hsua0536432019-02-16 00:38:59 +08006432 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006433 @Override
6434 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006435 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006436 return mTopProcessState;
6437 }
6438 }
6439
Riddle Hsua0536432019-02-16 00:38:59 +08006440 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006441 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006442 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006443 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006444 return proc == mHeavyWeightProcess;
6445 }
6446 }
6447
Riddle Hsua0536432019-02-16 00:38:59 +08006448 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006449 @Override
6450 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006451 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006452 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6453 }
6454 }
6455
6456 @Override
6457 public void finishHeavyWeightApp() {
6458 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006459 if (mHeavyWeightProcess != null) {
6460 mHeavyWeightProcess.finishActivities();
6461 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006462 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6463 mHeavyWeightProcess);
6464 }
6465 }
6466
Riddle Hsua0536432019-02-16 00:38:59 +08006467 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006468 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006469 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006470 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006471 return isSleepingLocked();
6472 }
6473 }
6474
6475 @Override
6476 public boolean isShuttingDown() {
6477 synchronized (mGlobalLock) {
6478 return mShuttingDown;
6479 }
6480 }
6481
6482 @Override
6483 public boolean shuttingDown(boolean booted, int timeout) {
6484 synchronized (mGlobalLock) {
6485 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006486 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006487 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006488 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006489 return mStackSupervisor.shutdownLocked(timeout);
6490 }
6491 }
6492
6493 @Override
6494 public void enableScreenAfterBoot(boolean booted) {
6495 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006496 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006497 mWindowManager.enableScreenAfterBoot();
6498 updateEventDispatchingLocked(booted);
6499 }
6500 }
6501
6502 @Override
6503 public boolean showStrictModeViolationDialog() {
6504 synchronized (mGlobalLock) {
6505 return mShowDialogs && !mSleeping && !mShuttingDown;
6506 }
6507 }
6508
6509 @Override
6510 public void showSystemReadyErrorDialogsIfNeeded() {
6511 synchronized (mGlobalLock) {
6512 try {
6513 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6514 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6515 + " data partition or your device will be unstable.");
6516 mUiHandler.post(() -> {
6517 if (mShowDialogs) {
6518 AlertDialog d = new BaseErrorDialog(mUiContext);
6519 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6520 d.setCancelable(false);
6521 d.setTitle(mUiContext.getText(R.string.android_system_label));
6522 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6523 d.setButton(DialogInterface.BUTTON_POSITIVE,
6524 mUiContext.getText(R.string.ok),
6525 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6526 d.show();
6527 }
6528 });
6529 }
6530 } catch (RemoteException e) {
6531 }
6532
6533 if (!Build.isBuildConsistent()) {
6534 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6535 mUiHandler.post(() -> {
6536 if (mShowDialogs) {
6537 AlertDialog d = new BaseErrorDialog(mUiContext);
6538 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6539 d.setCancelable(false);
6540 d.setTitle(mUiContext.getText(R.string.android_system_label));
6541 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6542 d.setButton(DialogInterface.BUTTON_POSITIVE,
6543 mUiContext.getText(R.string.ok),
6544 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6545 d.show();
6546 }
6547 });
6548 }
6549 }
6550 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006551
6552 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006553 public void onProcessMapped(int pid, WindowProcessController proc) {
6554 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006555 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006556 }
6557 }
6558
6559 @Override
6560 public void onProcessUnMapped(int pid) {
6561 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006562 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006563 }
6564 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006565
6566 @Override
6567 public void onPackageDataCleared(String name) {
6568 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006569 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006570 mAppWarnings.onPackageDataCleared(name);
6571 }
6572 }
6573
6574 @Override
6575 public void onPackageUninstalled(String name) {
6576 synchronized (mGlobalLock) {
6577 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006578 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006579 }
6580 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006581
6582 @Override
6583 public void onPackageAdded(String name, boolean replacing) {
6584 synchronized (mGlobalLock) {
6585 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6586 }
6587 }
6588
6589 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006590 public void onPackageReplaced(ApplicationInfo aInfo) {
6591 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006592 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006593 }
6594 }
6595
6596 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006597 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6598 synchronized (mGlobalLock) {
6599 return compatibilityInfoForPackageLocked(ai);
6600 }
6601 }
6602
Yunfan Chen75157d72018-07-27 14:47:21 +09006603 /**
6604 * Set the corresponding display information for the process global configuration. To be
6605 * called when we need to show IME on a different display.
6606 *
6607 * @param pid The process id associated with the IME window.
6608 * @param displayId The ID of the display showing the IME.
6609 */
6610 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006611 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006612 // Don't update process-level configuration for Multi-Client IME process since other
6613 // IMEs on other displays will also receive this configuration change due to IME
6614 // services use the same application config/context.
6615 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006616
Yunfan Chen75157d72018-07-27 14:47:21 +09006617 if (pid == MY_PID || pid < 0) {
6618 if (DEBUG_CONFIGURATION) {
6619 Slog.w(TAG,
6620 "Trying to update display configuration for system/invalid process.");
6621 }
6622 return;
6623 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006624 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006625 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006626 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006627 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006628 // Call might come when display is not yet added or has been removed.
6629 if (DEBUG_CONFIGURATION) {
6630 Slog.w(TAG, "Trying to update display configuration for non-existing "
6631 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006632 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006633 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006634 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006635 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006636 if (process == null) {
6637 if (DEBUG_CONFIGURATION) {
6638 Slog.w(TAG, "Trying to update display configuration for invalid "
6639 + "process, pid=" + pid);
6640 }
6641 return;
6642 }
lumarkddc77fb2019-06-27 22:22:23 +08006643 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006644 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006645 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006646 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006647
6648 @Override
6649 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006650 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006651 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006652 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006653 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006654 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006655 }
6656 }
6657 }
6658
6659 @Override
6660 public void clearPendingResultForActivity(IBinder activityToken,
6661 WeakReference<PendingIntentRecord> pir) {
6662 synchronized (mGlobalLock) {
6663 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6664 if (r != null && r.pendingResults != null) {
6665 r.pendingResults.remove(pir);
6666 }
6667 }
6668 }
6669
6670 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006671 public ActivityTokens getTopActivityForTask(int taskId) {
6672 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006673 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006674 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006675 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6676 + " Requested task not found");
6677 return null;
6678 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006679 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006680 if (activity == null) {
6681 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6682 + " Requested activity not found");
6683 return null;
6684 }
6685 if (!activity.attachedToProcess()) {
6686 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6687 + activity);
6688 return null;
6689 }
6690 return new ActivityTokens(activity.appToken, activity.assistToken,
6691 activity.app.getThread());
6692 }
6693 }
6694
6695 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006696 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00006697 int callingUid, int userId, IBinder token, String resultWho,
6698 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6699 Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006700 synchronized (mGlobalLock) {
Philip P. Moltmanne7421e92020-02-10 16:14:12 +00006701 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6702 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006703 }
6704 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006705
6706 @Override
6707 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6708 synchronized (mGlobalLock) {
6709 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6710 if (r == null) {
6711 return null;
6712 }
6713 if (r.mServiceConnectionsHolder == null) {
6714 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6715 ActivityTaskManagerService.this, r);
6716 }
6717
6718 return r.mServiceConnectionsHolder;
6719 }
6720 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006721
6722 @Override
6723 public Intent getHomeIntent() {
6724 synchronized (mGlobalLock) {
6725 return ActivityTaskManagerService.this.getHomeIntent();
6726 }
6727 }
6728
6729 @Override
6730 public boolean startHomeActivity(int userId, String reason) {
6731 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006732 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006733 }
6734 }
6735
6736 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006737 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006738 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006739 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006740 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006741 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006742 }
Chilun8b1f1be2019-03-13 17:14:36 +08006743 }
6744
6745 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006746 public boolean startHomeOnAllDisplays(int userId, String reason) {
6747 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006748 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006749 }
6750 }
6751
Riddle Hsua0536432019-02-16 00:38:59 +08006752 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006753 @Override
6754 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006755 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006756 if (mFactoryTest == FACTORY_TEST_OFF) {
6757 return false;
6758 }
6759 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6760 && wpc.mName.equals(mTopComponent.getPackageName())) {
6761 return true;
6762 }
6763 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6764 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6765 }
6766 }
6767
6768 @Override
6769 public void updateTopComponentForFactoryTest() {
6770 synchronized (mGlobalLock) {
6771 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6772 return;
6773 }
6774 final ResolveInfo ri = mContext.getPackageManager()
6775 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6776 final CharSequence errorMsg;
6777 if (ri != null) {
6778 final ActivityInfo ai = ri.activityInfo;
6779 final ApplicationInfo app = ai.applicationInfo;
6780 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6781 mTopAction = Intent.ACTION_FACTORY_TEST;
6782 mTopData = null;
6783 mTopComponent = new ComponentName(app.packageName, ai.name);
6784 errorMsg = null;
6785 } else {
6786 errorMsg = mContext.getResources().getText(
6787 com.android.internal.R.string.factorytest_not_system);
6788 }
6789 } else {
6790 errorMsg = mContext.getResources().getText(
6791 com.android.internal.R.string.factorytest_no_action);
6792 }
6793 if (errorMsg == null) {
6794 return;
6795 }
6796
6797 mTopAction = null;
6798 mTopData = null;
6799 mTopComponent = null;
6800 mUiHandler.post(() -> {
6801 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6802 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006803 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006804 });
6805 }
6806 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006807
Riddle Hsua0536432019-02-16 00:38:59 +08006808 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006809 @Override
6810 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6811 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006812 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006813 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006814 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006815
6816 wpc.clearRecentTasks();
6817 wpc.clearActivities();
6818
6819 if (wpc.isInstrumenting()) {
6820 finishInstrumentationCallback.run();
6821 }
6822
Jorim Jaggid0752812018-10-16 16:07:20 +02006823 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006824 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006825 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006826 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006827 // If there was nothing to resume, and we are not already restarting
6828 // this process, but there is a visible activity that is hosted by the
6829 // process...then make sure all visible activities are running, taking
6830 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006831 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006832 !PRESERVE_WINDOWS);
6833 }
6834 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006835 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006836 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006837 }
6838 }
6839 }
6840
6841 @Override
6842 public void closeSystemDialogs(String reason) {
6843 enforceNotIsolatedCaller("closeSystemDialogs");
6844
6845 final int pid = Binder.getCallingPid();
6846 final int uid = Binder.getCallingUid();
6847 final long origId = Binder.clearCallingIdentity();
6848 try {
6849 synchronized (mGlobalLock) {
6850 // Only allow this from foreground processes, so that background
6851 // applications can't abuse it to prevent system UI from being shown.
6852 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006853 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006854 if (!proc.isPerceptible()) {
6855 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6856 + " from background process " + proc);
6857 return;
6858 }
6859 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006860 mWindowManager.closeSystemDialogs(reason);
6861
Louis Chang149d5c82019-12-30 09:47:39 +08006862 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006863 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006864 // Call into AM outside the synchronized block.
6865 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006866 } finally {
6867 Binder.restoreCallingIdentity(origId);
6868 }
6869 }
6870
6871 @Override
6872 public void cleanupDisabledPackageComponents(
6873 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6874 synchronized (mGlobalLock) {
6875 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006876 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006877 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006878 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006879 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006880 }
6881
6882 // Clean-up disabled tasks
6883 getRecentTasks().cleanupDisabledPackageTasksLocked(
6884 packageName, disabledClasses, userId);
6885 }
6886 }
6887
6888 @Override
6889 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6890 int userId) {
6891 synchronized (mGlobalLock) {
6892
6893 boolean didSomething =
6894 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006895 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006896 null, doit, evenPersistent, userId);
6897 return didSomething;
6898 }
6899 }
6900
6901 @Override
6902 public void resumeTopActivities(boolean scheduleIdle) {
6903 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006904 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006905 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006906 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006907 }
6908 }
6909 }
6910
Riddle Hsua0536432019-02-16 00:38:59 +08006911 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006912 @Override
6913 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006914 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006915 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6916 }
6917 }
6918
Riddle Hsua0536432019-02-16 00:38:59 +08006919 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006920 @Override
6921 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006922 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006923 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6924 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6925 }
6926 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006927 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006928 } finally {
6929 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6930 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006931 }
6932 }
6933
6934 @Override
6935 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6936 try {
6937 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6938 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6939 }
6940 } catch (RemoteException ex) {
6941 throw new SecurityException("Fail to check is caller a privileged app", ex);
6942 }
6943
6944 synchronized (mGlobalLock) {
6945 final long ident = Binder.clearCallingIdentity();
6946 try {
6947 if (mAmInternal.shouldConfirmCredentials(userId)) {
6948 if (mKeyguardController.isKeyguardLocked()) {
6949 // Showing launcher to avoid user entering credential twice.
6950 startHomeActivity(currentUserId, "notifyLockedProfile");
6951 }
Louis Chang149d5c82019-12-30 09:47:39 +08006952 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006953 }
6954 } finally {
6955 Binder.restoreCallingIdentity(ident);
6956 }
6957 }
6958 }
6959
6960 @Override
6961 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6962 mAmInternal.enforceCallingPermission(
6963 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6964
6965 synchronized (mGlobalLock) {
6966 final long ident = Binder.clearCallingIdentity();
6967 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006968 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6969 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006970 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006971 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6972 UserHandle.CURRENT);
6973 } finally {
6974 Binder.restoreCallingIdentity(ident);
6975 }
6976 }
6977 }
6978
6979 @Override
6980 public void writeActivitiesToProto(ProtoOutputStream proto) {
6981 synchronized (mGlobalLock) {
6982 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006983 mRootWindowContainer.dumpDebug(
6984 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006985 }
6986 }
6987
6988 @Override
6989 public void saveANRState(String reason) {
6990 synchronized (mGlobalLock) {
6991 final StringWriter sw = new StringWriter();
6992 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6993 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6994 if (reason != null) {
6995 pw.println(" Reason: " + reason);
6996 }
6997 pw.println();
6998 getActivityStartController().dump(pw, " ", null);
6999 pw.println();
7000 pw.println("-------------------------------------------------------------------------------");
7001 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7002 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7003 "" /* header */);
7004 pw.println();
7005 pw.close();
7006
7007 mLastANRState = sw.toString();
7008 }
7009 }
7010
7011 @Override
7012 public void clearSavedANRState() {
7013 synchronized (mGlobalLock) {
7014 mLastANRState = null;
7015 }
7016 }
7017
7018 @Override
7019 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7020 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7021 synchronized (mGlobalLock) {
7022 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7023 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7024 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7025 dumpLastANRLocked(pw);
7026 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7027 dumpLastANRTracesLocked(pw);
7028 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7029 dumpActivityStarterLocked(pw, dumpPackage);
7030 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7031 dumpActivityContainersLocked(pw);
7032 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7033 if (getRecentTasks() != null) {
7034 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7035 }
7036 }
7037 }
7038 }
7039
7040 @Override
7041 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7042 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7043 int wakefulness) {
7044 synchronized (mGlobalLock) {
7045 if (mHomeProcess != null && (dumpPackage == null
7046 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7047 if (needSep) {
7048 pw.println();
7049 needSep = false;
7050 }
7051 pw.println(" mHomeProcess: " + mHomeProcess);
7052 }
7053 if (mPreviousProcess != null && (dumpPackage == null
7054 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7055 if (needSep) {
7056 pw.println();
7057 needSep = false;
7058 }
7059 pw.println(" mPreviousProcess: " + mPreviousProcess);
7060 }
7061 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7062 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7063 StringBuilder sb = new StringBuilder(128);
7064 sb.append(" mPreviousProcessVisibleTime: ");
7065 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7066 pw.println(sb);
7067 }
7068 if (mHeavyWeightProcess != null && (dumpPackage == null
7069 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7070 if (needSep) {
7071 pw.println();
7072 needSep = false;
7073 }
7074 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7075 }
7076 if (dumpPackage == null) {
7077 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007078 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007079 }
7080 if (dumpAll) {
7081 if (dumpPackage == null) {
7082 pw.println(" mConfigWillChange: "
7083 + getTopDisplayFocusedStack().mConfigWillChange);
7084 }
7085 if (mCompatModePackages.getPackages().size() > 0) {
7086 boolean printed = false;
7087 for (Map.Entry<String, Integer> entry
7088 : mCompatModePackages.getPackages().entrySet()) {
7089 String pkg = entry.getKey();
7090 int mode = entry.getValue();
7091 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7092 continue;
7093 }
7094 if (!printed) {
7095 pw.println(" mScreenCompatPackages:");
7096 printed = true;
7097 }
7098 pw.println(" " + pkg + ": " + mode);
7099 }
7100 }
7101 }
7102
7103 if (dumpPackage == null) {
7104 pw.println(" mWakefulness="
7105 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007106 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007107 if (mRunningVoice != null) {
7108 pw.println(" mRunningVoice=" + mRunningVoice);
7109 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7110 }
7111 pw.println(" mSleeping=" + mSleeping);
7112 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7113 pw.println(" mVrController=" + mVrController);
7114 }
7115 if (mCurAppTimeTracker != null) {
7116 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7117 }
7118 if (mAllowAppSwitchUids.size() > 0) {
7119 boolean printed = false;
7120 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7121 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7122 for (int j = 0; j < types.size(); j++) {
7123 if (dumpPackage == null ||
7124 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7125 if (needSep) {
7126 pw.println();
7127 needSep = false;
7128 }
7129 if (!printed) {
7130 pw.println(" mAllowAppSwitchUids:");
7131 printed = true;
7132 }
7133 pw.print(" User ");
7134 pw.print(mAllowAppSwitchUids.keyAt(i));
7135 pw.print(": Type ");
7136 pw.print(types.keyAt(j));
7137 pw.print(" = ");
7138 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7139 pw.println();
7140 }
7141 }
7142 }
7143 }
7144 if (dumpPackage == null) {
7145 if (mController != null) {
7146 pw.println(" mController=" + mController
7147 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7148 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007149 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7150 pw.println(" mLaunchingActivityWakeLock="
7151 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007152 }
7153
7154 return needSep;
7155 }
7156 }
7157
7158 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007159 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7160 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007161 synchronized (mGlobalLock) {
7162 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007163 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007164 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007165 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7166 if (mRunningVoice != null) {
7167 final long vrToken = proto.start(
7168 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7169 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7170 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007171 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007172 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7173 proto.end(vrToken);
7174 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007175 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007176 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007177 if (mController != null) {
7178 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007179 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7180 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007181 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7182 proto.end(token);
7183 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007184 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7185 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007186 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007187 }
7188
7189 if (mHomeProcess != null && (dumpPackage == null
7190 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007191 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007192 }
7193
7194 if (mPreviousProcess != null && (dumpPackage == null
7195 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007196 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007197 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7198 }
7199
7200 if (mHeavyWeightProcess != null && (dumpPackage == null
7201 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007202 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007203 }
7204
7205 for (Map.Entry<String, Integer> entry
7206 : mCompatModePackages.getPackages().entrySet()) {
7207 String pkg = entry.getKey();
7208 int mode = entry.getValue();
7209 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7210 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7211 proto.write(PACKAGE, pkg);
7212 proto.write(MODE, mode);
7213 proto.end(compatToken);
7214 }
7215 }
7216
7217 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007218 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007219 }
7220
7221 }
7222 }
7223
7224 @Override
7225 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7226 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7227 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007228 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7229 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007230 }
7231
7232 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007233 public void dumpForOom(PrintWriter pw) {
7234 synchronized (mGlobalLock) {
7235 pw.println(" mHomeProcess: " + mHomeProcess);
7236 pw.println(" mPreviousProcess: " + mPreviousProcess);
7237 if (mHeavyWeightProcess != null) {
7238 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7239 }
7240 }
7241 }
7242
7243 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007244 public boolean canGcNow() {
7245 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007246 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007247 }
7248 }
7249
Riddle Hsua0536432019-02-16 00:38:59 +08007250 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007251 @Override
7252 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007253 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007254 if (mRootWindowContainer == null) {
7255 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007256 // oomadj after AMS created.
7257 return null;
7258 }
Louis Chang149d5c82019-12-30 09:47:39 +08007259 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007260 return top != null ? top.app : null;
7261 }
7262 }
7263
Riddle Hsua0536432019-02-16 00:38:59 +08007264 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007265 @Override
7266 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007267 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007268 if (mRootWindowContainer != null) {
7269 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007270 }
7271 }
7272 }
7273
7274 @Override
7275 public void scheduleDestroyAllActivities(String reason) {
7276 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007277 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007278 }
7279 }
7280
7281 @Override
7282 public void removeUser(int userId) {
7283 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007284 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007285 }
7286 }
7287
7288 @Override
7289 public boolean switchUser(int userId, UserState userState) {
7290 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007291 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007292 }
7293 }
7294
7295 @Override
7296 public void onHandleAppCrash(WindowProcessController wpc) {
7297 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007298 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007299 }
7300 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007301
7302 @Override
7303 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7304 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007305 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007306 }
7307 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007308
Riddle Hsua0536432019-02-16 00:38:59 +08007309 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007310 @Override
7311 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007312 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007313 }
7314
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 onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007318 mActiveUids.onUidInactive(uid);
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 onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007324 mActiveUids.onActiveUidsCleared();
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 onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007330 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007331 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007332
7333 @Override
7334 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007335 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007336 mPendingTempWhitelist.put(uid, tag);
7337 }
7338 }
7339
7340 @Override
7341 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007342 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007343 mPendingTempWhitelist.remove(uid);
7344 }
7345 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007346
7347 @Override
7348 public boolean handleAppCrashInActivityController(String processName, int pid,
7349 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7350 Runnable killCrashingAppCallback) {
7351 synchronized (mGlobalLock) {
7352 if (mController == null) {
7353 return false;
7354 }
7355
7356 try {
7357 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7358 stackTrace)) {
7359 killCrashingAppCallback.run();
7360 return true;
7361 }
7362 } catch (RemoteException e) {
7363 mController = null;
7364 Watchdog.getInstance().setActivityController(null);
7365 }
7366 return false;
7367 }
7368 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007369
7370 @Override
7371 public void removeRecentTasksByPackageName(String packageName, int userId) {
7372 synchronized (mGlobalLock) {
7373 mRecentTasks.removeTasksByPackageName(packageName, userId);
7374 }
7375 }
7376
7377 @Override
7378 public void cleanupRecentTasksForUser(int userId) {
7379 synchronized (mGlobalLock) {
7380 mRecentTasks.cleanupLocked(userId);
7381 }
7382 }
7383
7384 @Override
7385 public void loadRecentTasksForUser(int userId) {
7386 synchronized (mGlobalLock) {
7387 mRecentTasks.loadUserRecentsLocked(userId);
7388 }
7389 }
7390
7391 @Override
7392 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7393 synchronized (mGlobalLock) {
7394 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7395 }
7396 }
7397
7398 @Override
7399 public void flushRecentTasks() {
7400 mRecentTasks.flush();
7401 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007402
7403 @Override
7404 public WindowProcessController getHomeProcess() {
7405 synchronized (mGlobalLock) {
7406 return mHomeProcess;
7407 }
7408 }
7409
7410 @Override
7411 public WindowProcessController getPreviousProcess() {
7412 synchronized (mGlobalLock) {
7413 return mPreviousProcess;
7414 }
7415 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007416
7417 @Override
7418 public void clearLockedTasks(String reason) {
7419 synchronized (mGlobalLock) {
7420 getLockTaskController().clearLockedTasks(reason);
7421 }
7422 }
7423
7424 @Override
7425 public void updateUserConfiguration() {
7426 synchronized (mGlobalLock) {
7427 final Configuration configuration = new Configuration(getGlobalConfiguration());
7428 final int currentUserId = mAmInternal.getCurrentUserId();
7429 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7430 configuration, currentUserId, Settings.System.canWrite(mContext));
7431 updateConfigurationLocked(configuration, null /* starting */,
7432 false /* initLocale */, false /* persistent */, currentUserId,
7433 false /* deferResume */);
7434 }
7435 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007436
7437 @Override
7438 public boolean canShowErrorDialogs() {
7439 synchronized (mGlobalLock) {
7440 return mShowDialogs && !mSleeping && !mShuttingDown
7441 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7442 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7443 mAmInternal.getCurrentUserId())
7444 && !(UserManager.isDeviceInDemoMode(mContext)
7445 && mAmInternal.getCurrentUser().isDemo());
7446 }
7447 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007448
7449 @Override
7450 public void setProfileApp(String profileApp) {
7451 synchronized (mGlobalLock) {
7452 mProfileApp = profileApp;
7453 }
7454 }
7455
7456 @Override
7457 public void setProfileProc(WindowProcessController wpc) {
7458 synchronized (mGlobalLock) {
7459 mProfileProc = wpc;
7460 }
7461 }
7462
7463 @Override
7464 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7465 synchronized (mGlobalLock) {
7466 mProfilerInfo = profilerInfo;
7467 }
7468 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007469
7470 @Override
7471 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7472 synchronized (mGlobalLock) {
7473 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7474 }
7475 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007476
7477 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007478 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7479 boolean reducedResolution) {
7480 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7481 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007482 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007483
7484 @Override
7485 public boolean isUidForeground(int uid) {
7486 synchronized (mGlobalLock) {
7487 return ActivityTaskManagerService.this.isUidForeground(uid);
7488 }
7489 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007490
7491 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007492 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007493 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007494 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007495 }
7496 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007497
7498 @Override
7499 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007500 // Translate package names into UIDs
7501 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007502 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007503 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7504 if (uid >= 0) {
7505 result.add(uid);
7506 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007507 }
7508 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007509 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007510 }
7511 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007512 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007513}