blob: d3129f021bab2c8892cf0c0e70f5e00aad582732 [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;
Evan Rosky4505b352018-09-06 11:20:40 -0700237import 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;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900267import 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;
381 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
894 AppOpsService getAppOpsService() {
895 if (mAppOpsService == null) {
896 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
897 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
898 }
899 return mAppOpsService;
900 }
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) {
907 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmannda554e42019-12-20 11:21:02 -0800908 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,
1028 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,
1032 UserHandle.getCallingUserId());
1033 }
1034
1035 @Override
1036 public final int startActivities(IApplicationThread caller, String callingPackage,
1037 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,
1045 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,
1052 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,
1056 true /*validateIncomingUser*/);
1057 }
1058
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001059 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060 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,
1234 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,
1260 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
1434 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1435 Intent intent, String resolvedType, IVoiceInteractionSession session,
1436 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
1460 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,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001498 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
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002798 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002799 @Override
2800 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002801 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002802 long ident = Binder.clearCallingIdentity();
2803 try {
2804 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002805 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002806 }
2807 } finally {
2808 Binder.restoreCallingIdentity(ident);
2809 }
2810 }
2811
2812 @Override
2813 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002814 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002815 long ident = Binder.clearCallingIdentity();
2816 try {
2817 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002818 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002819 }
2820 } finally {
2821 Binder.restoreCallingIdentity(ident);
2822 }
2823 }
2824
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002825 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002827 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2828 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2829 long ident = Binder.clearCallingIdentity();
2830 try {
2831 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002832 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002833 }
2834 } finally {
2835 Binder.restoreCallingIdentity(ident);
2836 }
2837 }
2838
2839 @Override
2840 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2841 int displayId) {
2842 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2843 long ident = Binder.clearCallingIdentity();
2844 try {
2845 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002846 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002847 }
2848 } finally {
2849 Binder.restoreCallingIdentity(ident);
2850 }
2851 }
2852
2853 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002854 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002855 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002856 final long callingUid = Binder.getCallingUid();
2857 final long origId = Binder.clearCallingIdentity();
2858 try {
2859 synchronized (mGlobalLock) {
2860 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002861 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002862 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2863 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2864 }
2865 } finally {
2866 Binder.restoreCallingIdentity(origId);
2867 }
2868 }
2869
2870 @Override
2871 public void startLockTaskModeByToken(IBinder token) {
2872 synchronized (mGlobalLock) {
2873 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2874 if (r == null) {
2875 return;
2876 }
Louis Changcdec0802019-11-11 11:45:07 +08002877 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002878 }
2879 }
2880
2881 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002882 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002883 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884 // This makes inner call to look as if it was initiated by system.
2885 long ident = Binder.clearCallingIdentity();
2886 try {
2887 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002888 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002889 MATCH_TASK_IN_STACKS_ONLY);
2890 if (task == null) {
2891 return;
2892 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002893
2894 // When starting lock task mode the stack must be in front and focused
2895 task.getStack().moveToFront("startSystemLockTaskMode");
2896 startLockTaskModeLocked(task, true /* isSystemCaller */);
2897 }
2898 } finally {
2899 Binder.restoreCallingIdentity(ident);
2900 }
2901 }
2902
2903 @Override
2904 public void stopLockTaskModeByToken(IBinder token) {
2905 synchronized (mGlobalLock) {
2906 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2907 if (r == null) {
2908 return;
2909 }
Louis Changcdec0802019-11-11 11:45:07 +08002910 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002911 }
2912 }
2913
2914 /**
2915 * This API should be called by SystemUI only when user perform certain action to dismiss
2916 * lock task mode. We should only dismiss pinned lock task mode in this case.
2917 */
2918 @Override
2919 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002920 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002921 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2922 }
2923
Louis Changcdec0802019-11-11 11:45:07 +08002924 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2926 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2927 return;
2928 }
2929
Louis Chang149d5c82019-12-30 09:47:39 +08002930 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002931 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002932 throw new IllegalArgumentException("Invalid task, not in foreground");
2933 }
2934
2935 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2936 // system or a specific app.
2937 // * System-initiated requests will only start the pinned mode (screen pinning)
2938 // * App-initiated requests
2939 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2940 // - will start the pinned mode, otherwise
2941 final int callingUid = Binder.getCallingUid();
2942 long ident = Binder.clearCallingIdentity();
2943 try {
2944 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002945 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002946
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002947 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002948 } finally {
2949 Binder.restoreCallingIdentity(ident);
2950 }
2951 }
2952
Louis Changcdec0802019-11-11 11:45:07 +08002953 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002954 final int callingUid = Binder.getCallingUid();
2955 long ident = Binder.clearCallingIdentity();
2956 try {
2957 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002958 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002959 }
2960 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2961 // task and jumping straight into a call in the case of emergency call back.
2962 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2963 if (tm != null) {
2964 tm.showInCallScreen(false);
2965 }
2966 } finally {
2967 Binder.restoreCallingIdentity(ident);
2968 }
2969 }
2970
2971 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002972 public void updateLockTaskPackages(int userId, String[] packages) {
2973 final int callingUid = Binder.getCallingUid();
2974 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2975 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2976 "updateLockTaskPackages()");
2977 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002978 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002979 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2980 + Arrays.toString(packages));
2981 getLockTaskController().updateLockTaskPackages(userId, packages);
2982 }
2983 }
2984
2985 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002986 public boolean isInLockTaskMode() {
2987 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2988 }
2989
2990 @Override
2991 public int getLockTaskModeState() {
2992 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002993 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002994 }
2995 }
2996
2997 @Override
2998 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2999 synchronized (mGlobalLock) {
3000 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3001 if (r != null) {
3002 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003003 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003004 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003005 }
3006 }
3007 }
3008
3009 @Override
3010 public Bundle getActivityOptions(IBinder token) {
3011 final long origId = Binder.clearCallingIdentity();
3012 try {
3013 synchronized (mGlobalLock) {
3014 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3015 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003016 final ActivityOptions activityOptions = r.takeOptionsLocked(
3017 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003018 return activityOptions == null ? null : activityOptions.toBundle();
3019 }
3020 return null;
3021 }
3022 } finally {
3023 Binder.restoreCallingIdentity(origId);
3024 }
3025 }
3026
3027 @Override
3028 public List<IBinder> getAppTasks(String callingPackage) {
3029 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003030 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003031 long ident = Binder.clearCallingIdentity();
3032 try {
3033 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003034 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003035 }
3036 } finally {
3037 Binder.restoreCallingIdentity(ident);
3038 }
3039 }
3040
3041 @Override
3042 public void finishVoiceTask(IVoiceInteractionSession session) {
3043 synchronized (mGlobalLock) {
3044 final long origId = Binder.clearCallingIdentity();
3045 try {
3046 // TODO: VI Consider treating local voice interactions and voice tasks
3047 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003048 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003049 } finally {
3050 Binder.restoreCallingIdentity(origId);
3051 }
3052 }
3053
3054 }
3055
3056 @Override
3057 public boolean isTopOfTask(IBinder token) {
3058 synchronized (mGlobalLock) {
3059 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003060 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003061 }
3062 }
3063
3064 @Override
3065 public void notifyLaunchTaskBehindComplete(IBinder token) {
3066 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3067 }
3068
3069 @Override
3070 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003071 mH.post(() -> {
3072 synchronized (mGlobalLock) {
3073 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003074 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003075 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003076 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003077 } catch (RemoteException e) {
3078 }
3079 }
3080 }
3081
3082 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003083 }
3084
3085 /** Called from an app when assist data is ready. */
3086 @Override
3087 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3088 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003089 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003090 synchronized (pae) {
3091 pae.result = extras;
3092 pae.structure = structure;
3093 pae.content = content;
3094 if (referrer != null) {
3095 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3096 }
3097 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003098 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003099 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003100 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003101 structure.setHomeActivity(pae.isHome);
3102 }
3103 pae.haveResult = true;
3104 pae.notifyAll();
3105 if (pae.intent == null && pae.receiver == null) {
3106 // Caller is just waiting for the result.
3107 return;
3108 }
3109 }
3110 // We are now ready to launch the assist activity.
3111 IAssistDataReceiver sendReceiver = null;
3112 Bundle sendBundle = null;
3113 synchronized (mGlobalLock) {
3114 buildAssistBundleLocked(pae, extras);
3115 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003116 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003117 if (!exists) {
3118 // Timed out.
3119 return;
3120 }
3121
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003122 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003123 // Caller wants result sent back to them.
3124 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003125 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003126 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003127 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3128 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003129 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3130 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3131 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3132 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3133 }
3134 }
3135 if (sendReceiver != null) {
3136 try {
3137 sendReceiver.onHandleAssistData(sendBundle);
3138 } catch (RemoteException e) {
3139 }
3140 return;
3141 }
3142
3143 final long ident = Binder.clearCallingIdentity();
3144 try {
3145 if (TextUtils.equals(pae.intent.getAction(),
3146 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003147 // Start voice interaction through VoiceInteractionManagerService.
3148 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3149 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003150 } else {
3151 pae.intent.replaceExtras(pae.extras);
3152 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3153 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3154 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003155 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003156
3157 try {
3158 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3159 } catch (ActivityNotFoundException e) {
3160 Slog.w(TAG, "No activity to handle assist action.", e);
3161 }
3162 }
3163 } finally {
3164 Binder.restoreCallingIdentity(ident);
3165 }
3166 }
3167
3168 @Override
3169 public int addAppTask(IBinder activityToken, Intent intent,
3170 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3171 final int callingUid = Binder.getCallingUid();
3172 final long callingIdent = Binder.clearCallingIdentity();
3173
3174 try {
3175 synchronized (mGlobalLock) {
3176 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3177 if (r == null) {
3178 throw new IllegalArgumentException("Activity does not exist; token="
3179 + activityToken);
3180 }
3181 ComponentName comp = intent.getComponent();
3182 if (comp == null) {
3183 throw new IllegalArgumentException("Intent " + intent
3184 + " must specify explicit component");
3185 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003186 if (thumbnail.getWidth() != mThumbnailWidth
3187 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003188 throw new IllegalArgumentException("Bad thumbnail size: got "
3189 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003190 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003191 }
3192 if (intent.getSelector() != null) {
3193 intent.setSelector(null);
3194 }
3195 if (intent.getSourceBounds() != null) {
3196 intent.setSourceBounds(null);
3197 }
3198 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3199 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3200 // The caller has added this as an auto-remove task... that makes no
3201 // sense, so turn off auto-remove.
3202 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3203 }
3204 }
3205 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3206 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3207 if (ainfo.applicationInfo.uid != callingUid) {
3208 throw new SecurityException(
3209 "Can't add task for another application: target uid="
3210 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3211 }
3212
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003213 final ActivityStack stack = r.getRootTask();
Louis Changcdec0802019-11-11 11:45:07 +08003214 final Task task = stack.createTask(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08003215 mStackSupervisor.getNextTaskIdForUser(r.mUserId), ainfo, intent, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003216 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003217 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003218 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003219 return INVALID_TASK_ID;
3220 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003221 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003222
3223 // TODO: Send the thumbnail to WM to store it.
3224
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003225 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003226 }
3227 } finally {
3228 Binder.restoreCallingIdentity(callingIdent);
3229 }
3230 }
3231
3232 @Override
3233 public Point getAppTaskThumbnailSize() {
3234 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003235 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003236 }
3237 }
3238
3239 @Override
3240 public void setTaskResizeable(int taskId, int resizeableMode) {
3241 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003242 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003243 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3244 if (task == null) {
3245 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3246 return;
3247 }
3248 task.setResizeMode(resizeableMode);
3249 }
3250 }
3251
3252 @Override
3253 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003254 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003255 long ident = Binder.clearCallingIdentity();
3256 try {
3257 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003258 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003259 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003260 if (task == null) {
3261 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3262 return;
3263 }
3264 // Place the task in the right stack if it isn't there already based on
3265 // the requested bounds.
3266 // The stack transition logic is:
3267 // - a null bounds on a freeform task moves that task to fullscreen
3268 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3269 // that task to freeform
3270 // - otherwise the task is not moved
3271 ActivityStack stack = task.getStack();
3272 if (!task.getWindowConfiguration().canResizeTask()) {
3273 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3274 }
3275 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3276 stack = stack.getDisplay().getOrCreateStack(
3277 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3278 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3279 stack = stack.getDisplay().getOrCreateStack(
3280 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3281 }
3282
3283 // Reparent the task to the right stack if necessary
3284 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3285 if (stack != task.getStack()) {
3286 // Defer resume until the task is resized below
3287 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3288 DEFER_RESUME, "resizeTask");
3289 preserveWindow = false;
3290 }
3291
3292 // After reparenting (which only resizes the task to the stack bounds), resize the
3293 // task to the actual bounds provided
3294 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3295 }
3296 } finally {
3297 Binder.restoreCallingIdentity(ident);
3298 }
3299 }
3300
3301 @Override
3302 public boolean releaseActivityInstance(IBinder token) {
3303 synchronized (mGlobalLock) {
3304 final long origId = Binder.clearCallingIdentity();
3305 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003306 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3307 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003308 return false;
3309 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003310 r.destroyImmediately(true /* removeFromApp */, "app-req");
3311 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003312 } finally {
3313 Binder.restoreCallingIdentity(origId);
3314 }
3315 }
3316 }
3317
3318 @Override
3319 public void releaseSomeActivities(IApplicationThread appInt) {
3320 synchronized (mGlobalLock) {
3321 final long origId = Binder.clearCallingIdentity();
3322 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003323 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003324 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003325 } finally {
3326 Binder.restoreCallingIdentity(origId);
3327 }
3328 }
3329 }
3330
3331 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003332 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003333 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003334 != PackageManager.PERMISSION_GRANTED) {
3335 throw new SecurityException("Requires permission "
3336 + android.Manifest.permission.DEVICE_POWER);
3337 }
3338
3339 synchronized (mGlobalLock) {
3340 long ident = Binder.clearCallingIdentity();
3341 if (mKeyguardShown != keyguardShowing) {
3342 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003343 final Message msg = PooledLambda.obtainMessage(
3344 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3345 keyguardShowing);
3346 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003347 }
3348 try {
wilsonshih177261f2019-02-22 12:02:18 +08003349 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003350 } finally {
3351 Binder.restoreCallingIdentity(ident);
3352 }
3353 }
3354
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003355 mH.post(() -> {
3356 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3357 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3358 }
3359 });
3360 }
3361
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003362 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003363 mH.post(() -> {
3364 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3365 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3366 }
3367 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003368 }
3369
3370 @Override
3371 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003372 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3373 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003374
3375 final File passedIconFile = new File(filePath);
3376 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3377 passedIconFile.getName());
3378 if (!legitIconFile.getPath().equals(filePath)
3379 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3380 throw new IllegalArgumentException("Bad file path: " + filePath
3381 + " passed for userId " + userId);
3382 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003383 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003384 }
3385
3386 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003387 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003388 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003389 synchronized (mGlobalLock) {
3390 final long ident = Binder.clearCallingIdentity();
3391 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003392 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003393 if (stack == null) {
3394 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3395 return;
3396 }
3397 if (!stack.isActivityTypeStandardOrUndefined()) {
3398 throw new IllegalArgumentException(
3399 "Removing non-standard stack is not allowed.");
3400 }
3401 mStackSupervisor.removeStack(stack);
3402 } finally {
3403 Binder.restoreCallingIdentity(ident);
3404 }
3405 }
3406 }
3407
3408 @Override
3409 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003410 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003411
3412 synchronized (mGlobalLock) {
3413 final long ident = Binder.clearCallingIdentity();
3414 try {
3415 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3416 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003417 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003418 } finally {
3419 Binder.restoreCallingIdentity(ident);
3420 }
3421 }
3422 }
3423
3424 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003425 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003426 synchronized (mGlobalLock) {
3427 long ident = Binder.clearCallingIdentity();
3428 try {
3429 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3430 if (r == null) {
3431 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003432 "toggleFreeformWindowingMode: No activity record matching token="
3433 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003434 }
3435
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003436 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003437 if (stack == null) {
3438 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3439 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003440 }
3441
Yunfan Chend967af82019-01-17 18:30:18 +09003442 if (!stack.inFreeformWindowingMode()
3443 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3444 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3445 + "toggle between fullscreen and freeform.");
3446 }
3447
3448 if (stack.inFreeformWindowingMode()) {
3449 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003450 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003451 throw new IllegalStateException("Size-compat windows are currently not"
3452 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003453 } else if (stack.getParent().inFreeformWindowingMode()) {
3454 // If the window is on a freeform display, set it to undefined. It will be
3455 // resolved to freeform and it can adjust windowing mode when the display mode
3456 // changes in runtime.
3457 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003458 } else {
3459 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3460 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003461 } finally {
3462 Binder.restoreCallingIdentity(ident);
3463 }
3464 }
3465 }
3466
3467 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3468 @Override
3469 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003470 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003471 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003472 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003473 }
3474
3475 /** Unregister a task stack listener so that it stops receiving callbacks. */
3476 @Override
3477 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003478 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003479 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003480 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003481 }
3482
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003483 @Override
3484 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3485 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3486 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3487 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3488 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3489 }
3490
3491 @Override
3492 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3493 IBinder activityToken, int flags) {
3494 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3495 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3496 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3497 }
3498
3499 @Override
3500 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3501 Bundle args) {
3502 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3503 true /* focused */, true /* newSessionId */, userHandle, args,
3504 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3505 }
3506
3507 @Override
3508 public Bundle getAssistContextExtras(int requestType) {
3509 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3510 null, null, true /* focused */, true /* newSessionId */,
3511 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3512 if (pae == null) {
3513 return null;
3514 }
3515 synchronized (pae) {
3516 while (!pae.haveResult) {
3517 try {
3518 pae.wait();
3519 } catch (InterruptedException e) {
3520 }
3521 }
3522 }
3523 synchronized (mGlobalLock) {
3524 buildAssistBundleLocked(pae, pae.result);
3525 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003526 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003527 }
3528 return pae.extras;
3529 }
3530
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003531 /**
3532 * Binder IPC calls go through the public entry point.
3533 * This can be called with or without the global lock held.
3534 */
3535 private static int checkCallingPermission(String permission) {
3536 return checkPermission(
3537 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3538 }
3539
3540 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003541 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003542 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3543 mAmInternal.enforceCallingPermission(permission, func);
3544 }
3545 }
3546
3547 @VisibleForTesting
3548 int checkGetTasksPermission(String permission, int pid, int uid) {
3549 return checkPermission(permission, pid, uid);
3550 }
3551
3552 static int checkPermission(String permission, int pid, int uid) {
3553 if (permission == null) {
3554 return PackageManager.PERMISSION_DENIED;
3555 }
3556 return checkComponentPermission(permission, pid, uid, -1, true);
3557 }
3558
Wale Ogunwale214f3482018-10-04 11:00:47 -07003559 public static int checkComponentPermission(String permission, int pid, int uid,
3560 int owningUid, boolean exported) {
3561 return ActivityManagerService.checkComponentPermission(
3562 permission, pid, uid, owningUid, exported);
3563 }
3564
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003565 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3566 if (getRecentTasks().isCallerRecents(callingUid)) {
3567 // Always allow the recents component to get tasks
3568 return true;
3569 }
3570
3571 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3572 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3573 if (!allowed) {
3574 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3575 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3576 // Temporary compatibility: some existing apps on the system image may
3577 // still be requesting the old permission and not switched to the new
3578 // one; if so, we'll still allow them full access. This means we need
3579 // to see if they are holding the old permission and are a system app.
3580 try {
3581 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3582 allowed = true;
3583 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3584 + " is using old GET_TASKS but privileged; allowing");
3585 }
3586 } catch (RemoteException e) {
3587 }
3588 }
3589 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3590 + " does not hold REAL_GET_TASKS; limiting output");
3591 }
3592 return allowed;
3593 }
3594
Nicholas Sauer0259e532019-08-30 08:24:55 -07003595 boolean isCrossUserAllowed(int pid, int uid) {
3596 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3597 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3598 }
3599
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003600 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3601 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3602 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3603 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003604 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003605 "enqueueAssistContext()");
3606
3607 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003608 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003609 if (activity == null) {
3610 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3611 return null;
3612 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003613 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003614 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3615 return null;
3616 }
3617 if (focused) {
3618 if (activityToken != null) {
3619 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3620 if (activity != caller) {
3621 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3622 + " is not current top " + activity);
3623 return null;
3624 }
3625 }
3626 } else {
3627 activity = ActivityRecord.forTokenLocked(activityToken);
3628 if (activity == null) {
3629 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3630 + " couldn't be found");
3631 return null;
3632 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003633 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003634 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3635 return null;
3636 }
3637 }
3638
3639 PendingAssistExtras pae;
3640 Bundle extras = new Bundle();
3641 if (args != null) {
3642 extras.putAll(args);
3643 }
3644 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003645 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003646
3647 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3648 userHandle);
3649 pae.isHome = activity.isActivityTypeHome();
3650
3651 // Increment the sessionId if necessary
3652 if (newSessionId) {
3653 mViSessionId++;
3654 }
3655 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003656 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3657 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003658 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003659 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003660 } catch (RemoteException e) {
3661 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3662 return null;
3663 }
3664 return pae;
3665 }
3666 }
3667
3668 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3669 if (result != null) {
3670 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3671 }
3672 if (pae.hint != null) {
3673 pae.extras.putBoolean(pae.hint, true);
3674 }
3675 }
3676
3677 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3678 IAssistDataReceiver receiver;
3679 synchronized (mGlobalLock) {
3680 mPendingAssistExtras.remove(pae);
3681 receiver = pae.receiver;
3682 }
3683 if (receiver != null) {
3684 // Caller wants result sent back to them.
3685 Bundle sendBundle = new Bundle();
3686 // At least return the receiver extras
3687 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3688 try {
3689 pae.receiver.onHandleAssistData(sendBundle);
3690 } catch (RemoteException e) {
3691 }
3692 }
3693 }
3694
3695 public class PendingAssistExtras extends Binder implements Runnable {
3696 public final ActivityRecord activity;
3697 public boolean isHome;
3698 public final Bundle extras;
3699 public final Intent intent;
3700 public final String hint;
3701 public final IAssistDataReceiver receiver;
3702 public final int userHandle;
3703 public boolean haveResult = false;
3704 public Bundle result = null;
3705 public AssistStructure structure = null;
3706 public AssistContent content = null;
3707 public Bundle receiverExtras;
3708
3709 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3710 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3711 int _userHandle) {
3712 activity = _activity;
3713 extras = _extras;
3714 intent = _intent;
3715 hint = _hint;
3716 receiver = _receiver;
3717 receiverExtras = _receiverExtras;
3718 userHandle = _userHandle;
3719 }
3720
3721 @Override
3722 public void run() {
3723 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3724 synchronized (this) {
3725 haveResult = true;
3726 notifyAll();
3727 }
3728 pendingAssistExtrasTimedOut(this);
3729 }
3730 }
3731
3732 @Override
3733 public boolean isAssistDataAllowedOnCurrentActivity() {
3734 int userId;
3735 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003736 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003737 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3738 return false;
3739 }
3740
Wale Ogunwale21e06482019-11-18 05:14:15 -08003741 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003742 if (activity == null) {
3743 return false;
3744 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003745 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003746 }
3747 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3748 }
3749
3750 @Override
3751 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3752 long ident = Binder.clearCallingIdentity();
3753 try {
3754 synchronized (mGlobalLock) {
3755 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003756 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003757 if (top != caller) {
3758 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3759 + " is not current top " + top);
3760 return false;
3761 }
3762 if (!top.nowVisible) {
3763 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3764 + " is not visible");
3765 return false;
3766 }
3767 }
3768 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3769 token);
3770 } finally {
3771 Binder.restoreCallingIdentity(ident);
3772 }
3773 }
3774
3775 @Override
3776 public boolean isRootVoiceInteraction(IBinder token) {
3777 synchronized (mGlobalLock) {
3778 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3779 if (r == null) {
3780 return false;
3781 }
3782 return r.rootVoiceInteraction;
3783 }
3784 }
3785
Wale Ogunwalef6733932018-06-27 05:14:34 -07003786 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3787 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3788 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3789 if (activityToCallback == null) return;
3790 activityToCallback.setVoiceSessionLocked(voiceSession);
3791
3792 // Inform the activity
3793 try {
3794 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3795 voiceInteractor);
3796 long token = Binder.clearCallingIdentity();
3797 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003798 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003799 } finally {
3800 Binder.restoreCallingIdentity(token);
3801 }
3802 // TODO: VI Should we cache the activity so that it's easier to find later
3803 // rather than scan through all the stacks and activities?
3804 } catch (RemoteException re) {
3805 activityToCallback.clearVoiceSessionLocked();
3806 // TODO: VI Should this terminate the voice session?
3807 }
3808 }
3809
3810 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3811 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3812 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3813 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3814 boolean wasRunningVoice = mRunningVoice != null;
3815 mRunningVoice = session;
3816 if (!wasRunningVoice) {
3817 mVoiceWakeLock.acquire();
3818 updateSleepIfNeededLocked();
3819 }
3820 }
3821 }
3822
3823 void finishRunningVoiceLocked() {
3824 if (mRunningVoice != null) {
3825 mRunningVoice = null;
3826 mVoiceWakeLock.release();
3827 updateSleepIfNeededLocked();
3828 }
3829 }
3830
3831 @Override
3832 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3833 synchronized (mGlobalLock) {
3834 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3835 if (keepAwake) {
3836 mVoiceWakeLock.acquire();
3837 } else {
3838 mVoiceWakeLock.release();
3839 }
3840 }
3841 }
3842 }
3843
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003844 @Override
3845 public ComponentName getActivityClassForToken(IBinder token) {
3846 synchronized (mGlobalLock) {
3847 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3848 if (r == null) {
3849 return null;
3850 }
3851 return r.intent.getComponent();
3852 }
3853 }
3854
3855 @Override
3856 public String getPackageForToken(IBinder token) {
3857 synchronized (mGlobalLock) {
3858 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3859 if (r == null) {
3860 return null;
3861 }
3862 return r.packageName;
3863 }
3864 }
3865
3866 @Override
3867 public void showLockTaskEscapeMessage(IBinder token) {
3868 synchronized (mGlobalLock) {
3869 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3870 if (r == null) {
3871 return;
3872 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003873 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003874 }
3875 }
3876
3877 @Override
3878 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003879 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003880 final long token = Binder.clearCallingIdentity();
3881 try {
3882 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003883 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003884 }
3885 } finally {
3886 Binder.restoreCallingIdentity(token);
3887 }
3888 }
3889
3890 /**
3891 * Try to place task to provided position. The final position might be different depending on
3892 * current user and stacks state. The task will be moved to target stack if it's currently in
3893 * different stack.
3894 */
3895 @Override
3896 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003897 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003898 synchronized (mGlobalLock) {
3899 long ident = Binder.clearCallingIdentity();
3900 try {
3901 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3902 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003903 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003904 if (task == null) {
3905 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3906 + taskId);
3907 }
3908
Louis Chang149d5c82019-12-30 09:47:39 +08003909 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003910
3911 if (stack == null) {
3912 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3913 + stackId);
3914 }
3915 if (!stack.isActivityTypeStandardOrUndefined()) {
3916 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3917 + " the position of task " + taskId + " in/to non-standard stack");
3918 }
3919
3920 // TODO: Have the callers of this API call a separate reparent method if that is
3921 // what they intended to do vs. having this method also do reparenting.
3922 if (task.getStack() == stack) {
3923 // Change position in current stack.
3924 stack.positionChildAt(task, position);
3925 } else {
3926 // Reparent to new stack.
3927 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3928 !DEFER_RESUME, "positionTaskInStack");
3929 }
3930 } finally {
3931 Binder.restoreCallingIdentity(ident);
3932 }
3933 }
3934 }
3935
3936 @Override
3937 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3938 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3939 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003940 + Arrays.toString(horizontalSizeConfiguration) + " "
3941 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003942 synchronized (mGlobalLock) {
3943 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3944 if (record == null) {
3945 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3946 + "found for: " + token);
3947 }
3948 record.setSizeConfigurations(horizontalSizeConfiguration,
3949 verticalSizeConfigurations, smallestSizeConfigurations);
3950 }
3951 }
3952
3953 /**
3954 * Dismisses split-screen multi-window mode.
3955 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3956 */
3957 @Override
3958 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003959 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003960 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3961 final long ident = Binder.clearCallingIdentity();
3962 try {
3963 synchronized (mGlobalLock) {
3964 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08003965 mRootWindowContainer.getDefaultDisplay().getRootSplitScreenPrimaryTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003966 if (stack == null) {
3967 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3968 return;
3969 }
3970
3971 if (toTop) {
3972 // Caller wants the current split-screen primary stack to be the top stack after
3973 // it goes fullscreen, so move it to the front.
3974 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003975 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003976 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003977 // stack after it goes fullscreen, so we move the focus to the top-most
3978 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003979 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3980 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3981 if (otherStack != null) {
3982 otherStack.moveToFront("dismissSplitScreenMode_other");
3983 }
3984 }
3985
Evan Rosky10475742018-09-05 19:02:48 -07003986 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003987 }
3988 } finally {
3989 Binder.restoreCallingIdentity(ident);
3990 }
3991 }
3992
3993 /**
3994 * Dismisses Pip
3995 * @param animate True if the dismissal should be animated.
3996 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3997 * default animation duration should be used.
3998 */
3999 @Override
4000 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004001 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004002 final long ident = Binder.clearCallingIdentity();
4003 try {
4004 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004005 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08004006 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004007 if (stack == null) {
4008 Slog.w(TAG, "dismissPip: pinned stack not found.");
4009 return;
4010 }
4011 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4012 throw new IllegalArgumentException("Stack: " + stack
4013 + " doesn't support animated resize.");
4014 }
Robert Carr8a2f9132019-11-11 15:03:15 -08004015 /**
4016 * TODO(b/146594635): Remove all PIP animation code from WM
4017 * once SysUI handles animation. Don't even try to animate TaskOrganized tasks.
4018 */
4019 if (animate && !stack.isControlledByTaskOrganizer()) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004020 stack.animateResizePinnedStack(null /* destBounds */,
4021 null /* sourceHintBounds */, animationDuration,
4022 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004023 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004024 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004025 }
4026 }
4027 } finally {
4028 Binder.restoreCallingIdentity(ident);
4029 }
4030 }
4031
4032 @Override
4033 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004034 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004035 synchronized (mGlobalLock) {
4036 mSuppressResizeConfigChanges = suppress;
4037 }
4038 }
4039
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004040 @Override
4041 // TODO: API should just be about changing windowing modes...
4042 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004043 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004044 "moveTasksToFullscreenStack()");
4045 synchronized (mGlobalLock) {
4046 final long origId = Binder.clearCallingIdentity();
4047 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004048 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004049 if (stack != null){
4050 if (!stack.isActivityTypeStandardOrUndefined()) {
4051 throw new IllegalArgumentException(
4052 "You can't move tasks from non-standard stacks.");
4053 }
4054 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4055 }
4056 } finally {
4057 Binder.restoreCallingIdentity(origId);
4058 }
4059 }
4060 }
4061
4062 /**
4063 * Moves the top activity in the input stackId to the pinned stack.
4064 *
4065 * @param stackId Id of stack to move the top activity to pinned stack.
4066 * @param bounds Bounds to use for pinned stack.
4067 *
4068 * @return True if the top activity of the input stack was successfully moved to the pinned
4069 * stack.
4070 */
4071 @Override
4072 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004073 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004074 "moveTopActivityToPinnedStack()");
4075 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004076 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004077 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4078 + "Device doesn't support picture-in-picture mode");
4079 }
4080
4081 long ident = Binder.clearCallingIdentity();
4082 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004083 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004084 } finally {
4085 Binder.restoreCallingIdentity(ident);
4086 }
4087 }
4088 }
4089
4090 @Override
4091 public boolean isInMultiWindowMode(IBinder token) {
4092 final long origId = Binder.clearCallingIdentity();
4093 try {
4094 synchronized (mGlobalLock) {
4095 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4096 if (r == null) {
4097 return false;
4098 }
4099 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4100 return r.inMultiWindowMode();
4101 }
4102 } finally {
4103 Binder.restoreCallingIdentity(origId);
4104 }
4105 }
4106
4107 @Override
4108 public boolean isInPictureInPictureMode(IBinder token) {
4109 final long origId = Binder.clearCallingIdentity();
4110 try {
4111 synchronized (mGlobalLock) {
4112 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4113 }
4114 } finally {
4115 Binder.restoreCallingIdentity(origId);
4116 }
4117 }
4118
4119 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004120 if (r == null || r.getRootTask() == null || !r.inPinnedWindowingMode()
4121 || r.getRootTask().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004122 return false;
4123 }
4124
4125 // If we are animating to fullscreen then we have already dispatched the PIP mode
4126 // changed, so we should reflect that check here as well.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004127 final ActivityStack taskStack = r.getRootTask();
Yunfan Chen279f5582018-12-12 15:24:50 -08004128 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004129 }
4130
4131 @Override
4132 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4133 final long origId = Binder.clearCallingIdentity();
4134 try {
4135 synchronized (mGlobalLock) {
4136 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4137 "enterPictureInPictureMode", token, params);
4138
4139 // If the activity is already in picture in picture mode, then just return early
4140 if (isInPictureInPictureMode(r)) {
4141 return true;
4142 }
4143
4144 // Activity supports picture-in-picture, now check that we can enter PiP at this
4145 // point, if it is
4146 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4147 false /* beforeStopping */)) {
4148 return false;
4149 }
4150
4151 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004152 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004153 if (r.getParent() == null) {
4154 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4155 return;
4156 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004157 // Only update the saved args from the args that are set
4158 r.pictureInPictureArgs.copyOnlySet(params);
4159 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4160 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4161 // Adjust the source bounds by the insets for the transition down
4162 final Rect sourceBounds = new Rect(
4163 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004164 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004165 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004166 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004167 stack.setPictureInPictureAspectRatio(aspectRatio);
4168 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004169 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4170 r.info.applicationInfo.uid, r.shortComponentName,
4171 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004172 logPictureInPictureArgs(params);
4173 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004174 };
4175
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004176 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004177 // If the keyguard is showing or occluded, then try and dismiss it before
4178 // entering picture-in-picture (this will prompt the user to authenticate if the
4179 // device is currently locked).
4180 dismissKeyguard(token, new KeyguardDismissCallback() {
4181 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004182 public void onDismissSucceeded() {
4183 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004184 }
4185 }, null /* message */);
4186 } else {
4187 // Enter picture in picture immediately otherwise
4188 enterPipRunnable.run();
4189 }
4190 return true;
4191 }
4192 } finally {
4193 Binder.restoreCallingIdentity(origId);
4194 }
4195 }
4196
4197 @Override
4198 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4199 final long origId = Binder.clearCallingIdentity();
4200 try {
4201 synchronized (mGlobalLock) {
4202 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4203 "setPictureInPictureParams", token, params);
4204
4205 // Only update the saved args from the args that are set
4206 r.pictureInPictureArgs.copyOnlySet(params);
4207 if (r.inPinnedWindowingMode()) {
4208 // If the activity is already in picture-in-picture, update the pinned stack now
4209 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4210 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004211 final ActivityStack stack = r.getRootTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004212 if (!stack.isAnimatingBoundsToFullscreen()) {
4213 stack.setPictureInPictureAspectRatio(
4214 r.pictureInPictureArgs.getAspectRatio());
4215 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4216 }
4217 }
4218 logPictureInPictureArgs(params);
4219 }
4220 } finally {
4221 Binder.restoreCallingIdentity(origId);
4222 }
4223 }
4224
4225 @Override
4226 public int getMaxNumPictureInPictureActions(IBinder token) {
4227 // Currently, this is a static constant, but later, we may change this to be dependent on
4228 // the context of the activity
4229 return 3;
4230 }
4231
4232 private void logPictureInPictureArgs(PictureInPictureParams params) {
4233 if (params.hasSetActions()) {
4234 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4235 params.getActions().size());
4236 }
4237 if (params.hasSetAspectRatio()) {
4238 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4239 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4240 MetricsLogger.action(lm);
4241 }
4242 }
4243
4244 /**
4245 * Checks the state of the system and the activity associated with the given {@param token} to
4246 * verify that picture-in-picture is supported for that activity.
4247 *
4248 * @return the activity record for the given {@param token} if all the checks pass.
4249 */
4250 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4251 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004252 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004253 throw new IllegalStateException(caller
4254 + ": Device doesn't support picture-in-picture mode.");
4255 }
4256
4257 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4258 if (r == null) {
4259 throw new IllegalStateException(caller
4260 + ": Can't find activity for token=" + token);
4261 }
4262
4263 if (!r.supportsPictureInPicture()) {
4264 throw new IllegalStateException(caller
4265 + ": Current activity does not support picture-in-picture.");
4266 }
4267
4268 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004269 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004270 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004271 final float minAspectRatio = mContext.getResources().getFloat(
4272 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4273 final float maxAspectRatio = mContext.getResources().getFloat(
4274 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4275 throw new IllegalArgumentException(String.format(caller
4276 + ": Aspect ratio is too extreme (must be between %f and %f).",
4277 minAspectRatio, maxAspectRatio));
4278 }
4279
4280 // Truncate the number of actions if necessary
4281 params.truncateActions(getMaxNumPictureInPictureActions(token));
4282
4283 return r;
4284 }
4285
4286 @Override
4287 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004288 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004289 synchronized (mGlobalLock) {
4290 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4291 if (r == null) {
4292 throw new IllegalArgumentException("Activity does not exist; token="
4293 + activityToken);
4294 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004295 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004296 }
4297 }
4298
4299 @Override
4300 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4301 Rect tempDockedTaskInsetBounds,
4302 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004303 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004304 long ident = Binder.clearCallingIdentity();
4305 try {
4306 synchronized (mGlobalLock) {
4307 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4308 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4309 PRESERVE_WINDOWS);
4310 }
4311 } finally {
4312 Binder.restoreCallingIdentity(ident);
4313 }
4314 }
4315
4316 @Override
4317 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004318 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004319 final long ident = Binder.clearCallingIdentity();
4320 try {
4321 synchronized (mGlobalLock) {
4322 mStackSupervisor.setSplitScreenResizing(resizing);
4323 }
4324 } finally {
4325 Binder.restoreCallingIdentity(ident);
4326 }
4327 }
4328
Evan Rosky0037e5f2019-11-05 10:26:24 -08004329 @Override
4330 public ITaskOrganizerController getTaskOrganizerController() {
4331 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
4332 "getTaskOrganizerController()");
4333 return mTaskOrganizerController;
4334 }
4335
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004336 /**
4337 * Check that we have the features required for VR-related API calls, and throw an exception if
4338 * not.
4339 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004340 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004341 if (!mContext.getPackageManager().hasSystemFeature(
4342 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4343 throw new UnsupportedOperationException("VR mode not supported on this device!");
4344 }
4345 }
4346
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004347 @Override
4348 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004349 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004350
4351 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4352
4353 ActivityRecord r;
4354 synchronized (mGlobalLock) {
4355 r = ActivityRecord.isInStackLocked(token);
4356 }
4357
4358 if (r == null) {
4359 throw new IllegalArgumentException();
4360 }
4361
4362 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004363 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004364 VrManagerInternal.NO_ERROR) {
4365 return err;
4366 }
4367
4368 // Clear the binder calling uid since this path may call moveToTask().
4369 final long callingId = Binder.clearCallingIdentity();
4370 try {
4371 synchronized (mGlobalLock) {
4372 r.requestedVrComponent = (enabled) ? packageName : null;
4373
4374 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004375 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004376 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004377 }
4378 return 0;
4379 }
4380 } finally {
4381 Binder.restoreCallingIdentity(callingId);
4382 }
4383 }
4384
4385 @Override
4386 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4387 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4388 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004389 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004390 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4391 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4392 }
Louis Changcdec0802019-11-11 11:45:07 +08004393 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004394 || activity.voiceSession != null) {
4395 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4396 return;
4397 }
4398 if (activity.pendingVoiceInteractionStart) {
4399 Slog.w(TAG, "Pending start of voice interaction already.");
4400 return;
4401 }
4402 activity.pendingVoiceInteractionStart = true;
4403 }
4404 LocalServices.getService(VoiceInteractionManagerInternal.class)
4405 .startLocalVoiceInteraction(callingActivity, options);
4406 }
4407
4408 @Override
4409 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4410 LocalServices.getService(VoiceInteractionManagerInternal.class)
4411 .stopLocalVoiceInteraction(callingActivity);
4412 }
4413
4414 @Override
4415 public boolean supportsLocalVoiceInteraction() {
4416 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4417 .supportsLocalVoiceInteraction();
4418 }
4419
4420 /** Notifies all listeners when the pinned stack animation starts. */
4421 @Override
4422 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004423 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004424 }
4425
4426 /** Notifies all listeners when the pinned stack animation ends. */
4427 @Override
4428 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004429 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004430 }
4431
4432 @Override
4433 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004434 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004435 final long ident = Binder.clearCallingIdentity();
4436 try {
4437 synchronized (mGlobalLock) {
4438 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4439 }
4440 } finally {
4441 Binder.restoreCallingIdentity(ident);
4442 }
4443 }
4444
4445 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004446 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004447 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004448
4449 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004450 if (mWindowManager == null) {
4451 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4452 return false;
4453 }
4454
4455 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004456 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004457 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004458 }
4459
Riddle Hsua0022cd2019-09-09 21:12:41 +08004460 mH.sendMessage(PooledLambda.obtainMessage(
4461 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4462 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004463
4464 final long origId = Binder.clearCallingIdentity();
4465 try {
4466 if (values != null) {
4467 Settings.System.clearConfiguration(values);
4468 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004469 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004470 UserHandle.USER_NULL, false /* deferResume */,
4471 mTmpUpdateConfigurationResult);
4472 return mTmpUpdateConfigurationResult.changes != 0;
4473 } finally {
4474 Binder.restoreCallingIdentity(origId);
4475 }
4476 }
4477 }
4478
4479 @Override
4480 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4481 CharSequence message) {
4482 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004483 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004484 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4485 }
4486 final long callingId = Binder.clearCallingIdentity();
4487 try {
4488 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004489 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004490 }
4491 } finally {
4492 Binder.restoreCallingIdentity(callingId);
4493 }
4494 }
4495
4496 @Override
4497 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004498 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004499 "cancelTaskWindowTransition()");
4500 final long ident = Binder.clearCallingIdentity();
4501 try {
4502 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004503 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004504 MATCH_TASK_IN_STACKS_ONLY);
4505 if (task == null) {
4506 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4507 return;
4508 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004509 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004510 }
4511 } finally {
4512 Binder.restoreCallingIdentity(ident);
4513 }
4514 }
4515
4516 @Override
4517 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004518 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004519 final long ident = Binder.clearCallingIdentity();
4520 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004521 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004522 } finally {
4523 Binder.restoreCallingIdentity(ident);
4524 }
4525 }
4526
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004527 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4528 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004529 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004530 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004531 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004532 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4533 if (task == null) {
4534 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4535 return null;
4536 }
4537 }
4538 // Don't call this while holding the lock as this operation might hit the disk.
4539 return task.getSnapshot(reducedResolution, restoreFromDisk);
4540 }
4541
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004542 @Override
4543 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4544 synchronized (mGlobalLock) {
4545 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4546 if (r == null) {
4547 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4548 + token);
4549 return;
4550 }
4551 final long origId = Binder.clearCallingIdentity();
4552 try {
4553 r.setDisablePreviewScreenshots(disable);
4554 } finally {
4555 Binder.restoreCallingIdentity(origId);
4556 }
4557 }
4558 }
4559
Riddle Hsu440f88b2019-11-06 22:17:35 +08004560 @Override
4561 public void invalidateHomeTaskSnapshot(IBinder token) {
4562 synchronized (mGlobalLock) {
4563 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4564 if (r == null || !r.isActivityTypeHome()) {
4565 return;
4566 }
4567 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4568 }
4569 }
4570
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004571 /** Return the user id of the last resumed activity. */
4572 @Override
4573 public @UserIdInt
4574 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004575 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004576 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4577 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004578 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004579 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004580 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004581 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004582 }
4583 }
4584
4585 @Override
4586 public void updateLockTaskFeatures(int userId, int flags) {
4587 final int callingUid = Binder.getCallingUid();
4588 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004589 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004590 "updateLockTaskFeatures()");
4591 }
4592 synchronized (mGlobalLock) {
4593 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4594 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004595 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004596 }
4597 }
4598
4599 @Override
4600 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4601 synchronized (mGlobalLock) {
4602 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4603 if (r == null) {
4604 return;
4605 }
4606 final long origId = Binder.clearCallingIdentity();
4607 try {
4608 r.setShowWhenLocked(showWhenLocked);
4609 } finally {
4610 Binder.restoreCallingIdentity(origId);
4611 }
4612 }
4613 }
4614
4615 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004616 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4617 synchronized (mGlobalLock) {
4618 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4619 if (r == null) {
4620 return;
4621 }
4622 final long origId = Binder.clearCallingIdentity();
4623 try {
4624 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4625 } finally {
4626 Binder.restoreCallingIdentity(origId);
4627 }
4628 }
4629 }
4630
4631 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004632 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4633 synchronized (mGlobalLock) {
4634 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4635 if (r == null) {
4636 return;
4637 }
4638 final long origId = Binder.clearCallingIdentity();
4639 try {
4640 r.setTurnScreenOn(turnScreenOn);
4641 } finally {
4642 Binder.restoreCallingIdentity(origId);
4643 }
4644 }
4645 }
4646
4647 @Override
4648 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004649 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004650 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004651 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004652 synchronized (mGlobalLock) {
4653 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4654 if (r == null) {
4655 return;
4656 }
4657 final long origId = Binder.clearCallingIdentity();
4658 try {
4659 r.registerRemoteAnimations(definition);
4660 } finally {
4661 Binder.restoreCallingIdentity(origId);
4662 }
4663 }
4664 }
4665
4666 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004667 public void unregisterRemoteAnimations(IBinder token) {
4668 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4669 "unregisterRemoteAnimations");
4670 synchronized (mGlobalLock) {
4671 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4672 if (r == null) {
4673 return;
4674 }
4675 final long origId = Binder.clearCallingIdentity();
4676 try {
4677 r.unregisterRemoteAnimations();
4678 } finally {
4679 Binder.restoreCallingIdentity(origId);
4680 }
4681 }
4682 }
4683
4684 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004685 public void registerRemoteAnimationForNextActivityStart(String packageName,
4686 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004687 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004688 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004689 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004690 synchronized (mGlobalLock) {
4691 final long origId = Binder.clearCallingIdentity();
4692 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004693 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004694 packageName, adapter);
4695 } finally {
4696 Binder.restoreCallingIdentity(origId);
4697 }
4698 }
4699 }
4700
Evan Rosky966759f2019-01-15 10:33:58 -08004701 @Override
4702 public void registerRemoteAnimationsForDisplay(int displayId,
4703 RemoteAnimationDefinition definition) {
4704 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4705 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004706 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004707 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004708 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004709 if (display == null) {
4710 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4711 return;
4712 }
4713 final long origId = Binder.clearCallingIdentity();
4714 try {
4715 display.mDisplayContent.registerRemoteAnimations(definition);
4716 } finally {
4717 Binder.restoreCallingIdentity(origId);
4718 }
4719 }
4720 }
4721
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004722 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4723 @Override
4724 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4725 synchronized (mGlobalLock) {
4726 final long origId = Binder.clearCallingIdentity();
4727 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004728 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004729 } finally {
4730 Binder.restoreCallingIdentity(origId);
4731 }
4732 }
4733 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004734
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004735 @Override
4736 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004737 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004738 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004739 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004740 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004741 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004742 }
4743 }
4744
4745 @Override
4746 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004747 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004748 != PERMISSION_GRANTED) {
4749 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4750 + Binder.getCallingPid()
4751 + ", uid=" + Binder.getCallingUid()
4752 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4753 Slog.w(TAG, msg);
4754 throw new SecurityException(msg);
4755 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004756 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004757 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004758 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004759 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004760 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004761 }
4762 }
4763
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004764 @Override
4765 public void stopAppSwitches() {
4766 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4767 synchronized (mGlobalLock) {
4768 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004769 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004770 mDidAppSwitch = false;
4771 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4772 }
4773 }
4774
4775 @Override
4776 public void resumeAppSwitches() {
4777 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4778 synchronized (mGlobalLock) {
4779 // Note that we don't execute any pending app switches... we will
4780 // let those wait until either the timeout, or the next start
4781 // activity request.
4782 mAppSwitchesAllowedTime = 0;
4783 }
4784 }
4785
Ricky Wai906af482019-06-03 17:25:28 +01004786 long getLastStopAppSwitchesTime() {
4787 return mLastStopAppSwitchesTime;
4788 }
4789
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004790 void onStartActivitySetDidAppSwitch() {
4791 if (mDidAppSwitch) {
4792 // This is the second allowed switch since we stopped switches, so now just generally
4793 // allow switches. Use case:
4794 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4795 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4796 // anyone to switch again).
4797 mAppSwitchesAllowedTime = 0;
4798 } else {
4799 mDidAppSwitch = true;
4800 }
4801 }
4802
4803 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004804 boolean shouldDisableNonVrUiLocked() {
4805 return mVrController.shouldDisableNonVrUiLocked();
4806 }
4807
Wale Ogunwale53783742018-09-16 10:21:51 -07004808 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004809 // 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 +00004810 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004811 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004812 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4813 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004814 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004815 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004816 }
4817 mH.post(() -> {
4818 if (!mVrController.onVrModeChanged(r)) {
4819 return;
4820 }
4821 synchronized (mGlobalLock) {
4822 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4823 mWindowManager.disableNonVrUi(disableNonVrUi);
4824 if (disableNonVrUi) {
4825 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4826 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004827 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004828 }
4829 }
4830 });
4831 }
4832
Wale Ogunwale53783742018-09-16 10:21:51 -07004833 @Override
4834 public int getPackageScreenCompatMode(String packageName) {
4835 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4836 synchronized (mGlobalLock) {
4837 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4838 }
4839 }
4840
4841 @Override
4842 public void setPackageScreenCompatMode(String packageName, int mode) {
4843 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4844 "setPackageScreenCompatMode");
4845 synchronized (mGlobalLock) {
4846 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4847 }
4848 }
4849
4850 @Override
4851 public boolean getPackageAskScreenCompat(String packageName) {
4852 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4853 synchronized (mGlobalLock) {
4854 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4855 }
4856 }
4857
4858 @Override
4859 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4860 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4861 "setPackageAskScreenCompat");
4862 synchronized (mGlobalLock) {
4863 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4864 }
4865 }
4866
Wale Ogunwale64258362018-10-16 15:13:37 -07004867 public static String relaunchReasonToString(int relaunchReason) {
4868 switch (relaunchReason) {
4869 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4870 return "window_resize";
4871 case RELAUNCH_REASON_FREE_RESIZE:
4872 return "free_resize";
4873 default:
4874 return null;
4875 }
4876 }
4877
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004878 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004879 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004880 }
4881
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004882 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004883 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004884 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4885 }
4886
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004887 boolean isKeyguardLocked() {
4888 return mKeyguardController.isKeyguardLocked();
4889 }
4890
Garfield Tan01548632018-11-27 10:15:48 -08004891 /**
4892 * Clears launch params for the given package.
4893 * @param packageNames the names of the packages of which the launch params are to be cleared
4894 */
4895 @Override
4896 public void clearLaunchParamsForPackages(List<String> packageNames) {
4897 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4898 "clearLaunchParamsForPackages");
4899 synchronized (mGlobalLock) {
4900 for (int i = 0; i < packageNames.size(); ++i) {
4901 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4902 }
4903 }
4904 }
4905
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004906 /**
4907 * Makes the display with the given id a single task instance display. I.e the display can only
4908 * contain one task.
4909 */
4910 @Override
4911 public void setDisplayToSingleTaskInstance(int displayId) {
4912 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4913 "setDisplayToSingleTaskInstance");
4914 final long origId = Binder.clearCallingIdentity();
4915 try {
Louis Chang677921f2019-12-06 16:44:24 +08004916 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004917 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004918 if (display != null) {
4919 display.setDisplayToSingleTaskInstance();
4920 }
4921 } finally {
4922 Binder.restoreCallingIdentity(origId);
4923 }
4924 }
4925
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004926 /**
4927 * Requests that an activity should enter picture-in-picture mode if possible.
4928 */
4929 @Override
4930 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4931 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4932 "requestPictureInPictureMode");
4933 final long origId = Binder.clearCallingIdentity();
4934 try {
4935 synchronized (mGlobalLock) {
4936 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4937 if (activity == null) {
4938 return;
4939 }
4940
4941 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4942 "requestPictureInPictureMode", /* beforeStopping */ false);
4943 if (!canEnterPictureInPicture) {
4944 throw new IllegalStateException(
4945 "Requested PIP on an activity that doesn't support it");
4946 }
4947
4948 try {
4949 final ClientTransaction transaction = ClientTransaction.obtain(
4950 activity.app.getThread(),
4951 activity.token);
4952 transaction.addCallback(EnterPipRequestedItem.obtain());
4953 getLifecycleManager().scheduleTransaction(transaction);
4954 } catch (Exception e) {
4955 Slog.w(TAG, "Failed to send enter pip requested item: "
4956 + activity.intent.getComponent(), e);
4957 }
4958 }
4959 } finally {
4960 Binder.restoreCallingIdentity(origId);
4961 }
4962 }
4963
Wale Ogunwale31913b52018-10-13 08:29:31 -07004964 void dumpLastANRLocked(PrintWriter pw) {
4965 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4966 if (mLastANRState == null) {
4967 pw.println(" <no ANR has occurred since boot>");
4968 } else {
4969 pw.println(mLastANRState);
4970 }
4971 }
4972
4973 void dumpLastANRTracesLocked(PrintWriter pw) {
4974 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4975
4976 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4977 if (ArrayUtils.isEmpty(files)) {
4978 pw.println(" <no ANR has occurred since boot>");
4979 return;
4980 }
4981 // Find the latest file.
4982 File latest = null;
4983 for (File f : files) {
4984 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4985 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004986 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004987 }
4988 pw.print("File: ");
4989 pw.print(latest.getName());
4990 pw.println();
4991 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4992 String line;
4993 while ((line = in.readLine()) != null) {
4994 pw.println(line);
4995 }
4996 } catch (IOException e) {
4997 pw.print("Unable to read: ");
4998 pw.print(e);
4999 pw.println();
5000 }
5001 }
5002
5003 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5004 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
5005 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
5006 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
5007 }
5008
5009 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5010 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5011 pw.println(header);
5012
Louis Chang149d5c82019-12-30 09:47:39 +08005013 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005014 dumpPackage);
5015 boolean needSep = printedAnything;
5016
5017 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08005018 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005019 " ResumedActivity: ");
5020 if (printed) {
5021 printedAnything = true;
5022 needSep = false;
5023 }
5024
5025 if (dumpPackage == null) {
5026 if (needSep) {
5027 pw.println();
5028 }
5029 printedAnything = true;
5030 mStackSupervisor.dump(pw, " ");
5031 }
5032
5033 if (!printedAnything) {
5034 pw.println(" (nothing)");
5035 }
5036 }
5037
5038 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005039 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005040 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005041 pw.println(" ");
5042 }
5043
5044 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5045 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5046 getActivityStartController().dump(pw, "", dumpPackage);
5047 }
5048
5049 /**
5050 * There are three things that cmd can be:
5051 * - a flattened component name that matches an existing activity
5052 * - the cmd arg isn't the flattened component name of an existing activity:
5053 * dump all activity whose component contains the cmd as a substring
5054 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005055 * <p>
5056 * The caller should not hold lock when calling this method because it will wait for the
5057 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005058 *
5059 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5060 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5061 */
5062 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5063 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5064 ArrayList<ActivityRecord> activities;
5065
5066 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005067 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005068 dumpFocusedStackOnly);
5069 }
5070
5071 if (activities.size() <= 0) {
5072 return false;
5073 }
5074
5075 String[] newArgs = new String[args.length - opti];
5076 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5077
Louis Changcdec0802019-11-11 11:45:07 +08005078 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005079 boolean needSep = false;
5080 for (int i = activities.size() - 1; i >= 0; i--) {
5081 ActivityRecord r = activities.get(i);
5082 if (needSep) {
5083 pw.println();
5084 }
5085 needSep = true;
5086 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005087 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005088 if (lastTask != task) {
5089 lastTask = task;
5090 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005091 pw.print(" id="); pw.print(lastTask.mTaskId);
5092 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005093 if (dumpAll) {
5094 lastTask.dump(pw, " ");
5095 }
5096 }
5097 }
5098 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5099 }
5100 return true;
5101 }
5102
5103 /**
5104 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5105 * there is a thread associated with the activity.
5106 */
5107 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5108 final ActivityRecord r, String[] args, boolean dumpAll) {
5109 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005110 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005111 synchronized (mGlobalLock) {
5112 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5113 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5114 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005115 if (r.hasProcess()) {
5116 pw.println(r.app.getPid());
5117 appThread = r.app.getThread();
5118 } else {
5119 pw.println("(not running)");
5120 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005121 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005122 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005123 }
5124 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005125 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005126 // flush anything that is already in the PrintWriter since the thread is going
5127 // to write to the file descriptor directly
5128 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005129 try (TransferPipe tp = new TransferPipe()) {
5130 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5131 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005132 } catch (IOException e) {
5133 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5134 } catch (RemoteException e) {
5135 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5136 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005137 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005138 }
5139
sanryhuang498e77e2018-12-06 14:57:01 +08005140 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5141 boolean testPssMode) {
5142 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5143 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5144 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005145 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005146 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5147 st.toString());
5148 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005149 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5150 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5151 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005152 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5153 testPssMode);
5154 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005155 }
5156
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005157 int getCurrentUserId() {
5158 return mAmInternal.getCurrentUserId();
5159 }
5160
5161 private void enforceNotIsolatedCaller(String caller) {
5162 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5163 throw new SecurityException("Isolated process not allowed to call " + caller);
5164 }
5165 }
5166
Wale Ogunwalef6733932018-06-27 05:14:34 -07005167 public Configuration getConfiguration() {
5168 Configuration ci;
5169 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005170 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005171 ci.userSetLocale = false;
5172 }
5173 return ci;
5174 }
5175
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005176 /**
5177 * Current global configuration information. Contains general settings for the entire system,
5178 * also corresponds to the merged configuration of the default display.
5179 */
5180 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005181 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005182 // while initializing process record for system, see {@link
5183 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005184 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005185 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005186 }
5187
5188 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5189 boolean initLocale) {
5190 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5191 }
5192
5193 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5194 boolean initLocale, boolean deferResume) {
5195 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5196 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5197 UserHandle.USER_NULL, deferResume);
5198 }
5199
Wale Ogunwale59507092018-10-29 09:00:30 -07005200 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005201 final long origId = Binder.clearCallingIdentity();
5202 try {
5203 synchronized (mGlobalLock) {
5204 updateConfigurationLocked(values, null, false, true, userId,
5205 false /* deferResume */);
5206 }
5207 } finally {
5208 Binder.restoreCallingIdentity(origId);
5209 }
5210 }
5211
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005212 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5213 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5214 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5215 deferResume, null /* result */);
5216 }
5217
5218 /**
5219 * Do either or both things: (1) change the current configuration, and (2)
5220 * make sure the given activity is running with the (now) current
5221 * configuration. Returns true if the activity has been left running, or
5222 * false if <var>starting</var> is being destroyed to match the new
5223 * configuration.
5224 *
5225 * @param userId is only used when persistent parameter is set to true to persist configuration
5226 * for that particular user
5227 */
5228 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5229 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5230 ActivityTaskManagerService.UpdateConfigurationResult result) {
5231 int changes = 0;
5232 boolean kept = true;
5233
Riddle Hsua0022cd2019-09-09 21:12:41 +08005234 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005235 try {
5236 if (values != null) {
5237 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5238 deferResume);
5239 }
5240
5241 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5242 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005243 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005244 }
5245
5246 if (result != null) {
5247 result.changes = changes;
5248 result.activityRelaunched = !kept;
5249 }
5250 return kept;
5251 }
5252
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005253 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005254 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005255 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005256
Louis Chang677921f2019-12-06 16:44:24 +08005257 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005258 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005259
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005260 mTempConfig.setTo(getGlobalConfiguration());
5261 final int changes = mTempConfig.updateFrom(values);
5262 if (changes == 0) {
5263 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5264 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5265 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5266 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005267 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005268 return 0;
5269 }
5270
5271 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5272 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005273 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005274 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005275 values.colorMode,
5276 values.densityDpi,
5277 values.fontScale,
5278 values.hardKeyboardHidden,
5279 values.keyboard,
5280 values.keyboardHidden,
5281 values.mcc,
5282 values.mnc,
5283 values.navigation,
5284 values.navigationHidden,
5285 values.orientation,
5286 values.screenHeightDp,
5287 values.screenLayout,
5288 values.screenWidthDp,
5289 values.smallestScreenWidthDp,
5290 values.touchscreen,
5291 values.uiMode);
5292
5293
5294 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5295 final LocaleList locales = values.getLocales();
5296 int bestLocaleIndex = 0;
5297 if (locales.size() > 1) {
5298 if (mSupportedSystemLocales == null) {
5299 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5300 }
5301 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5302 }
5303 SystemProperties.set("persist.sys.locale",
5304 locales.get(bestLocaleIndex).toLanguageTag());
5305 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005306
5307 final Message m = PooledLambda.obtainMessage(
5308 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5309 locales.get(bestLocaleIndex));
5310 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005311 }
5312
Yunfan Chen75157d72018-07-27 14:47:21 +09005313 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005314
5315 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005316 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005317
5318 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5319 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005320 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005321
5322 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005323 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005324
5325 AttributeCache ac = AttributeCache.instance();
5326 if (ac != null) {
5327 ac.updateConfiguration(mTempConfig);
5328 }
5329
5330 // Make sure all resources in our process are updated right now, so that anyone who is going
5331 // to retrieve resource values after we return will be sure to get the new ones. This is
5332 // especially important during boot, where the first config change needs to guarantee all
5333 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005334 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005335
5336 // We need another copy of global config because we're scheduling some calls instead of
5337 // running them in place. We need to be sure that object we send will be handled unchanged.
5338 final Configuration configCopy = new Configuration(mTempConfig);
5339 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005340 final Message msg = PooledLambda.obtainMessage(
5341 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5342 this, userId, configCopy);
5343 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005344 }
5345
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005346 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5347 for (int i = pidMap.size() - 1; i >= 0; i--) {
5348 final int pid = pidMap.keyAt(i);
5349 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005350 if (DEBUG_CONFIGURATION) {
5351 Slog.v(TAG_CONFIGURATION, "Update process config of "
5352 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005353 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005354 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005355 }
5356
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005357 final Message msg = PooledLambda.obtainMessage(
5358 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5359 mAmInternal, changes, initLocale);
5360 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005361
5362 // Override configuration of the default display duplicates global config, so we need to
5363 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005364 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005365 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005366
5367 return changes;
5368 }
5369
Riddle Hsua0022cd2019-09-09 21:12:41 +08005370 /** @see WindowSurfacePlacer#deferLayout */
5371 void deferWindowLayout() {
5372 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5373 // Reset the reasons at the first entrance because we only care about the changes in the
5374 // deferred scope.
5375 mLayoutReasons = 0;
5376 }
5377
5378 mWindowManager.mWindowPlacerLocked.deferLayout();
5379 }
5380
5381 /** @see WindowSurfacePlacer#continueLayout */
5382 void continueWindowLayout() {
5383 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5384 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5385 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5386 }
5387 }
5388
5389 /**
5390 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5391 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5392 * defer count is gone.
5393 */
5394 void addWindowLayoutReasons(@LayoutReason int reasons) {
5395 mLayoutReasons |= reasons;
5396 }
5397
Wale Ogunwalef6733932018-06-27 05:14:34 -07005398 private void updateEventDispatchingLocked(boolean booted) {
5399 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5400 }
5401
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005402 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5403 final ContentResolver resolver = mContext.getContentResolver();
5404 Settings.System.putConfigurationForUser(resolver, config, userId);
5405 }
5406
5407 private void sendLocaleToMountDaemonMsg(Locale l) {
5408 try {
5409 IBinder service = ServiceManager.getService("mount");
5410 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5411 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5412 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5413 } catch (RemoteException e) {
5414 Log.e(TAG, "Error storing locale for decryption UI", e);
5415 }
5416 }
5417
Alison Cichowlas3e340502018-08-07 17:15:01 -04005418 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5419 mStartActivitySources.remove(permissionToken);
5420 mExpiredStartAsCallerTokens.add(permissionToken);
5421 }
5422
5423 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5424 mExpiredStartAsCallerTokens.remove(permissionToken);
5425 }
5426
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005427 boolean isActivityStartsLoggingEnabled() {
5428 return mAmInternal.isActivityStartsLoggingEnabled();
5429 }
5430
Michal Karpinski8596ded2018-11-14 14:43:48 +00005431 boolean isBackgroundActivityStartsEnabled() {
5432 return mAmInternal.isBackgroundActivityStartsEnabled();
5433 }
5434
Wale Ogunwalef6733932018-06-27 05:14:34 -07005435 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005436 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005437 mWindowManager.enableScreenAfterBoot();
5438
5439 synchronized (mGlobalLock) {
5440 updateEventDispatchingLocked(booted);
5441 }
5442 }
5443
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005444 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5445 if (r == null || !r.hasProcess()) {
5446 return KEY_DISPATCHING_TIMEOUT_MS;
5447 }
5448 return getInputDispatchingTimeoutLocked(r.app);
5449 }
5450
5451 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005452 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005453 }
5454
Wale Ogunwalef6733932018-06-27 05:14:34 -07005455 /**
5456 * Decide based on the configuration whether we should show the ANR,
5457 * crash, etc dialogs. The idea is that if there is no affordance to
5458 * press the on-screen buttons, or the user experience would be more
5459 * greatly impacted than the crash itself, we shouldn't show the dialog.
5460 *
5461 * A thought: SystemUI might also want to get told about this, the Power
5462 * dialog / global actions also might want different behaviors.
5463 */
5464 private void updateShouldShowDialogsLocked(Configuration config) {
5465 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5466 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5467 && config.navigation == Configuration.NAVIGATION_NONAV);
5468 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5469 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5470 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5471 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5472 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5473 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5474 HIDE_ERROR_DIALOGS, 0) != 0;
5475 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5476 }
5477
5478 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5479 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5480 FONT_SCALE, 1.0f, userId);
5481
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005482 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005483 if (getGlobalConfiguration().fontScale == scaleFactor) {
5484 return;
5485 }
5486
5487 final Configuration configuration
5488 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5489 configuration.fontScale = scaleFactor;
5490 updatePersistentConfiguration(configuration, userId);
5491 }
5492 }
5493
5494 // Actually is sleeping or shutting down or whatever else in the future
5495 // is an inactive state.
5496 boolean isSleepingOrShuttingDownLocked() {
5497 return isSleepingLocked() || mShuttingDown;
5498 }
5499
5500 boolean isSleepingLocked() {
5501 return mSleeping;
5502 }
5503
Riddle Hsu16567132018-08-16 21:37:47 +08005504 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005505 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005506 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005507 if (task.isActivityTypeStandard()) {
5508 if (mCurAppTimeTracker != r.appTimeTracker) {
5509 // We are switching app tracking. Complete the current one.
5510 if (mCurAppTimeTracker != null) {
5511 mCurAppTimeTracker.stop();
5512 mH.obtainMessage(
5513 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005514 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005515 mCurAppTimeTracker = null;
5516 }
5517 if (r.appTimeTracker != null) {
5518 mCurAppTimeTracker = r.appTimeTracker;
5519 startTimeTrackingFocusedActivityLocked();
5520 }
5521 } else {
5522 startTimeTrackingFocusedActivityLocked();
5523 }
5524 } else {
5525 r.appTimeTracker = null;
5526 }
5527 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5528 // TODO: Probably not, because we don't want to resume voice on switching
5529 // back to this activity
5530 if (task.voiceInteractor != null) {
5531 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5532 } else {
5533 finishRunningVoiceLocked();
5534
5535 if (mLastResumedActivity != null) {
5536 final IVoiceInteractionSession session;
5537
Louis Changcdec0802019-11-11 11:45:07 +08005538 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005539 if (lastResumedActivityTask != null
5540 && lastResumedActivityTask.voiceSession != null) {
5541 session = lastResumedActivityTask.voiceSession;
5542 } else {
5543 session = mLastResumedActivity.voiceSession;
5544 }
5545
5546 if (session != null) {
5547 // We had been in a voice interaction session, but now focused has
5548 // move to something different. Just finish the session, we can't
5549 // return to it and retain the proper state and synchronization with
5550 // the voice interaction service.
5551 finishVoiceTask(session);
5552 }
5553 }
5554 }
5555
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005556 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5557 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005558 }
5559 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
5564 applyUpdateLockStateLocked(r);
5565 applyUpdateVrModeLocked(r);
5566
Jeff Changd136e772019-11-05 20:33:52 +08005567 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005568 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005569 r == null ? "NULL" : r.shortComponentName,
5570 reason);
5571 }
5572
5573 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5574 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005575 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005576 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005577 updateSleepIfNeededLocked();
5578 return token;
5579 }
5580 }
5581
5582 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005583 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005584 final boolean wasSleeping = mSleeping;
5585 boolean updateOomAdj = false;
5586
5587 if (!shouldSleep) {
5588 // If wasSleeping is true, we need to wake up activity manager state from when
5589 // we started sleeping. In either case, we need to apply the sleep tokens, which
5590 // will wake up stacks or put them to sleep as appropriate.
5591 if (wasSleeping) {
5592 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005593 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5594 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005595 startTimeTrackingFocusedActivityLocked();
5596 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005597 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005598 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5599 }
Louis Chang149d5c82019-12-30 09:47:39 +08005600 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005601 if (wasSleeping) {
5602 updateOomAdj = true;
5603 }
5604 } else if (!mSleeping && shouldSleep) {
5605 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005606 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5607 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005608 if (mCurAppTimeTracker != null) {
5609 mCurAppTimeTracker.stop();
5610 }
5611 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005612 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005613 mStackSupervisor.goingToSleepLocked();
5614 updateResumedAppTrace(null /* resumed */);
5615 updateOomAdj = true;
5616 }
5617 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005618 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005619 }
5620 }
5621
5622 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005623 mH.removeCallbacks(mUpdateOomAdjRunnable);
5624 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005625 }
5626
Wale Ogunwale53783742018-09-16 10:21:51 -07005627 void updateCpuStats() {
5628 mH.post(mAmInternal::updateCpuStats);
5629 }
5630
Hui Yu03d12402018-12-06 18:00:37 -08005631 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5632 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005633 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5634 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005635 mH.sendMessage(m);
5636 }
5637
Hui Yu03d12402018-12-06 18:00:37 -08005638 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005639 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005640 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005641 if (task != null) {
5642 final ActivityRecord rootActivity = task.getRootActivity();
5643 if (rootActivity != null) {
5644 taskRoot = rootActivity.mActivityComponent;
5645 }
5646 }
5647
Hui Yu03d12402018-12-06 18:00:37 -08005648 final Message m = PooledLambda.obtainMessage(
5649 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005650 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005651 mH.sendMessage(m);
5652 }
5653
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005654 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5655 String hostingType) {
5656 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005657 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5658 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005659 + activity.processName);
5660 }
5661 // Post message to start process to avoid possible deadlock of calling into AMS with the
5662 // ATMS lock held.
5663 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5664 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5665 isTop, hostingType, activity.intent.getComponent());
5666 mH.sendMessage(m);
5667 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005668 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005669 }
5670 }
5671
Wale Ogunwale53783742018-09-16 10:21:51 -07005672 void setBooting(boolean booting) {
5673 mAmInternal.setBooting(booting);
5674 }
5675
5676 boolean isBooting() {
5677 return mAmInternal.isBooting();
5678 }
5679
5680 void setBooted(boolean booted) {
5681 mAmInternal.setBooted(booted);
5682 }
5683
5684 boolean isBooted() {
5685 return mAmInternal.isBooted();
5686 }
5687
5688 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5689 mH.post(() -> {
5690 if (finishBooting) {
5691 mAmInternal.finishBooting();
5692 }
5693 if (enableScreen) {
5694 mInternal.enableScreenAfterBoot(isBooted());
5695 }
5696 });
5697 }
5698
5699 void setHeavyWeightProcess(ActivityRecord root) {
5700 mHeavyWeightProcess = root.app;
5701 final Message m = PooledLambda.obtainMessage(
5702 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005703 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005704 mH.sendMessage(m);
5705 }
5706
5707 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5708 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5709 return;
5710 }
5711
5712 mHeavyWeightProcess = null;
5713 final Message m = PooledLambda.obtainMessage(
5714 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5715 proc.mUserId);
5716 mH.sendMessage(m);
5717 }
5718
5719 private void cancelHeavyWeightProcessNotification(int userId) {
5720 final INotificationManager inm = NotificationManager.getService();
5721 if (inm == null) {
5722 return;
5723 }
5724 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005725 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005726 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5727 } catch (RuntimeException e) {
5728 Slog.w(TAG, "Error canceling notification for service", e);
5729 } catch (RemoteException e) {
5730 }
5731
5732 }
5733
5734 private void postHeavyWeightProcessNotification(
5735 WindowProcessController proc, Intent intent, int userId) {
5736 if (proc == null) {
5737 return;
5738 }
5739
5740 final INotificationManager inm = NotificationManager.getService();
5741 if (inm == null) {
5742 return;
5743 }
5744
5745 try {
5746 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5747 String text = mContext.getString(R.string.heavy_weight_notification,
5748 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5749 Notification notification =
5750 new Notification.Builder(context,
5751 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5752 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5753 .setWhen(0)
5754 .setOngoing(true)
5755 .setTicker(text)
5756 .setColor(mContext.getColor(
5757 com.android.internal.R.color.system_notification_accent_color))
5758 .setContentTitle(text)
5759 .setContentText(
5760 mContext.getText(R.string.heavy_weight_notification_detail))
5761 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5762 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5763 new UserHandle(userId)))
5764 .build();
5765 try {
5766 inm.enqueueNotificationWithTag("android", "android", null,
5767 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5768 } catch (RuntimeException e) {
5769 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5770 } catch (RemoteException e) {
5771 }
5772 } catch (PackageManager.NameNotFoundException e) {
5773 Slog.w(TAG, "Unable to create context for heavy notification", e);
5774 }
5775
5776 }
5777
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005778 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5779 IBinder token, String resultWho, int requestCode, Intent[] intents,
5780 String[] resolvedTypes, int flags, Bundle bOptions) {
5781
5782 ActivityRecord activity = null;
5783 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5784 activity = ActivityRecord.isInStackLocked(token);
5785 if (activity == null) {
5786 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5787 return null;
5788 }
5789 if (activity.finishing) {
5790 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5791 return null;
5792 }
5793 }
5794
5795 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5796 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5797 bOptions);
5798 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5799 if (noCreate) {
5800 return rec;
5801 }
5802 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5803 if (activity.pendingResults == null) {
5804 activity.pendingResults = new HashSet<>();
5805 }
5806 activity.pendingResults.add(rec.ref);
5807 }
5808 return rec;
5809 }
5810
Andrii Kulian52d255c2018-07-13 11:32:19 -07005811 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005812 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005813 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005814 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5815 mCurAppTimeTracker.start(resumedActivity.packageName);
5816 }
5817 }
5818
5819 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5820 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005821 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005822 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5823 }
5824 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005825 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005826 constructResumedTraceName(resumed.packageName), 0);
5827 }
5828 mTracedResumedActivity = resumed;
5829 }
5830
5831 private String constructResumedTraceName(String packageName) {
5832 return "focused app: " + packageName;
5833 }
5834
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005835 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005836 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005837 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005838 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005839 // mainStack is null during startup.
5840 if (mainStack != null) {
5841 if (changes != 0 && starting == null) {
5842 // If the configuration changed, and the caller is not already
5843 // in the process of starting an activity, then find the top
5844 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005845 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005846 }
5847
5848 if (starting != null) {
5849 kept = starting.ensureActivityConfiguration(changes,
5850 false /* preserveWindow */);
5851 // And we need to make sure at this point that all other activities
5852 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005853 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005854 !PRESERVE_WINDOWS);
5855 }
5856 }
5857
5858 return kept;
5859 }
5860
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005861 void scheduleAppGcsLocked() {
5862 mH.post(() -> mAmInternal.scheduleAppGcs());
5863 }
5864
Wale Ogunwale53783742018-09-16 10:21:51 -07005865 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5866 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5867 }
5868
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005869 /**
5870 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5871 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5872 * on demand.
5873 */
5874 IPackageManager getPackageManager() {
5875 return AppGlobals.getPackageManager();
5876 }
5877
5878 PackageManagerInternal getPackageManagerInternalLocked() {
5879 if (mPmInternal == null) {
5880 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5881 }
5882 return mPmInternal;
5883 }
5884
Hai Zhangf4da9be2019-05-01 13:46:06 +08005885 PermissionPolicyInternal getPermissionPolicyInternal() {
5886 if (mPermissionPolicyInternal == null) {
5887 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5888 }
5889 return mPermissionPolicyInternal;
5890 }
5891
Wale Ogunwale008163e2018-07-23 23:11:08 -07005892 AppWarnings getAppWarningsLocked() {
5893 return mAppWarnings;
5894 }
5895
Wale Ogunwale214f3482018-10-04 11:00:47 -07005896 Intent getHomeIntent() {
5897 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5898 intent.setComponent(mTopComponent);
5899 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5900 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5901 intent.addCategory(Intent.CATEGORY_HOME);
5902 }
5903 return intent;
5904 }
5905
Chilun2ef71f72018-11-16 17:57:15 +08005906 /**
5907 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5908 * activities.
5909 *
5910 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5911 * component defined in config_secondaryHomeComponent.
5912 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5913 */
5914 Intent getSecondaryHomeIntent(String preferredPackage) {
5915 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005916 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5917 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5918 if (preferredPackage == null || useSystemProvidedLauncher) {
5919 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005920 final String secondaryHomeComponent = mContext.getResources().getString(
5921 com.android.internal.R.string.config_secondaryHomeComponent);
5922 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5923 } else {
5924 intent.setPackage(preferredPackage);
5925 }
5926 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5927 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5928 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5929 }
5930 return intent;
5931 }
5932
Wale Ogunwale214f3482018-10-04 11:00:47 -07005933 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5934 if (info == null) return null;
5935 ApplicationInfo newInfo = new ApplicationInfo(info);
5936 newInfo.initForUser(userId);
5937 return newInfo;
5938 }
5939
Wale Ogunwale9c103022018-10-18 07:44:54 -07005940 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005941 if (uid == SYSTEM_UID) {
5942 // The system gets to run in any process. If there are multiple processes with the same
5943 // uid, just pick the first (this should never happen).
5944 final SparseArray<WindowProcessController> procs =
5945 mProcessNames.getMap().get(processName);
5946 if (procs == null) return null;
5947 final int procCount = procs.size();
5948 for (int i = 0; i < procCount; i++) {
5949 final int procUid = procs.keyAt(i);
5950 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5951 // Don't use an app process or different user process for system component.
5952 continue;
5953 }
5954 return procs.valueAt(i);
5955 }
5956 }
5957
5958 return mProcessNames.get(processName, uid);
5959 }
5960
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005961 WindowProcessController getProcessController(IApplicationThread thread) {
5962 if (thread == null) {
5963 return null;
5964 }
5965
5966 final IBinder threadBinder = thread.asBinder();
5967 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5968 for (int i = pmap.size()-1; i >= 0; i--) {
5969 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5970 for (int j = procs.size() - 1; j >= 0; j--) {
5971 final WindowProcessController proc = procs.valueAt(j);
5972 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5973 return proc;
5974 }
5975 }
5976 }
5977
5978 return null;
5979 }
5980
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005981 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005982 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005983 if (proc == null) return null;
5984 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5985 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005986 }
5987 return null;
5988 }
5989
Riddle Hsua0536432019-02-16 00:38:59 +08005990 int getUidState(int uid) {
5991 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005992 }
5993
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005994 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005995 // A uid is considered to be foreground if it has a visible non-toast window.
5996 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005997 }
5998
Ricky Wai96f5c352019-04-10 18:40:17 +01005999 boolean isDeviceOwner(int uid) {
6000 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006001 }
6002
Ricky Wai96f5c352019-04-10 18:40:17 +01006003 void setDeviceOwnerUid(int uid) {
6004 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006005 }
6006
Wale Ogunwale9de19442018-10-18 19:05:03 -07006007 /**
6008 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6009 * the whitelist
6010 */
6011 String getPendingTempWhitelistTagForUidLocked(int uid) {
6012 return mPendingTempWhitelist.get(uid);
6013 }
6014
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006015 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6016 if (true || Build.IS_USER) {
6017 return;
6018 }
6019
6020 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6021 StrictMode.allowThreadDiskWrites();
6022 try {
6023 File tracesDir = new File("/data/anr");
6024 File tracesFile = null;
6025 try {
6026 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6027
6028 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006029 String timeString =
6030 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6031 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006032 sb.append(": ");
6033 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6034 sb.append(" since ");
6035 sb.append(msg);
6036 FileOutputStream fos = new FileOutputStream(tracesFile);
6037 fos.write(sb.toString().getBytes());
6038 if (app == null) {
6039 fos.write("\n*** No application process!".getBytes());
6040 }
6041 fos.close();
6042 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6043 } catch (IOException e) {
6044 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6045 return;
6046 }
6047
6048 if (app != null && app.getPid() > 0) {
6049 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6050 firstPids.add(app.getPid());
6051 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6052 }
6053
6054 File lastTracesFile = null;
6055 File curTracesFile = null;
6056 for (int i=9; i>=0; i--) {
6057 String name = String.format(Locale.US, "slow%02d.txt", i);
6058 curTracesFile = new File(tracesDir, name);
6059 if (curTracesFile.exists()) {
6060 if (lastTracesFile != null) {
6061 curTracesFile.renameTo(lastTracesFile);
6062 } else {
6063 curTracesFile.delete();
6064 }
6065 }
6066 lastTracesFile = curTracesFile;
6067 }
6068 tracesFile.renameTo(curTracesFile);
6069 } finally {
6070 StrictMode.setThreadPolicy(oldPolicy);
6071 }
6072 }
6073
Michal Karpinskida34cd42019-04-02 19:46:52 +01006074 boolean isAssociatedCompanionApp(int userId, int uid) {
6075 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6076 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006077 return false;
6078 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006079 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006080 }
6081
Issei Suzuki734bc942019-06-05 13:59:52 +02006082 void notifySingleTaskDisplayEmpty(int displayId) {
6083 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6084 }
6085
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006086 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006087 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006088
6089
Wale Ogunwale98875612018-10-12 07:53:02 -07006090 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6091 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006092
Riddle Hsud93a6c42018-11-29 21:50:06 +08006093 H(Looper looper) {
6094 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006095 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006096
6097 @Override
6098 public void handleMessage(Message msg) {
6099 switch (msg.what) {
6100 case REPORT_TIME_TRACKER_MSG: {
6101 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6102 tracker.deliverResult(mContext);
6103 } break;
6104 }
6105 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006106 }
6107
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006108 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006109 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006110
6111 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006112 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006113 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006114
6115 @Override
6116 public void handleMessage(Message msg) {
6117 switch (msg.what) {
6118 case DISMISS_DIALOG_UI_MSG: {
6119 final Dialog d = (Dialog) msg.obj;
6120 d.dismiss();
6121 break;
6122 }
6123 }
6124 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006125 }
6126
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006127 final class LocalService extends ActivityTaskManagerInternal {
6128 @Override
6129 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006130 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006131 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006132 }
6133
6134 @Override
6135 public ComponentName getHomeActivityForUser(int userId) {
6136 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006137 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006138 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006139 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006140 }
6141 }
6142
6143 @Override
6144 public void onLocalVoiceInteractionStarted(IBinder activity,
6145 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6146 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006147 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006148 }
6149 }
6150
6151 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006152 public void notifySingleTaskDisplayDrawn(int displayId) {
6153 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6154 }
6155
6156 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006157 public void notifyAppTransitionFinished() {
6158 synchronized (mGlobalLock) {
6159 mStackSupervisor.notifyAppTransitionDone();
6160 }
6161 }
6162
6163 @Override
6164 public void notifyAppTransitionCancelled() {
6165 synchronized (mGlobalLock) {
6166 mStackSupervisor.notifyAppTransitionDone();
6167 }
6168 }
6169
6170 @Override
6171 public List<IBinder> getTopVisibleActivities() {
6172 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006173 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006174 }
6175 }
6176
6177 @Override
6178 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6179 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006180 mRootWindowContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006181 }
6182 }
6183
6184 @Override
6185 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6186 Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006187 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006188 final String[] resolvedTypes = new String[intents.length];
6189
6190 // UID of the package on user userId.
6191 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6192 // packageUid may not be initialized.
6193 int packageUid = 0;
6194 final long ident = Binder.clearCallingIdentity();
6195
6196 try {
6197 for (int i = 0; i < intents.length; i++) {
6198 resolvedTypes[i] =
6199 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6200 }
6201
6202 packageUid = AppGlobals.getPackageManager().getPackageUid(
6203 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6204 } catch (RemoteException e) {
6205 // Shouldn't happen.
6206 } finally {
6207 Binder.restoreCallingIdentity(ident);
6208 }
6209
Riddle Hsu591bf612019-02-14 17:55:31 +08006210 return getActivityStartController().startActivitiesInPackage(
6211 packageUid, packageName,
6212 intents, resolvedTypes, null /* resultTo */,
6213 SafeActivityOptions.fromBundle(bOptions), userId,
6214 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6215 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006216 }
6217
6218 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006219 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6220 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6221 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6222 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006223 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006224 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006225 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006226 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6227 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6228 userId, validateIncomingUser, originatingPendingIntent,
6229 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006230 }
6231 }
6232
6233 @Override
6234 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6235 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6236 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006237 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006238 PendingIntentRecord originatingPendingIntent,
6239 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006240 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006241 synchronized (mGlobalLock) {
6242 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6243 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6244 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006245 validateIncomingUser, originatingPendingIntent,
6246 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006247 }
6248 }
6249
6250 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006251 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6252 Intent intent, Bundle options, int userId) {
6253 return ActivityTaskManagerService.this.startActivityAsUser(
6254 caller, callerPacakge, intent,
6255 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6256 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6257 false /*validateIncomingUser*/);
6258 }
6259
6260 @Override
lumark588a3e82018-07-20 18:53:54 +08006261 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006262 synchronized (mGlobalLock) {
6263
6264 // We might change the visibilities here, so prepare an empty app transition which
6265 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006266 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006267 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006268 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006269 return;
6270 }
Louis Chang677921f2019-12-06 16:44:24 +08006271 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006272 final boolean wasTransitionSet =
6273 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006274 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006275 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006276 }
Louis Chang149d5c82019-12-30 09:47:39 +08006277 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006278
6279 // If there was a transition set already we don't want to interfere with it as we
6280 // might be starting it too early.
6281 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006282 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006283 }
6284 }
6285 if (callback != null) {
6286 callback.run();
6287 }
6288 }
6289
6290 @Override
6291 public void notifyKeyguardTrustedChanged() {
6292 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006293 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006294 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006295 }
6296 }
6297 }
6298
6299 /**
6300 * Called after virtual display Id is updated by
6301 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6302 * {@param vrVr2dDisplayId}.
6303 */
6304 @Override
6305 public void setVr2dDisplayId(int vr2dDisplayId) {
6306 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6307 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006308 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006309 }
6310 }
6311
6312 @Override
6313 public void setFocusedActivity(IBinder token) {
6314 synchronized (mGlobalLock) {
6315 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6316 if (r == null) {
6317 throw new IllegalArgumentException(
6318 "setFocusedActivity: No activity record matching token=" + token);
6319 }
Louis Chang19443452018-10-09 12:10:21 +08006320 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006321 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006322 }
6323 }
6324 }
6325
6326 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006327 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006328 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006329 }
6330
6331 @Override
6332 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006333 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006334 }
6335
6336 @Override
6337 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006338 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006339 }
6340
6341 @Override
6342 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6343 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6344 }
6345
6346 @Override
6347 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006348 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006349 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006350
6351 @Override
6352 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6353 synchronized (mGlobalLock) {
6354 mActiveVoiceInteractionServiceComponent = component;
6355 }
6356 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006357
6358 @Override
6359 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6360 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6361 return;
6362 }
6363 synchronized (mGlobalLock) {
6364 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6365 if (types == null) {
6366 if (uid < 0) {
6367 return;
6368 }
6369 types = new ArrayMap<>();
6370 mAllowAppSwitchUids.put(userId, types);
6371 }
6372 if (uid < 0) {
6373 types.remove(type);
6374 } else {
6375 types.put(type, uid);
6376 }
6377 }
6378 }
6379
6380 @Override
6381 public void onUserStopped(int userId) {
6382 synchronized (mGlobalLock) {
6383 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6384 mAllowAppSwitchUids.remove(userId);
6385 }
6386 }
6387
6388 @Override
6389 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6390 synchronized (mGlobalLock) {
6391 return ActivityTaskManagerService.this.isGetTasksAllowed(
6392 caller, callingPid, callingUid);
6393 }
6394 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006395
Riddle Hsua0536432019-02-16 00:38:59 +08006396 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006397 @Override
6398 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006399 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006400 mProcessNames.put(proc.mName, proc.mUid, proc);
6401 }
6402 }
6403
Riddle Hsua0536432019-02-16 00:38:59 +08006404 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006405 @Override
6406 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006407 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006408 mProcessNames.remove(name, uid);
6409 }
6410 }
6411
Riddle Hsua0536432019-02-16 00:38:59 +08006412 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006413 @Override
6414 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006415 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006416 if (proc == mHomeProcess) {
6417 mHomeProcess = null;
6418 }
6419 if (proc == mPreviousProcess) {
6420 mPreviousProcess = null;
6421 }
6422 }
6423 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006424
Riddle Hsua0536432019-02-16 00:38:59 +08006425 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006426 @Override
6427 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006428 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006429 return mTopProcessState;
6430 }
6431 }
6432
Riddle Hsua0536432019-02-16 00:38:59 +08006433 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006434 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006435 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006436 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006437 return proc == mHeavyWeightProcess;
6438 }
6439 }
6440
Riddle Hsua0536432019-02-16 00:38:59 +08006441 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006442 @Override
6443 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006444 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006445 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6446 }
6447 }
6448
6449 @Override
6450 public void finishHeavyWeightApp() {
6451 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006452 if (mHeavyWeightProcess != null) {
6453 mHeavyWeightProcess.finishActivities();
6454 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006455 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6456 mHeavyWeightProcess);
6457 }
6458 }
6459
Riddle Hsua0536432019-02-16 00:38:59 +08006460 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006461 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006462 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006463 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006464 return isSleepingLocked();
6465 }
6466 }
6467
6468 @Override
6469 public boolean isShuttingDown() {
6470 synchronized (mGlobalLock) {
6471 return mShuttingDown;
6472 }
6473 }
6474
6475 @Override
6476 public boolean shuttingDown(boolean booted, int timeout) {
6477 synchronized (mGlobalLock) {
6478 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006479 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006480 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006481 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006482 return mStackSupervisor.shutdownLocked(timeout);
6483 }
6484 }
6485
6486 @Override
6487 public void enableScreenAfterBoot(boolean booted) {
6488 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006489 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006490 mWindowManager.enableScreenAfterBoot();
6491 updateEventDispatchingLocked(booted);
6492 }
6493 }
6494
6495 @Override
6496 public boolean showStrictModeViolationDialog() {
6497 synchronized (mGlobalLock) {
6498 return mShowDialogs && !mSleeping && !mShuttingDown;
6499 }
6500 }
6501
6502 @Override
6503 public void showSystemReadyErrorDialogsIfNeeded() {
6504 synchronized (mGlobalLock) {
6505 try {
6506 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6507 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6508 + " data partition or your device will be unstable.");
6509 mUiHandler.post(() -> {
6510 if (mShowDialogs) {
6511 AlertDialog d = new BaseErrorDialog(mUiContext);
6512 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6513 d.setCancelable(false);
6514 d.setTitle(mUiContext.getText(R.string.android_system_label));
6515 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6516 d.setButton(DialogInterface.BUTTON_POSITIVE,
6517 mUiContext.getText(R.string.ok),
6518 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6519 d.show();
6520 }
6521 });
6522 }
6523 } catch (RemoteException e) {
6524 }
6525
6526 if (!Build.isBuildConsistent()) {
6527 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6528 mUiHandler.post(() -> {
6529 if (mShowDialogs) {
6530 AlertDialog d = new BaseErrorDialog(mUiContext);
6531 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6532 d.setCancelable(false);
6533 d.setTitle(mUiContext.getText(R.string.android_system_label));
6534 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6535 d.setButton(DialogInterface.BUTTON_POSITIVE,
6536 mUiContext.getText(R.string.ok),
6537 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6538 d.show();
6539 }
6540 });
6541 }
6542 }
6543 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006544
6545 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006546 public void onProcessMapped(int pid, WindowProcessController proc) {
6547 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006548 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006549 }
6550 }
6551
6552 @Override
6553 public void onProcessUnMapped(int pid) {
6554 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006555 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006556 }
6557 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006558
6559 @Override
6560 public void onPackageDataCleared(String name) {
6561 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006562 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006563 mAppWarnings.onPackageDataCleared(name);
6564 }
6565 }
6566
6567 @Override
6568 public void onPackageUninstalled(String name) {
6569 synchronized (mGlobalLock) {
6570 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006571 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006572 }
6573 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006574
6575 @Override
6576 public void onPackageAdded(String name, boolean replacing) {
6577 synchronized (mGlobalLock) {
6578 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6579 }
6580 }
6581
6582 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006583 public void onPackageReplaced(ApplicationInfo aInfo) {
6584 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006585 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006586 }
6587 }
6588
6589 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006590 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6591 synchronized (mGlobalLock) {
6592 return compatibilityInfoForPackageLocked(ai);
6593 }
6594 }
6595
Yunfan Chen75157d72018-07-27 14:47:21 +09006596 /**
6597 * Set the corresponding display information for the process global configuration. To be
6598 * called when we need to show IME on a different display.
6599 *
6600 * @param pid The process id associated with the IME window.
6601 * @param displayId The ID of the display showing the IME.
6602 */
6603 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006604 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006605 // Don't update process-level configuration for Multi-Client IME process since other
6606 // IMEs on other displays will also receive this configuration change due to IME
6607 // services use the same application config/context.
6608 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006609
Yunfan Chen75157d72018-07-27 14:47:21 +09006610 if (pid == MY_PID || pid < 0) {
6611 if (DEBUG_CONFIGURATION) {
6612 Slog.w(TAG,
6613 "Trying to update display configuration for system/invalid process.");
6614 }
6615 return;
6616 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006617 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006618 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006619 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006620 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006621 // Call might come when display is not yet added or has been removed.
6622 if (DEBUG_CONFIGURATION) {
6623 Slog.w(TAG, "Trying to update display configuration for non-existing "
6624 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006625 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006626 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006627 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006628 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006629 if (process == null) {
6630 if (DEBUG_CONFIGURATION) {
6631 Slog.w(TAG, "Trying to update display configuration for invalid "
6632 + "process, pid=" + pid);
6633 }
6634 return;
6635 }
lumarkddc77fb2019-06-27 22:22:23 +08006636 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006637 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006638 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006639 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006640
6641 @Override
6642 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006643 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006644 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006645 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006646 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006647 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006648 }
6649 }
6650 }
6651
6652 @Override
6653 public void clearPendingResultForActivity(IBinder activityToken,
6654 WeakReference<PendingIntentRecord> pir) {
6655 synchronized (mGlobalLock) {
6656 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6657 if (r != null && r.pendingResults != null) {
6658 r.pendingResults.remove(pir);
6659 }
6660 }
6661 }
6662
6663 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006664 public ActivityTokens getTopActivityForTask(int taskId) {
6665 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006666 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006667 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006668 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6669 + " Requested task not found");
6670 return null;
6671 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006672 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006673 if (activity == null) {
6674 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6675 + " Requested activity not found");
6676 return null;
6677 }
6678 if (!activity.attachedToProcess()) {
6679 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6680 + activity);
6681 return null;
6682 }
6683 return new ActivityTokens(activity.appToken, activity.assistToken,
6684 activity.app.getThread());
6685 }
6686 }
6687
6688 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006689 public IIntentSender getIntentSender(int type, String packageName,
6690 int callingUid, int userId, IBinder token, String resultWho,
6691 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6692 Bundle bOptions) {
6693 synchronized (mGlobalLock) {
6694 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6695 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6696 }
6697 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006698
6699 @Override
6700 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6701 synchronized (mGlobalLock) {
6702 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6703 if (r == null) {
6704 return null;
6705 }
6706 if (r.mServiceConnectionsHolder == null) {
6707 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6708 ActivityTaskManagerService.this, r);
6709 }
6710
6711 return r.mServiceConnectionsHolder;
6712 }
6713 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006714
6715 @Override
6716 public Intent getHomeIntent() {
6717 synchronized (mGlobalLock) {
6718 return ActivityTaskManagerService.this.getHomeIntent();
6719 }
6720 }
6721
6722 @Override
6723 public boolean startHomeActivity(int userId, String reason) {
6724 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006725 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006726 }
6727 }
6728
6729 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006730 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006731 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006732 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006733 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006734 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006735 }
Chilun8b1f1be2019-03-13 17:14:36 +08006736 }
6737
6738 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006739 public boolean startHomeOnAllDisplays(int userId, String reason) {
6740 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006741 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006742 }
6743 }
6744
Riddle Hsua0536432019-02-16 00:38:59 +08006745 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006746 @Override
6747 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006748 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006749 if (mFactoryTest == FACTORY_TEST_OFF) {
6750 return false;
6751 }
6752 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6753 && wpc.mName.equals(mTopComponent.getPackageName())) {
6754 return true;
6755 }
6756 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6757 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6758 }
6759 }
6760
6761 @Override
6762 public void updateTopComponentForFactoryTest() {
6763 synchronized (mGlobalLock) {
6764 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6765 return;
6766 }
6767 final ResolveInfo ri = mContext.getPackageManager()
6768 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6769 final CharSequence errorMsg;
6770 if (ri != null) {
6771 final ActivityInfo ai = ri.activityInfo;
6772 final ApplicationInfo app = ai.applicationInfo;
6773 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6774 mTopAction = Intent.ACTION_FACTORY_TEST;
6775 mTopData = null;
6776 mTopComponent = new ComponentName(app.packageName, ai.name);
6777 errorMsg = null;
6778 } else {
6779 errorMsg = mContext.getResources().getText(
6780 com.android.internal.R.string.factorytest_not_system);
6781 }
6782 } else {
6783 errorMsg = mContext.getResources().getText(
6784 com.android.internal.R.string.factorytest_no_action);
6785 }
6786 if (errorMsg == null) {
6787 return;
6788 }
6789
6790 mTopAction = null;
6791 mTopData = null;
6792 mTopComponent = null;
6793 mUiHandler.post(() -> {
6794 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6795 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006796 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006797 });
6798 }
6799 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006800
Riddle Hsua0536432019-02-16 00:38:59 +08006801 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006802 @Override
6803 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6804 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006805 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006807 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006808
6809 wpc.clearRecentTasks();
6810 wpc.clearActivities();
6811
6812 if (wpc.isInstrumenting()) {
6813 finishInstrumentationCallback.run();
6814 }
6815
Jorim Jaggid0752812018-10-16 16:07:20 +02006816 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006817 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006818 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006819 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006820 // If there was nothing to resume, and we are not already restarting
6821 // this process, but there is a visible activity that is hosted by the
6822 // process...then make sure all visible activities are running, taking
6823 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006824 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006825 !PRESERVE_WINDOWS);
6826 }
6827 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006828 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006829 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006830 }
6831 }
6832 }
6833
6834 @Override
6835 public void closeSystemDialogs(String reason) {
6836 enforceNotIsolatedCaller("closeSystemDialogs");
6837
6838 final int pid = Binder.getCallingPid();
6839 final int uid = Binder.getCallingUid();
6840 final long origId = Binder.clearCallingIdentity();
6841 try {
6842 synchronized (mGlobalLock) {
6843 // Only allow this from foreground processes, so that background
6844 // applications can't abuse it to prevent system UI from being shown.
6845 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006846 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006847 if (!proc.isPerceptible()) {
6848 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6849 + " from background process " + proc);
6850 return;
6851 }
6852 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006853 mWindowManager.closeSystemDialogs(reason);
6854
Louis Chang149d5c82019-12-30 09:47:39 +08006855 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006856 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006857 // Call into AM outside the synchronized block.
6858 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006859 } finally {
6860 Binder.restoreCallingIdentity(origId);
6861 }
6862 }
6863
6864 @Override
6865 public void cleanupDisabledPackageComponents(
6866 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6867 synchronized (mGlobalLock) {
6868 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006869 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006870 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006871 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006872 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006873 }
6874
6875 // Clean-up disabled tasks
6876 getRecentTasks().cleanupDisabledPackageTasksLocked(
6877 packageName, disabledClasses, userId);
6878 }
6879 }
6880
6881 @Override
6882 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6883 int userId) {
6884 synchronized (mGlobalLock) {
6885
6886 boolean didSomething =
6887 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006888 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006889 null, doit, evenPersistent, userId);
6890 return didSomething;
6891 }
6892 }
6893
6894 @Override
6895 public void resumeTopActivities(boolean scheduleIdle) {
6896 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006897 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006898 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006899 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006900 }
6901 }
6902 }
6903
Riddle Hsua0536432019-02-16 00:38:59 +08006904 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006905 @Override
6906 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006907 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006908 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6909 }
6910 }
6911
Riddle Hsua0536432019-02-16 00:38:59 +08006912 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006913 @Override
6914 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006915 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006916 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6917 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6918 }
6919 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006920 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006921 } finally {
6922 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6923 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006924 }
6925 }
6926
6927 @Override
6928 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6929 try {
6930 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6931 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6932 }
6933 } catch (RemoteException ex) {
6934 throw new SecurityException("Fail to check is caller a privileged app", ex);
6935 }
6936
6937 synchronized (mGlobalLock) {
6938 final long ident = Binder.clearCallingIdentity();
6939 try {
6940 if (mAmInternal.shouldConfirmCredentials(userId)) {
6941 if (mKeyguardController.isKeyguardLocked()) {
6942 // Showing launcher to avoid user entering credential twice.
6943 startHomeActivity(currentUserId, "notifyLockedProfile");
6944 }
Louis Chang149d5c82019-12-30 09:47:39 +08006945 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006946 }
6947 } finally {
6948 Binder.restoreCallingIdentity(ident);
6949 }
6950 }
6951 }
6952
6953 @Override
6954 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6955 mAmInternal.enforceCallingPermission(
6956 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6957
6958 synchronized (mGlobalLock) {
6959 final long ident = Binder.clearCallingIdentity();
6960 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006961 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6962 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006963 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006964 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6965 UserHandle.CURRENT);
6966 } finally {
6967 Binder.restoreCallingIdentity(ident);
6968 }
6969 }
6970 }
6971
6972 @Override
6973 public void writeActivitiesToProto(ProtoOutputStream proto) {
6974 synchronized (mGlobalLock) {
6975 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006976 mRootWindowContainer.dumpDebug(
6977 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006978 }
6979 }
6980
6981 @Override
6982 public void saveANRState(String reason) {
6983 synchronized (mGlobalLock) {
6984 final StringWriter sw = new StringWriter();
6985 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6986 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6987 if (reason != null) {
6988 pw.println(" Reason: " + reason);
6989 }
6990 pw.println();
6991 getActivityStartController().dump(pw, " ", null);
6992 pw.println();
6993 pw.println("-------------------------------------------------------------------------------");
6994 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6995 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6996 "" /* header */);
6997 pw.println();
6998 pw.close();
6999
7000 mLastANRState = sw.toString();
7001 }
7002 }
7003
7004 @Override
7005 public void clearSavedANRState() {
7006 synchronized (mGlobalLock) {
7007 mLastANRState = null;
7008 }
7009 }
7010
7011 @Override
7012 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7013 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7014 synchronized (mGlobalLock) {
7015 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7016 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7017 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7018 dumpLastANRLocked(pw);
7019 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7020 dumpLastANRTracesLocked(pw);
7021 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7022 dumpActivityStarterLocked(pw, dumpPackage);
7023 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7024 dumpActivityContainersLocked(pw);
7025 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7026 if (getRecentTasks() != null) {
7027 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7028 }
7029 }
7030 }
7031 }
7032
7033 @Override
7034 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7035 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7036 int wakefulness) {
7037 synchronized (mGlobalLock) {
7038 if (mHomeProcess != null && (dumpPackage == null
7039 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7040 if (needSep) {
7041 pw.println();
7042 needSep = false;
7043 }
7044 pw.println(" mHomeProcess: " + mHomeProcess);
7045 }
7046 if (mPreviousProcess != null && (dumpPackage == null
7047 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7048 if (needSep) {
7049 pw.println();
7050 needSep = false;
7051 }
7052 pw.println(" mPreviousProcess: " + mPreviousProcess);
7053 }
7054 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7055 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7056 StringBuilder sb = new StringBuilder(128);
7057 sb.append(" mPreviousProcessVisibleTime: ");
7058 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7059 pw.println(sb);
7060 }
7061 if (mHeavyWeightProcess != null && (dumpPackage == null
7062 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7063 if (needSep) {
7064 pw.println();
7065 needSep = false;
7066 }
7067 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7068 }
7069 if (dumpPackage == null) {
7070 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007071 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007072 }
7073 if (dumpAll) {
7074 if (dumpPackage == null) {
7075 pw.println(" mConfigWillChange: "
7076 + getTopDisplayFocusedStack().mConfigWillChange);
7077 }
7078 if (mCompatModePackages.getPackages().size() > 0) {
7079 boolean printed = false;
7080 for (Map.Entry<String, Integer> entry
7081 : mCompatModePackages.getPackages().entrySet()) {
7082 String pkg = entry.getKey();
7083 int mode = entry.getValue();
7084 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7085 continue;
7086 }
7087 if (!printed) {
7088 pw.println(" mScreenCompatPackages:");
7089 printed = true;
7090 }
7091 pw.println(" " + pkg + ": " + mode);
7092 }
7093 }
7094 }
7095
7096 if (dumpPackage == null) {
7097 pw.println(" mWakefulness="
7098 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007099 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007100 if (mRunningVoice != null) {
7101 pw.println(" mRunningVoice=" + mRunningVoice);
7102 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7103 }
7104 pw.println(" mSleeping=" + mSleeping);
7105 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7106 pw.println(" mVrController=" + mVrController);
7107 }
7108 if (mCurAppTimeTracker != null) {
7109 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7110 }
7111 if (mAllowAppSwitchUids.size() > 0) {
7112 boolean printed = false;
7113 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7114 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7115 for (int j = 0; j < types.size(); j++) {
7116 if (dumpPackage == null ||
7117 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7118 if (needSep) {
7119 pw.println();
7120 needSep = false;
7121 }
7122 if (!printed) {
7123 pw.println(" mAllowAppSwitchUids:");
7124 printed = true;
7125 }
7126 pw.print(" User ");
7127 pw.print(mAllowAppSwitchUids.keyAt(i));
7128 pw.print(": Type ");
7129 pw.print(types.keyAt(j));
7130 pw.print(" = ");
7131 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7132 pw.println();
7133 }
7134 }
7135 }
7136 }
7137 if (dumpPackage == null) {
7138 if (mController != null) {
7139 pw.println(" mController=" + mController
7140 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7141 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007142 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7143 pw.println(" mLaunchingActivityWakeLock="
7144 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007145 }
7146
7147 return needSep;
7148 }
7149 }
7150
7151 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007152 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7153 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007154 synchronized (mGlobalLock) {
7155 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007156 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007157 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007158 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7159 if (mRunningVoice != null) {
7160 final long vrToken = proto.start(
7161 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7162 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7163 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007164 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007165 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7166 proto.end(vrToken);
7167 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007168 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007169 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007170 if (mController != null) {
7171 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007172 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7173 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007174 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7175 proto.end(token);
7176 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007177 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7178 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007179 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007180 }
7181
7182 if (mHomeProcess != null && (dumpPackage == null
7183 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007184 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007185 }
7186
7187 if (mPreviousProcess != null && (dumpPackage == null
7188 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007189 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007190 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7191 }
7192
7193 if (mHeavyWeightProcess != null && (dumpPackage == null
7194 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007195 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007196 }
7197
7198 for (Map.Entry<String, Integer> entry
7199 : mCompatModePackages.getPackages().entrySet()) {
7200 String pkg = entry.getKey();
7201 int mode = entry.getValue();
7202 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7203 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7204 proto.write(PACKAGE, pkg);
7205 proto.write(MODE, mode);
7206 proto.end(compatToken);
7207 }
7208 }
7209
7210 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007211 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007212 }
7213
7214 }
7215 }
7216
7217 @Override
7218 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7219 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7220 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007221 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7222 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007223 }
7224
7225 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007226 public void dumpForOom(PrintWriter pw) {
7227 synchronized (mGlobalLock) {
7228 pw.println(" mHomeProcess: " + mHomeProcess);
7229 pw.println(" mPreviousProcess: " + mPreviousProcess);
7230 if (mHeavyWeightProcess != null) {
7231 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7232 }
7233 }
7234 }
7235
7236 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007237 public boolean canGcNow() {
7238 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007239 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007240 }
7241 }
7242
Riddle Hsua0536432019-02-16 00:38:59 +08007243 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007244 @Override
7245 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007246 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007247 if (mRootWindowContainer == null) {
7248 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007249 // oomadj after AMS created.
7250 return null;
7251 }
Louis Chang149d5c82019-12-30 09:47:39 +08007252 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007253 return top != null ? top.app : null;
7254 }
7255 }
7256
Riddle Hsua0536432019-02-16 00:38:59 +08007257 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007258 @Override
7259 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007260 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007261 if (mRootWindowContainer != null) {
7262 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007263 }
7264 }
7265 }
7266
7267 @Override
7268 public void scheduleDestroyAllActivities(String reason) {
7269 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007270 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007271 }
7272 }
7273
7274 @Override
7275 public void removeUser(int userId) {
7276 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007277 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007278 }
7279 }
7280
7281 @Override
7282 public boolean switchUser(int userId, UserState userState) {
7283 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007284 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007285 }
7286 }
7287
7288 @Override
7289 public void onHandleAppCrash(WindowProcessController wpc) {
7290 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007291 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007292 }
7293 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007294
7295 @Override
7296 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7297 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007298 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007299 }
7300 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007301
Riddle Hsua0536432019-02-16 00:38:59 +08007302 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007303 @Override
7304 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007305 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007306 }
7307
Riddle Hsua0536432019-02-16 00:38:59 +08007308 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007309 @Override
7310 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007311 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007312 }
7313
Riddle Hsua0536432019-02-16 00:38:59 +08007314 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007315 @Override
7316 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007317 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007318 }
7319
Riddle Hsua0536432019-02-16 00:38:59 +08007320 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007321 @Override
7322 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007323 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007324 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007325
7326 @Override
7327 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007328 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007329 mPendingTempWhitelist.put(uid, tag);
7330 }
7331 }
7332
7333 @Override
7334 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007335 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007336 mPendingTempWhitelist.remove(uid);
7337 }
7338 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007339
7340 @Override
7341 public boolean handleAppCrashInActivityController(String processName, int pid,
7342 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7343 Runnable killCrashingAppCallback) {
7344 synchronized (mGlobalLock) {
7345 if (mController == null) {
7346 return false;
7347 }
7348
7349 try {
7350 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7351 stackTrace)) {
7352 killCrashingAppCallback.run();
7353 return true;
7354 }
7355 } catch (RemoteException e) {
7356 mController = null;
7357 Watchdog.getInstance().setActivityController(null);
7358 }
7359 return false;
7360 }
7361 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007362
7363 @Override
7364 public void removeRecentTasksByPackageName(String packageName, int userId) {
7365 synchronized (mGlobalLock) {
7366 mRecentTasks.removeTasksByPackageName(packageName, userId);
7367 }
7368 }
7369
7370 @Override
7371 public void cleanupRecentTasksForUser(int userId) {
7372 synchronized (mGlobalLock) {
7373 mRecentTasks.cleanupLocked(userId);
7374 }
7375 }
7376
7377 @Override
7378 public void loadRecentTasksForUser(int userId) {
7379 synchronized (mGlobalLock) {
7380 mRecentTasks.loadUserRecentsLocked(userId);
7381 }
7382 }
7383
7384 @Override
7385 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7386 synchronized (mGlobalLock) {
7387 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7388 }
7389 }
7390
7391 @Override
7392 public void flushRecentTasks() {
7393 mRecentTasks.flush();
7394 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007395
7396 @Override
7397 public WindowProcessController getHomeProcess() {
7398 synchronized (mGlobalLock) {
7399 return mHomeProcess;
7400 }
7401 }
7402
7403 @Override
7404 public WindowProcessController getPreviousProcess() {
7405 synchronized (mGlobalLock) {
7406 return mPreviousProcess;
7407 }
7408 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007409
7410 @Override
7411 public void clearLockedTasks(String reason) {
7412 synchronized (mGlobalLock) {
7413 getLockTaskController().clearLockedTasks(reason);
7414 }
7415 }
7416
7417 @Override
7418 public void updateUserConfiguration() {
7419 synchronized (mGlobalLock) {
7420 final Configuration configuration = new Configuration(getGlobalConfiguration());
7421 final int currentUserId = mAmInternal.getCurrentUserId();
7422 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7423 configuration, currentUserId, Settings.System.canWrite(mContext));
7424 updateConfigurationLocked(configuration, null /* starting */,
7425 false /* initLocale */, false /* persistent */, currentUserId,
7426 false /* deferResume */);
7427 }
7428 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007429
7430 @Override
7431 public boolean canShowErrorDialogs() {
7432 synchronized (mGlobalLock) {
7433 return mShowDialogs && !mSleeping && !mShuttingDown
7434 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7435 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7436 mAmInternal.getCurrentUserId())
7437 && !(UserManager.isDeviceInDemoMode(mContext)
7438 && mAmInternal.getCurrentUser().isDemo());
7439 }
7440 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007441
7442 @Override
7443 public void setProfileApp(String profileApp) {
7444 synchronized (mGlobalLock) {
7445 mProfileApp = profileApp;
7446 }
7447 }
7448
7449 @Override
7450 public void setProfileProc(WindowProcessController wpc) {
7451 synchronized (mGlobalLock) {
7452 mProfileProc = wpc;
7453 }
7454 }
7455
7456 @Override
7457 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7458 synchronized (mGlobalLock) {
7459 mProfilerInfo = profilerInfo;
7460 }
7461 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007462
7463 @Override
7464 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7465 synchronized (mGlobalLock) {
7466 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7467 }
7468 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007469
7470 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007471 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7472 boolean reducedResolution) {
7473 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7474 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007475 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007476
7477 @Override
7478 public boolean isUidForeground(int uid) {
7479 synchronized (mGlobalLock) {
7480 return ActivityTaskManagerService.this.isUidForeground(uid);
7481 }
7482 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007483
7484 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007485 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007486 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007487 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007488 }
7489 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007490
7491 @Override
7492 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007493 // Translate package names into UIDs
7494 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007495 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007496 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7497 if (uid >= 0) {
7498 result.add(uid);
7499 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007500 }
7501 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007502 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007503 }
7504 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007505 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007506}