blob: a5b0026398b6479495b9e9fc6f69836d40bfa8dc [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Jonathan Scott92335342019-12-17 14:46:26 +000031import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Galia Peycheva45f48d32020-02-20 15:39:10 +010034import static android.app.WindowConfiguration.ACTIVITY_TYPE_DREAM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070035import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
40import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070041import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070042import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070043import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070044import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070045import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
46import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070047import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070048import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070049import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
50import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070052import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070053import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080054import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070055import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070059import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
60import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070061import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040062import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.view.Display.DEFAULT_DISPLAY;
64import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070065import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070066
Yunfan Chen79b96062018-10-17 12:45:23 -070067import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
68import static com.android.server.am.ActivityManagerService.MY_PID;
69import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
70import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwalef342f062020-01-27 07:34:13 -080071import static com.android.server.am.ActivityManagerServiceDumpActivitiesProto.ROOT_WINDOW_CONTAINER;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Jeff Changd136e772019-11-05 20:33:52 +080086import static com.android.server.am.EventLogTags.writeBootProgressEnableScreen;
87import static com.android.server.am.EventLogTags.writeConfigurationChanged;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070088import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
89import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Louis Chang149d5c82019-12-30 09:47:39 +0800120import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
Louis Changcdec0802019-11-11 11:45:07 +0800122import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
Louis Changa009c762020-02-26 11:21:31 +0800125import static com.android.server.wm.WindowContainer.POSITION_TOP;
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;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700149import android.app.Notification;
150import android.app.NotificationManager;
151import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700152import android.app.PictureInPictureParams;
153import android.app.ProfilerInfo;
154import android.app.RemoteAction;
155import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700156import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.app.admin.DevicePolicyCache;
158import android.app.assist.AssistContent;
159import android.app.assist.AssistStructure;
jorgegil@google.com06bc3232019-10-31 14:51:22 -0700160import android.app.servertransaction.ClientTransaction;
161import android.app.servertransaction.EnterPipRequestedItem;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700162import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700163import android.content.ActivityNotFoundException;
164import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700166import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.IIntentSender;
169import android.content.Intent;
170import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700171import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900172import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700173import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700174import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.content.pm.ParceledListSlice;
177import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700178import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700180import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700181import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.graphics.Bitmap;
183import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700184import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700185import android.metrics.LogMaker;
186import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700187import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700189import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700190import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700191import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700192import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700193import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700194import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700195import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800196import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700197import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700200import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100201import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700204import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700205import android.os.SystemClock;
206import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700207import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700208import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700210import android.os.UserManager;
211import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700212import android.os.storage.IStorageManager;
213import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700214import android.provider.Settings;
Galia Peycheva6861e912019-08-21 10:20:23 +0200215import android.service.dreams.DreamActivity;
Galia Peycheva52e89222020-02-18 23:41:43 +0100216import android.service.dreams.DreamManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700217import android.service.voice.IVoiceInteractionSession;
218import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900219import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700220import android.telecom.TelecomManager;
221import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100222import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700223import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700224import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700225import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700226import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700227import android.util.SparseArray;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700228import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700229import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700230import android.view.IRecentsAnimationRunner;
231import android.view.RemoteAnimationAdapter;
232import android.view.RemoteAnimationDefinition;
Louis Changa009c762020-02-26 11:21:31 +0800233import android.view.WindowManager;
Wale Ogunwale568f9f412020-03-21 22:27:35 -0700234import android.window.IWindowOrganizerController;
Wale Ogunwale57946582020-03-21 14:29:07 -0700235import android.window.WindowContainerTransaction;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700236
Evan Rosky4505b352018-09-06 11:20:40 -0700237import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700238import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.app.AssistUtils;
240import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700241import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700243import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700244import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
245import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700246import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700247import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700248import com.android.internal.policy.IKeyguardDismissCallback;
249import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700250import com.android.internal.util.ArrayUtils;
251import com.android.internal.util.FastPrintWriter;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800252import com.android.internal.util.FrameworkStatsLog;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800253import com.android.internal.util.function.pooled.PooledConsumer;
254import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700255import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700256import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700257import com.android.server.LocalServices;
258import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700259import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800260import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700261import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700262import com.android.server.am.ActivityManagerService;
Wale Ogunwale59507092018-10-29 09:00:30 -0700263import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
264import com.android.server.am.AppTimeTracker;
265import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700266import com.android.server.am.PendingIntentController;
267import com.android.server.am.PendingIntentRecord;
268import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700269import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700270import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700271import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800272import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700273import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700275
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700277import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700279import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700280import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700281import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700282import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700283import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800284import java.lang.annotation.ElementType;
285import java.lang.annotation.Retention;
286import java.lang.annotation.RetentionPolicy;
287import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700288import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700291import java.util.Arrays;
Jeff Sharkey8b0cff72020-03-09 15:49:01 -0600292import java.util.Collection;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700293import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400294import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700295import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700296import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700297import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700298import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000299import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700300import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301
302/**
303 * System service for managing activities and their containers (task, stacks, displays,... ).
304 *
305 * {@hide}
306 */
307public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700308 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800309 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000310 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700311 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
312 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
313 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
314 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700315 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700316
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700318 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700319 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700320 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100321 // How long we permit background activity starts after an activity in the process
322 // started or finished.
323 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700324
Wale Ogunwale98875612018-10-12 07:53:02 -0700325 /** Used to indicate that an app transition should be animated. */
326 static final boolean ANIMATE = true;
327
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700328 /** Hardware-reported OpenGLES version. */
329 final int GL_ES_VERSION;
330
Wale Ogunwale31913b52018-10-13 08:29:31 -0700331 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
332 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
333 public static final String DUMP_LASTANR_CMD = "lastanr" ;
334 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
335 public static final String DUMP_STARTER_CMD = "starter" ;
336 public static final String DUMP_CONTAINERS_CMD = "containers" ;
337 public static final String DUMP_RECENTS_CMD = "recents" ;
338 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
339
Wale Ogunwale64258362018-10-16 15:13:37 -0700340 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
341 public static final int RELAUNCH_REASON_NONE = 0;
342 /** This activity is being relaunched due to windowing mode change. */
343 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
344 /** This activity is being relaunched due to a free-resize operation. */
345 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
346
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700347 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700348
Wale Ogunwalef6733932018-06-27 05:14:34 -0700349 /**
350 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
351 * change at runtime. Use mContext for non-UI purposes.
352 */
353 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700354 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700355 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700356 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700357 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700358 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700359 private PackageManagerInternal mPmInternal;
Darryl L Johnsona0982222020-02-18 18:21:51 -0800360 /** The cached sys ui service component name from package manager. */
361 private ComponentName mSysUiServiceComponent;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800362 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800363 @VisibleForTesting
364 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700365 PowerManagerInternal mPowerManagerInternal;
366 private UsageStatsManagerInternal mUsageStatsInternal;
367
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700368 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700369 IntentFirewall mIntentFirewall;
370
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700371 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800372 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800373 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700374 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800375 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
376 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
377 *
378 * @see WindowManagerThreadPriorityBooster
379 */
380 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700381 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800382 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700383 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700384 private UserManagerService mUserManager;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800385 private AppOpsManager mAppOpsManager;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700386 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800387 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700388 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700389 /** All processes currently running that might have a window organized by name. */
390 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100391 /** All processes we currently have running mapped by pid and uid */
392 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700393 /** This is the process holding what we currently consider to be the "home" activity. */
394 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700395 /** The currently running heavy-weight process, if any. */
396 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700397 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700398 /**
399 * This is the process holding the activity the user last visited that is in a different process
400 * from the one they are currently in.
401 */
402 WindowProcessController mPreviousProcess;
403 /** The time at which the previous process was last visible. */
404 long mPreviousProcessVisibleTime;
405
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700406 /** List of intents that were used to start the most recent tasks. */
407 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700408 /** State of external calls telling us if the device is awake or asleep. */
409 private boolean mKeyguardShown = false;
410
411 // Wrapper around VoiceInteractionServiceManager
412 private AssistUtils mAssistUtils;
413
414 // VoiceInteraction session ID that changes for each new request except when
415 // being called for multi-window assist in a single session.
416 private int mViSessionId = 1000;
417
418 // How long to wait in getAssistContextExtras for the activity and foreground services
419 // to respond with the result.
420 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
421
422 // How long top wait when going through the modern assist (which doesn't need to block
423 // on getting this result before starting to launch its UI).
424 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
425
426 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
427 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
428
Alison Cichowlas3e340502018-08-07 17:15:01 -0400429 // Permission tokens are used to temporarily granted a trusted app the ability to call
430 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
431 // showing any appropriate error messages to the user.
432 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
433 10 * MINUTE_IN_MILLIS;
434
435 // How long before the service actually expires a token. This is slightly longer than
436 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
437 // expiration exception.
438 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
439 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
440
441 // How long the service will remember expired tokens, for the purpose of providing error
442 // messaging when a client uses an expired token.
443 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
444 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
445
446 // Activity tokens of system activities that are delegating their call to
447 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
448 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
449
450 // Permission tokens that have expired, but we remember for error reporting.
451 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
452
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700453 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
454
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700455 // Keeps track of the active voice interaction service component, notified from
456 // VoiceInteractionManagerService
457 ComponentName mActiveVoiceInteractionServiceComponent;
458
Michal Karpinskida34cd42019-04-02 19:46:52 +0100459 // A map userId and all its companion app uids
460 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000461
Wale Ogunwalee2172292018-10-25 10:11:10 -0700462 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700463 KeyguardController mKeyguardController;
464 private final ClientLifecycleManager mLifecycleManager;
465 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700466 /** The controller for all operations related to locktask. */
467 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700468 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700469
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700470 boolean mSuppressResizeConfigChanges;
471
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700472 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700473 new UpdateConfigurationResult();
474
475 static final class UpdateConfigurationResult {
476 // Configuration changes that were updated.
477 int changes;
478 // If the activity was relaunched to match the new configuration.
479 boolean activityRelaunched;
480
481 void reset() {
482 changes = 0;
483 activityRelaunched = false;
484 }
485 }
486
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700487 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700488 private int mConfigurationSeq;
489 // To cache the list of supported system locales
490 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700491
492 /**
493 * Temp object used when global and/or display override configuration is updated. It is also
494 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
495 * anyone...
496 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700497 private Configuration mTempConfig = new Configuration();
498
Wale Ogunwalef6733932018-06-27 05:14:34 -0700499 /** Temporary to avoid allocations. */
500 final StringBuilder mStringBuilder = new StringBuilder(256);
501
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700502 // Amount of time after a call to stopAppSwitches() during which we will
503 // prevent further untrusted switches from happening.
504 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
505
506 /**
507 * The time at which we will allow normal application switches again,
508 * after a call to {@link #stopAppSwitches()}.
509 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700510 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511 /**
512 * This is set to true after the first switch after mAppSwitchesAllowedTime
513 * is set; any switches after that will clear the time.
514 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700515 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700516
Ricky Wai906af482019-06-03 17:25:28 +0100517 /**
518 * Last stop app switches time, apps finished before this time cannot start background activity
519 * even if they are in grace period.
520 */
521 private long mLastStopAppSwitchesTime;
522
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700523 IActivityController mController = null;
524 boolean mControllerIsAMonkey = false;
525
Wale Ogunwale214f3482018-10-04 11:00:47 -0700526 final int mFactoryTest;
527
528 /** Used to control how we initialize the service. */
529 ComponentName mTopComponent;
530 String mTopAction = Intent.ACTION_MAIN;
531 String mTopData;
532
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800533 /** Profiling app information. */
534 String mProfileApp = null;
535 WindowProcessController mProfileProc = null;
536 ProfilerInfo mProfilerInfo = null;
537
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700538 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700539 * Dump of the activity state at the time of the last ANR. Cleared after
540 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
541 */
542 String mLastANRState;
543
544 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700545 * Used to retain an update lock when the foreground activity is in
546 * immersive mode.
547 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700548 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700549
550 /**
551 * Packages that are being allowed to perform unrestricted app switches. Mapping is
552 * User -> Type -> uid.
553 */
554 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
555
556 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700557 private int mThumbnailWidth;
558 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700559
560 /**
561 * Flag that indicates if multi-window is enabled.
562 *
563 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
564 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
565 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
566 * At least one of the forms of multi-window must be enabled in order for this flag to be
567 * initialized to 'true'.
568 *
569 * @see #mSupportsSplitScreenMultiWindow
570 * @see #mSupportsFreeformWindowManagement
571 * @see #mSupportsPictureInPicture
572 * @see #mSupportsMultiDisplay
573 */
574 boolean mSupportsMultiWindow;
575 boolean mSupportsSplitScreenMultiWindow;
576 boolean mSupportsFreeformWindowManagement;
577 boolean mSupportsPictureInPicture;
578 boolean mSupportsMultiDisplay;
579 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700580 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700581
582 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
583
584 // VR Vr2d Display Id.
585 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700586
Wale Ogunwalef6733932018-06-27 05:14:34 -0700587 /**
588 * Set while we are wanting to sleep, to prevent any
589 * activities from being started/resumed.
590 *
591 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
592 *
593 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
594 * while in the sleep state until there is a pending transition out of sleep, in which case
595 * mSleeping is set to false, and remains false while awake.
596 *
597 * Whether mSleeping can quickly toggled between true/false without the device actually
598 * display changing states is undefined.
599 */
600 private boolean mSleeping = false;
601
602 /**
603 * The process state used for processes that are running the top activities.
604 * This changes between TOP and TOP_SLEEPING to following mSleeping.
605 */
606 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
607
Riddle Hsua0022cd2019-09-09 21:12:41 +0800608 @Retention(RetentionPolicy.SOURCE)
609 @IntDef({
610 LAYOUT_REASON_CONFIG_CHANGED,
611 LAYOUT_REASON_VISIBILITY_CHANGED,
612 })
613 @interface LayoutReason {}
614 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
615 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
616
617 /** The reasons to perform surface placement. */
618 @LayoutReason
619 private int mLayoutReasons;
620
Wale Ogunwalef6733932018-06-27 05:14:34 -0700621 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
622 // automatically. Important for devices without direct input devices.
623 private boolean mShowDialogs = true;
624
625 /** Set if we are shutting down the system, similar to sleeping. */
626 boolean mShuttingDown = false;
627
628 /**
629 * We want to hold a wake lock while running a voice interaction session, since
630 * this may happen with the screen off and we need to keep the CPU running to
631 * be able to continue to interact with the user.
632 */
633 PowerManager.WakeLock mVoiceWakeLock;
634
635 /**
636 * Set while we are running a voice interaction. This overrides sleeping while it is active.
637 */
638 IVoiceInteractionSession mRunningVoice;
639
640 /**
641 * The last resumed activity. This is identical to the current resumed activity most
642 * of the time but could be different when we're pausing one activity before we resume
643 * another activity.
644 */
645 ActivityRecord mLastResumedActivity;
646
647 /**
648 * The activity that is currently being traced as the active resumed activity.
649 *
650 * @see #updateResumedAppTrace
651 */
652 private @Nullable ActivityRecord mTracedResumedActivity;
653
654 /** If non-null, we are tracking the time the user spends in the currently focused app. */
655 AppTimeTracker mCurAppTimeTracker;
656
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700657 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700658
Wale Ogunwale53783742018-09-16 10:21:51 -0700659 /**
660 * Packages that the user has asked to have run in screen size
661 * compatibility mode instead of filling the screen.
662 */
663 CompatModePackages mCompatModePackages;
664
Wale Ogunwalef6733932018-06-27 05:14:34 -0700665 private FontScaleSettingObserver mFontScaleSettingObserver;
666
Wale Ogunwale568f9f412020-03-21 22:27:35 -0700667 WindowOrganizerController mWindowOrganizerController;
668 TaskOrganizerController mTaskOrganizerController;
Robert Carr8a2f9132019-11-11 15:03:15 -0800669
Ricky Wai96f5c352019-04-10 18:40:17 +0100670 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000671
Wale Ogunwalef6733932018-06-27 05:14:34 -0700672 private final class FontScaleSettingObserver extends ContentObserver {
673 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
674 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
675
676 public FontScaleSettingObserver() {
677 super(mH);
678 final ContentResolver resolver = mContext.getContentResolver();
679 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
680 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
681 UserHandle.USER_ALL);
682 }
683
684 @Override
Jeff Sharkey8b0cff72020-03-09 15:49:01 -0600685 public void onChange(boolean selfChange, Collection<Uri> uris, int flags,
Riddle Hsu9c024d12020-03-09 16:10:07 +0800686 @UserIdInt int userId) {
687 for (Uri uri : uris) {
688 if (mFontScaleUri.equals(uri)) {
689 updateFontScaleIfNeeded(userId);
690 } else if (mHideErrorDialogsUri.equals(uri)) {
691 synchronized (mGlobalLock) {
692 updateShouldShowDialogsLocked(getGlobalConfiguration());
693 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700694 }
695 }
696 }
697 }
698
Riddle Hsua0536432019-02-16 00:38:59 +0800699 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
700 @Target(ElementType.METHOD)
701 @Retention(RetentionPolicy.SOURCE)
702 @interface HotPath {
703 int NONE = 0;
704 int OOM_ADJUSTMENT = 1;
705 int LRU_UPDATE = 2;
706 int PROCESS_CHANGE = 3;
707 int caller() default NONE;
708 }
709
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800710 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
711 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900712 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800713 mAmInternal.updateOomAdj();
714 }
715 };
716
Charles Chen8d98dd22018-12-26 17:36:54 +0800717 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
718 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700719 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700720 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700721 mSystemThread = ActivityThread.currentActivityThread();
722 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700723 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800724 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700725 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale568f9f412020-03-21 22:27:35 -0700726 mWindowOrganizerController = new WindowOrganizerController(this);
727 mTaskOrganizerController = mWindowOrganizerController.mTaskOrganizerController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700728 }
729
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700730 public void onSystemReady() {
731 synchronized (mGlobalLock) {
732 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
733 PackageManager.FEATURE_CANT_SAVE_STATE);
734 mAssistUtils = new AssistUtils(mContext);
735 mVrController.onSystemReady();
736 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700737 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700738 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700739 }
740
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700741 public void onInitPowerManagement() {
742 synchronized (mGlobalLock) {
743 mStackSupervisor.initPowerManagement();
744 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
745 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
746 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
747 mVoiceWakeLock.setReferenceCounted(false);
748 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700749 }
750
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700751 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700752 mFontScaleSettingObserver = new FontScaleSettingObserver();
753 }
754
Wale Ogunwale59507092018-10-29 09:00:30 -0700755 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700756 final boolean freeformWindowManagement =
757 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
758 || Settings.Global.getInt(
759 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
760
761 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
762 final boolean supportsPictureInPicture = supportsMultiWindow &&
763 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
764 final boolean supportsSplitScreenMultiWindow =
765 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
766 final boolean supportsMultiDisplay = mContext.getPackageManager()
767 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700768 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
769 final boolean forceResizable = Settings.Global.getInt(
770 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700771 final boolean sizeCompatFreeform = Settings.Global.getInt(
772 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700773
774 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900775 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700776
777 final Configuration configuration = new Configuration();
778 Settings.System.getConfiguration(resolver, configuration);
779 if (forceRtl) {
780 // This will take care of setting the correct layout direction flags
781 configuration.setLayoutDirection(configuration.locale);
782 }
783
784 synchronized (mGlobalLock) {
785 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700786 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700787 final boolean multiWindowFormEnabled = freeformWindowManagement
788 || supportsSplitScreenMultiWindow
789 || supportsPictureInPicture
790 || supportsMultiDisplay;
791 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
792 mSupportsMultiWindow = true;
793 mSupportsFreeformWindowManagement = freeformWindowManagement;
794 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
795 mSupportsPictureInPicture = supportsPictureInPicture;
796 mSupportsMultiDisplay = supportsMultiDisplay;
797 } else {
798 mSupportsMultiWindow = false;
799 mSupportsFreeformWindowManagement = false;
800 mSupportsSplitScreenMultiWindow = false;
801 mSupportsPictureInPicture = false;
802 mSupportsMultiDisplay = false;
803 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700804 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700805 // This happens before any activities are started, so we can change global configuration
806 // in-place.
807 updateConfigurationLocked(configuration, null, true);
808 final Configuration globalConfig = getGlobalConfiguration();
809 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
810
811 // Load resources only after the current configuration has been set.
812 final Resources res = mContext.getResources();
813 mThumbnailWidth = res.getDimensionPixelSize(
814 com.android.internal.R.dimen.thumbnail_width);
815 mThumbnailHeight = res.getDimensionPixelSize(
816 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700817 }
818 }
819
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800820 public WindowManagerGlobalLock getGlobalLock() {
821 return mGlobalLock;
822 }
823
Yunfan Chen585f2932019-01-29 16:04:45 +0900824 /** For test purpose only. */
825 @VisibleForTesting
826 public ActivityTaskManagerInternal getAtmInternal() {
827 return mInternal;
828 }
829
Riddle Hsud93a6c42018-11-29 21:50:06 +0800830 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
831 Looper looper) {
832 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700833 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700834 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700835 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800836 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700837 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700838 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700839 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700840
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700841 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700842 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700843 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700844 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700845 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700846 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700847 mKeyguardController = mStackSupervisor.getKeyguardController();
848 }
849
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700850 public void onActivityManagerInternalAdded() {
851 synchronized (mGlobalLock) {
852 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
853 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
854 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700855 }
856
Yunfan Chen75157d72018-07-27 14:47:21 +0900857 int increaseConfigurationSeqLocked() {
858 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
859 return mConfigurationSeq;
860 }
861
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700862 protected ActivityStackSupervisor createStackSupervisor() {
863 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
864 supervisor.initialize();
865 return supervisor;
866 }
867
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800868 protected AppWarnings createAppWarnings(
869 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
870 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
871 }
872
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700873 public void setWindowManager(WindowManagerService wm) {
874 synchronized (mGlobalLock) {
875 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800876 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800877 mTempConfig.setToDefaults();
878 mTempConfig.setLocales(LocaleList.getDefault());
879 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800880 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700881 mLockTaskController.setWindowManager(wm);
882 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800883 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700884 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700885 }
886
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700887 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
888 synchronized (mGlobalLock) {
889 mUsageStatsInternal = usageStatsManager;
890 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700891 }
892
Wale Ogunwalef6733932018-06-27 05:14:34 -0700893 UserManagerService getUserManager() {
894 if (mUserManager == null) {
895 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
896 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
897 }
898 return mUserManager;
899 }
900
Philip P. Moltmannee295092020-02-10 08:46:26 -0800901 AppOpsManager getAppOpsManager() {
902 if (mAppOpsManager == null) {
903 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Wale Ogunwalef6733932018-06-27 05:14:34 -0700904 }
Philip P. Moltmannee295092020-02-10 08:46:26 -0800905 return mAppOpsManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700906 }
907
908 boolean hasUserRestriction(String restriction, int userId) {
909 return getUserManager().hasUserRestriction(restriction, userId);
910 }
911
Michal Karpinski15486842019-04-25 17:33:42 +0100912 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
Philip P. Moltmannee295092020-02-10 08:46:26 -0800913 final int mode = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
914 callingUid, callingPackage, /* featureId */ null, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100915 if (mode == AppOpsManager.MODE_DEFAULT) {
916 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
917 == PERMISSION_GRANTED;
918 }
919 return mode == AppOpsManager.MODE_ALLOWED;
920 }
921
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700922 @VisibleForTesting
923 protected void setRecentTasks(RecentTasks recentTasks) {
924 mRecentTasks = recentTasks;
925 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700926 }
927
928 RecentTasks getRecentTasks() {
929 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700930 }
931
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700932 ClientLifecycleManager getLifecycleManager() {
933 return mLifecycleManager;
934 }
935
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700936 ActivityStartController getActivityStartController() {
937 return mActivityStartController;
938 }
939
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700940 TaskChangeNotificationController getTaskChangeNotificationController() {
941 return mTaskChangeNotificationController;
942 }
943
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700944 LockTaskController getLockTaskController() {
945 return mLockTaskController;
946 }
947
Yunfan Chen75157d72018-07-27 14:47:21 +0900948 /**
949 * Return the global configuration used by the process corresponding to the input pid. This is
950 * usually the global configuration with some overrides specific to that process.
951 */
952 Configuration getGlobalConfigurationForCallingPid() {
953 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800954 return getGlobalConfigurationForPid(pid);
955 }
956
957 /**
958 * Return the global configuration used by the process corresponding to the given pid.
959 */
960 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900961 if (pid == MY_PID || pid < 0) {
962 return getGlobalConfiguration();
963 }
964 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100965 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900966 return app != null ? app.getConfiguration() : getGlobalConfiguration();
967 }
968 }
969
970 /**
971 * Return the device configuration info used by the process corresponding to the input pid.
972 * The value is consistent with the global configuration for the process.
973 */
974 @Override
975 public ConfigurationInfo getDeviceConfigurationInfo() {
976 ConfigurationInfo config = new ConfigurationInfo();
977 synchronized (mGlobalLock) {
978 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
979 config.reqTouchScreen = globalConfig.touchscreen;
980 config.reqKeyboardType = globalConfig.keyboard;
981 config.reqNavigation = globalConfig.navigation;
982 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
983 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
984 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
985 }
986 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
987 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
988 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
989 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700990 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900991 }
992 return config;
993 }
994
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700995 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700996 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700997 }
998
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700999 public static final class Lifecycle extends SystemService {
1000 private final ActivityTaskManagerService mService;
1001
1002 public Lifecycle(Context context) {
1003 super(context);
1004 mService = new ActivityTaskManagerService(context);
1005 }
1006
1007 @Override
1008 public void onStart() {
1009 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001010 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001011 }
1012
Garfield Tan891146c2018-10-09 12:14:00 -07001013 @Override
1014 public void onUnlockUser(int userId) {
1015 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001016 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001017 }
1018 }
1019
1020 @Override
1021 public void onCleanupUser(int userId) {
1022 synchronized (mService.getGlobalLock()) {
1023 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1024 }
1025 }
1026
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001027 public ActivityTaskManagerService getService() {
1028 return mService;
1029 }
1030 }
1031
1032 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001033 public final int startActivity(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001034 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1035 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1036 Bundle bOptions) {
1037 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1038 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001039 UserHandle.getCallingUserId());
1040 }
1041
1042 @Override
1043 public final int startActivities(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001044 String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
1045 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001046 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001047 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001048 enforceNotIsolatedCaller(reason);
1049 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001050 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001051 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001052 callingFeatureId, intents, resolvedTypes, resultTo,
1053 SafeActivityOptions.fromBundle(bOptions), userId, reason,
1054 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001055 }
1056
1057 @Override
1058 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001059 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1060 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1061 Bundle bOptions, int userId) {
1062 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1063 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001064 true /*validateIncomingUser*/);
1065 }
1066
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001067 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001068 @Nullable String callingFeatureId, Intent intent, String resolvedType,
1069 IBinder resultTo, String resultWho, int requestCode, int startFlags,
1070 ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001071 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001072 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001073
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001074 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001075 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1076
1077 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001078 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001079 .setCaller(caller)
1080 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001081 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001082 .setResolvedType(resolvedType)
1083 .setResultTo(resultTo)
1084 .setResultWho(resultWho)
1085 .setRequestCode(requestCode)
1086 .setStartFlags(startFlags)
1087 .setProfilerInfo(profilerInfo)
1088 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001089 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001090 .execute();
1091
1092 }
1093
1094 @Override
1095 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1096 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001097 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1098 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001099 // Refuse possible leaked file descriptors
1100 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1101 throw new IllegalArgumentException("File descriptors passed in Intent");
1102 }
1103
1104 if (!(target instanceof PendingIntentRecord)) {
1105 throw new IllegalArgumentException("Bad PendingIntent object");
1106 }
1107
1108 PendingIntentRecord pir = (PendingIntentRecord)target;
1109
1110 synchronized (mGlobalLock) {
1111 // If this is coming from the currently resumed activity, it is
1112 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001113 final ActivityStack stack = getTopDisplayFocusedStack();
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001114 if (stack != null && stack.mResumedActivity != null
1115 && stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001116 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001117 }
1118 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001119 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001120 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001121 }
1122
1123 @Override
1124 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1125 Bundle bOptions) {
1126 // Refuse possible leaked file descriptors
1127 if (intent != null && intent.hasFileDescriptors()) {
1128 throw new IllegalArgumentException("File descriptors passed in Intent");
1129 }
1130 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1131
1132 synchronized (mGlobalLock) {
1133 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1134 if (r == null) {
1135 SafeActivityOptions.abort(options);
1136 return false;
1137 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001138 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001139 // The caller is not running... d'oh!
1140 SafeActivityOptions.abort(options);
1141 return false;
1142 }
1143 intent = new Intent(intent);
1144 // The caller is not allowed to change the data.
1145 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1146 // And we are resetting to find the next component...
1147 intent.setComponent(null);
1148
1149 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1150
1151 ActivityInfo aInfo = null;
1152 try {
1153 List<ResolveInfo> resolves =
1154 AppGlobals.getPackageManager().queryIntentActivities(
1155 intent, r.resolvedType,
1156 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1157 UserHandle.getCallingUserId()).getList();
1158
1159 // Look for the original activity in the list...
1160 final int N = resolves != null ? resolves.size() : 0;
1161 for (int i=0; i<N; i++) {
1162 ResolveInfo rInfo = resolves.get(i);
1163 if (rInfo.activityInfo.packageName.equals(r.packageName)
1164 && rInfo.activityInfo.name.equals(r.info.name)) {
1165 // We found the current one... the next matching is
1166 // after it.
1167 i++;
1168 if (i<N) {
1169 aInfo = resolves.get(i).activityInfo;
1170 }
1171 if (debug) {
1172 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1173 + "/" + r.info.name);
1174 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1175 ? "null" : aInfo.packageName + "/" + aInfo.name));
1176 }
1177 break;
1178 }
1179 }
1180 } catch (RemoteException e) {
1181 }
1182
1183 if (aInfo == null) {
1184 // Nobody who is next!
1185 SafeActivityOptions.abort(options);
1186 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1187 return false;
1188 }
1189
1190 intent.setComponent(new ComponentName(
1191 aInfo.applicationInfo.packageName, aInfo.name));
1192 intent.setFlags(intent.getFlags()&~(
1193 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1194 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1195 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1196 FLAG_ACTIVITY_NEW_TASK));
1197
1198 // Okay now we need to start the new activity, replacing the currently running activity.
1199 // This is a little tricky because we want to start the new one as if the current one is
1200 // finished, but not finish the current one first so that there is no flicker.
1201 // And thus...
1202 final boolean wasFinishing = r.finishing;
1203 r.finishing = true;
1204
1205 // Propagate reply information over to the new activity.
1206 final ActivityRecord resultTo = r.resultTo;
1207 final String resultWho = r.resultWho;
1208 final int requestCode = r.requestCode;
1209 r.resultTo = null;
1210 if (resultTo != null) {
1211 resultTo.removeResultsLocked(r, resultWho, requestCode);
1212 }
1213
1214 final long origId = Binder.clearCallingIdentity();
1215 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001216 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001217 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001218 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001219 .setResolvedType(r.resolvedType)
1220 .setActivityInfo(aInfo)
1221 .setResultTo(resultTo != null ? resultTo.appToken : null)
1222 .setResultWho(resultWho)
1223 .setRequestCode(requestCode)
1224 .setCallingPid(-1)
1225 .setCallingUid(r.launchedFromUid)
1226 .setCallingPackage(r.launchedFromPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001227 .setCallingFeatureId(r.launchedFromFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001228 .setRealCallingPid(-1)
1229 .setRealCallingUid(r.launchedFromUid)
1230 .setActivityOptions(options)
1231 .execute();
1232 Binder.restoreCallingIdentity(origId);
1233
1234 r.finishing = wasFinishing;
1235 if (res != ActivityManager.START_SUCCESS) {
1236 return false;
1237 }
1238 return true;
1239 }
1240 }
1241
1242 @Override
Galia Peycheva6861e912019-08-21 10:20:23 +02001243 public boolean startDreamActivity(Intent intent) {
Galia Peycheva52e89222020-02-18 23:41:43 +01001244 final WindowProcessController process = mProcessMap.getProcess(Binder.getCallingPid());
1245 final long origId = Binder.clearCallingIdentity();
1246
1247 // The dream activity is only called for non-doze dreams.
1248 final ComponentName currentDream = LocalServices.getService(DreamManagerInternal.class)
1249 .getActiveDreamComponent(/* doze= */ false);
1250
1251 if (currentDream == null || currentDream.getPackageName() == null
1252 || !currentDream.getPackageName().equals(process.mInfo.packageName)) {
1253 Slog.e(TAG, "Calling package is not the current dream package. "
1254 + "Aborting startDreamActivity...");
1255 return false;
1256 }
1257
Galia Peycheva6861e912019-08-21 10:20:23 +02001258 final ActivityInfo a = new ActivityInfo();
1259 a.theme = com.android.internal.R.style.Theme_Dream;
1260 a.exported = true;
1261 a.name = DreamActivity.class.getName();
1262
Galia Peycheva6861e912019-08-21 10:20:23 +02001263
1264 a.packageName = process.mInfo.packageName;
1265 a.applicationInfo = process.mInfo;
1266 a.processName = process.mInfo.processName;
1267 a.uiOptions = process.mInfo.uiOptions;
1268 a.taskAffinity = "android:" + a.packageName + "/dream";
1269 a.enabled = true;
1270 a.launchMode = ActivityInfo.LAUNCH_SINGLE_INSTANCE;
1271
1272 a.persistableMode = ActivityInfo.PERSIST_NEVER;
1273 a.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1274 a.colorMode = ActivityInfo.COLOR_MODE_DEFAULT;
1275 a.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1276
Galia Peycheva45f48d32020-02-20 15:39:10 +01001277 final ActivityOptions options = ActivityOptions.makeBasic();
1278 options.setLaunchActivityType(ACTIVITY_TYPE_DREAM);
1279
Galia Peycheva6861e912019-08-21 10:20:23 +02001280 try {
1281 getActivityStartController().obtainStarter(intent, "dream")
1282 .setActivityInfo(a)
Galia Peycheva45f48d32020-02-20 15:39:10 +01001283 .setActivityOptions(options.toBundle())
Galia Peycheva6861e912019-08-21 10:20:23 +02001284 .setIsDream(true)
1285 .execute();
1286 return true;
1287 } finally {
1288 Binder.restoreCallingIdentity(origId);
1289 }
1290 }
1291
1292 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001293 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001294 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1295 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1296 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001297 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001298 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001299 enforceNotIsolatedCaller("startActivityAndWait");
1300 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1301 userId, "startActivityAndWait");
1302 // TODO: Switch to user app stacks here.
1303 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1304 .setCaller(caller)
1305 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001306 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001307 .setResolvedType(resolvedType)
1308 .setResultTo(resultTo)
1309 .setResultWho(resultWho)
1310 .setRequestCode(requestCode)
1311 .setStartFlags(startFlags)
1312 .setActivityOptions(bOptions)
1313 .setUserId(userId)
1314 .setProfilerInfo(profilerInfo)
1315 .setWaitResult(res)
1316 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001317 return res;
1318 }
1319
1320 @Override
1321 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001322 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1323 String resultWho, int requestCode, int startFlags, Configuration config,
1324 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001325 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001326 enforceNotIsolatedCaller("startActivityWithConfig");
1327 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1328 "startActivityWithConfig");
1329 // TODO: Switch to user app stacks here.
1330 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1331 .setCaller(caller)
1332 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001333 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001334 .setResolvedType(resolvedType)
1335 .setResultTo(resultTo)
1336 .setResultWho(resultWho)
1337 .setRequestCode(requestCode)
1338 .setStartFlags(startFlags)
1339 .setGlobalConfiguration(config)
1340 .setActivityOptions(bOptions)
1341 .setUserId(userId)
1342 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001343 }
1344
Robert Carr8a2f9132019-11-11 15:03:15 -08001345 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001346 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1347 int callingUid = Binder.getCallingUid();
1348 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1349 throw new SecurityException("Only the system process can request a permission token, "
1350 + "received request from uid: " + callingUid);
1351 }
1352 IBinder permissionToken = new Binder();
1353 synchronized (mGlobalLock) {
1354 mStartActivitySources.put(permissionToken, delegatorToken);
1355 }
1356
1357 Message expireMsg = PooledLambda.obtainMessage(
1358 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1359 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1360
1361 Message forgetMsg = PooledLambda.obtainMessage(
1362 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1363 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1364
1365 return permissionToken;
1366 }
1367
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 @Override
1369 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1370 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001371 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1372 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001373 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001374 // permission grants) as any app that may launch one of your own activities. So we only
1375 // allow this in two cases:
1376 // 1) The caller is an activity that is part of the core framework, and then only when it
1377 // is running as the system.
1378 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1379 // can only be requested by a system activity, which may then delegate this call to
1380 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001381 final ActivityRecord sourceRecord;
1382 final int targetUid;
1383 final String targetPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001384 final String targetFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001385 final boolean isResolver;
1386 synchronized (mGlobalLock) {
1387 if (resultTo == null) {
1388 throw new SecurityException("Must be called from an activity");
1389 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001390 final IBinder sourceToken;
1391 if (permissionToken != null) {
1392 // To even attempt to use a permissionToken, an app must also have this signature
1393 // permission.
1394 mAmInternal.enforceCallingPermission(
1395 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1396 "startActivityAsCaller");
1397 // If called with a permissionToken, we want the sourceRecord from the delegator
1398 // activity that requested this token.
1399 sourceToken = mStartActivitySources.remove(permissionToken);
1400 if (sourceToken == null) {
1401 // Invalid permissionToken, check if it recently expired.
1402 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1403 throw new SecurityException("Called with expired permission token: "
1404 + permissionToken);
1405 } else {
1406 throw new SecurityException("Called with invalid permission token: "
1407 + permissionToken);
1408 }
1409 }
1410 } else {
1411 // This method was called directly by the source.
1412 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001414
Louis Chang149d5c82019-12-30 09:47:39 +08001415 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001416 if (sourceRecord == null) {
1417 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001418 }
1419 if (sourceRecord.app == null) {
1420 throw new SecurityException("Called without a process attached to activity");
1421 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001422
1423 // Whether called directly or from a delegate, the source activity must be from the
1424 // android package.
1425 if (!sourceRecord.info.packageName.equals("android")) {
1426 throw new SecurityException("Must be called from an activity that is "
1427 + "declared in the android package");
1428 }
1429
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001430 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001431 // This is still okay, as long as this activity is running under the
1432 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001433 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001434 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001435 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001436 + " must be system uid or original calling uid "
1437 + sourceRecord.launchedFromUid);
1438 }
1439 }
1440 if (ignoreTargetSecurity) {
1441 if (intent.getComponent() == null) {
1442 throw new SecurityException(
1443 "Component must be specified with ignoreTargetSecurity");
1444 }
1445 if (intent.getSelector() != null) {
1446 throw new SecurityException(
1447 "Selector not allowed with ignoreTargetSecurity");
1448 }
1449 }
1450 targetUid = sourceRecord.launchedFromUid;
1451 targetPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001452 targetFeatureId = sourceRecord.launchedFromFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 isResolver = sourceRecord.isResolverOrChildActivity();
1454 }
1455
1456 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001457 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458 }
1459
1460 // TODO: Switch to user app stacks here.
1461 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001462 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001463 .setCallingUid(targetUid)
1464 .setCallingPackage(targetPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001465 .setCallingFeatureId(targetFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001466 .setResolvedType(resolvedType)
1467 .setResultTo(resultTo)
1468 .setResultWho(resultWho)
1469 .setRequestCode(requestCode)
1470 .setStartFlags(startFlags)
1471 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001472 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1474 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001475 // The target may well be in the background, which would normally prevent it
1476 // from starting an activity. Here we definitely want the start to succeed.
1477 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001478 .execute();
1479 } catch (SecurityException e) {
1480 // XXX need to figure out how to propagate to original app.
1481 // A SecurityException here is generally actually a fault of the original
1482 // calling activity (such as a fairly granting permissions), so propagate it
1483 // back to them.
1484 /*
1485 StringBuilder msg = new StringBuilder();
1486 msg.append("While launching");
1487 msg.append(intent.toString());
1488 msg.append(": ");
1489 msg.append(e.getMessage());
1490 */
1491 throw e;
1492 }
1493 }
1494
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001495 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1496 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001497 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001498 }
1499
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001500 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001501 public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1502 int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001503 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1504 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001505 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001506 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001507 if (session == null || interactor == null) {
1508 throw new NullPointerException("null session or interactor");
1509 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001510 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001511 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001512 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001513 .setCallingUid(callingUid)
1514 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001515 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001516 .setResolvedType(resolvedType)
1517 .setVoiceSession(session)
1518 .setVoiceInteractor(interactor)
1519 .setStartFlags(startFlags)
1520 .setProfilerInfo(profilerInfo)
1521 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001522 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001523 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001524 .execute();
1525 }
1526
1527 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001528 public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1529 int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1530 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001531 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001532 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1533 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001534
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001535 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001536 .setCallingUid(callingUid)
1537 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001538 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001539 .setResolvedType(resolvedType)
1540 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001541 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001542 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001543 .execute();
1544 }
1545
Riddle Hsu609a8e22019-06-27 16:46:29 -06001546 /**
1547 * Start the recents activity to perform the recents animation.
1548 *
1549 * @param intent The intent to start the recents activity.
1550 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1551 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001552 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001553 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1554 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001555 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001556 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001557 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001558 final long origId = Binder.clearCallingIdentity();
1559 try {
1560 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001561 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
Philip P. Moltmannee295092020-02-10 08:46:26 -08001562 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001563 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001564 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001565
1566 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001567 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001568 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001569 recentsFeatureId, recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001570 if (recentsAnimationRunner == null) {
1571 anim.preloadRecentsActivity();
1572 } else {
1573 anim.startRecentsActivity(recentsAnimationRunner);
1574 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001575 }
1576 } finally {
1577 Binder.restoreCallingIdentity(origId);
1578 }
1579 }
1580
1581 @Override
1582 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001583 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001584 "startActivityFromRecents()");
1585
1586 final int callingPid = Binder.getCallingPid();
1587 final int callingUid = Binder.getCallingUid();
1588 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1589 final long origId = Binder.clearCallingIdentity();
1590 try {
1591 synchronized (mGlobalLock) {
1592 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1593 safeOptions);
1594 }
1595 } finally {
1596 Binder.restoreCallingIdentity(origId);
1597 }
1598 }
1599
1600 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001601 * Public API to check if the client is allowed to start an activity on specified display.
1602 *
1603 * If the target display is private or virtual, some restrictions will apply.
1604 *
1605 * @param displayId Target display id.
1606 * @param intent Intent used to launch the activity.
1607 * @param resolvedType The MIME type of the intent.
1608 * @param userId The id of the user for whom the call is made.
1609 * @return {@code true} if a call to start an activity on the target display should succeed and
1610 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1611 */
1612 @Override
1613 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1614 String resolvedType, int userId) {
1615 final int callingUid = Binder.getCallingUid();
1616 final int callingPid = Binder.getCallingPid();
1617 final long origId = Binder.clearCallingIdentity();
1618
1619 try {
1620 // Collect information about the target of the Intent.
1621 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1622 0 /* startFlags */, null /* profilerInfo */, userId,
1623 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1624 UserHandle.USER_NULL));
1625 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1626
1627 synchronized (mGlobalLock) {
1628 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1629 aInfo);
1630 }
1631 } finally {
1632 Binder.restoreCallingIdentity(origId);
1633 }
1634 }
1635
1636 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001637 * This is the internal entry point for handling Activity.finish().
1638 *
1639 * @param token The Binder token referencing the Activity we want to finish.
1640 * @param resultCode Result code, if any, from this Activity.
1641 * @param resultData Result data (Intent), if any, from this Activity.
1642 * @param finishTask Whether to finish the task associated with this Activity.
1643 *
1644 * @return Returns true if the activity successfully finished, or false if it is still running.
1645 */
1646 @Override
1647 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1648 int finishTask) {
1649 // Refuse possible leaked file descriptors
1650 if (resultData != null && resultData.hasFileDescriptors()) {
1651 throw new IllegalArgumentException("File descriptors passed in Intent");
1652 }
1653
1654 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001655 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001656 if (r == null) {
1657 return true;
1658 }
1659 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001660 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001661 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001662 if (rootR == null) {
1663 Slog.w(TAG, "Finishing task with all activities already finished");
1664 }
1665 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1666 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001667 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001668 return false;
1669 }
1670
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001671 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1672 // We should consolidate.
1673 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001674 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001675 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001676 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001677 if (next != null) {
1678 // ask watcher if this is allowed
1679 boolean resumeOK = true;
1680 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001681 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001682 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001683 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001684 Watchdog.getInstance().setActivityController(null);
1685 }
1686
1687 if (!resumeOK) {
1688 Slog.i(TAG, "Not finishing activity because controller resumed");
1689 return false;
1690 }
1691 }
1692 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001693
1694 // note down that the process has finished an activity and is in background activity
1695 // starts grace period
1696 if (r.app != null) {
1697 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1698 }
1699
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001700 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001701 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001702 try {
1703 boolean res;
1704 final boolean finishWithRootActivity =
1705 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1706 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1707 || (finishWithRootActivity && r == rootR)) {
1708 // If requested, remove the task that is associated to this activity only if it
1709 // was the root activity in the task. The result code and data is ignored
1710 // because we don't support returning them across task boundaries. Also, to
1711 // keep backwards compatibility we remove the task from recents when finishing
1712 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001713 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001714 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001715 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001716 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001717 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001718 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001719 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001720 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001721 if (!res) {
1722 Slog.i(TAG, "Failed to finish by app-request");
1723 }
1724 }
1725 return res;
1726 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001727 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001728 Binder.restoreCallingIdentity(origId);
1729 }
1730 }
1731 }
1732
1733 @Override
1734 public boolean finishActivityAffinity(IBinder token) {
1735 synchronized (mGlobalLock) {
1736 final long origId = Binder.clearCallingIdentity();
1737 try {
1738 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1739 if (r == null) {
1740 return false;
1741 }
1742
1743 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1744 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001745 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001746 return false;
1747 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001748
1749 final PooledFunction p = PooledLambda.obtainFunction(
1750 ActivityRecord::finishIfSameAffinity, r,
1751 PooledLambda.__(ActivityRecord.class));
1752 r.getTask().forAllActivities(
1753 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1754 p.recycle();
1755
Andrii Kuliande93eff2019-07-12 12:21:27 -07001756 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001757 } finally {
1758 Binder.restoreCallingIdentity(origId);
1759 }
1760 }
1761 }
1762
1763 @Override
1764 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1765 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001766 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001767 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001768 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001769 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1770 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001771 return;
1772 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001773 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1774 false /* processPausingActivities */, config);
1775 if (stopProfiling && r.hasProcess()) {
1776 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001777 }
1778 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001779 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001780 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001781 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001782 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001783 }
1784
1785 @Override
1786 public final void activityResumed(IBinder token) {
1787 final long origId = Binder.clearCallingIdentity();
1788 synchronized (mGlobalLock) {
1789 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001790 }
1791 Binder.restoreCallingIdentity(origId);
1792 }
1793
1794 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001795 public final void activityTopResumedStateLost() {
1796 final long origId = Binder.clearCallingIdentity();
1797 synchronized (mGlobalLock) {
1798 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1799 }
1800 Binder.restoreCallingIdentity(origId);
1801 }
1802
1803 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001804 public final void activityPaused(IBinder token) {
1805 final long origId = Binder.clearCallingIdentity();
1806 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001807 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001808 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1809 if (r != null) {
1810 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001811 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001812 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001813 }
1814 Binder.restoreCallingIdentity(origId);
1815 }
1816
1817 @Override
1818 public final void activityStopped(IBinder token, Bundle icicle,
1819 PersistableBundle persistentState, CharSequence description) {
1820 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1821
1822 // Refuse possible leaked file descriptors
1823 if (icicle != null && icicle.hasFileDescriptors()) {
1824 throw new IllegalArgumentException("File descriptors passed in Bundle");
1825 }
1826
1827 final long origId = Binder.clearCallingIdentity();
1828
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001829 String restartingName = null;
1830 int restartingUid = 0;
1831 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001832 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001833 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001834 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001835 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001836 if (r.attachedToProcess()
1837 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1838 // The activity was requested to restart from
1839 // {@link #restartActivityProcessIfVisible}.
1840 restartingName = r.app.mName;
1841 restartingUid = r.app.mUid;
1842 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001843 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001844 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001845 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001846 }
1847
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001848 if (restartingName != null) {
1849 // In order to let the foreground activity can be restarted with its saved state from
1850 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1851 // until the activity reports stopped with the state. And the activity record will be
1852 // kept because the record state is restarting, then the activity will be restarted
1853 // immediately if it is still the top one.
1854 mStackSupervisor.removeRestartTimeouts(r);
1855 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1856 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001857 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001858
1859 Binder.restoreCallingIdentity(origId);
1860 }
1861
1862 @Override
1863 public final void activityDestroyed(IBinder token) {
1864 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1865 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001866 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001867 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001868 try {
1869 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1870 if (activity != null) {
1871 activity.destroyed("activityDestroyed");
1872 }
1873 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001874 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001875 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001876 }
1877 }
1878 }
1879
1880 @Override
1881 public final void activityRelaunched(IBinder token) {
1882 final long origId = Binder.clearCallingIdentity();
1883 synchronized (mGlobalLock) {
1884 mStackSupervisor.activityRelaunchedLocked(token);
1885 }
1886 Binder.restoreCallingIdentity(origId);
1887 }
1888
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001889 @Override
1890 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1891 synchronized (mGlobalLock) {
1892 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1893 if (r == null) {
1894 return;
1895 }
1896 final long origId = Binder.clearCallingIdentity();
1897 try {
1898 r.setRequestedOrientation(requestedOrientation);
1899 } finally {
1900 Binder.restoreCallingIdentity(origId);
1901 }
1902 }
1903 }
1904
1905 @Override
1906 public int getRequestedOrientation(IBinder token) {
1907 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001908 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1909 return (r != null)
1910 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001911 }
1912 }
1913
1914 @Override
1915 public void setImmersive(IBinder token, boolean immersive) {
1916 synchronized (mGlobalLock) {
1917 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1918 if (r == null) {
1919 throw new IllegalArgumentException();
1920 }
1921 r.immersive = immersive;
1922
1923 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001924 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001925 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001926 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001927 }
1928 }
1929 }
1930
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001931 void applyUpdateLockStateLocked(ActivityRecord r) {
1932 // Modifications to the UpdateLock state are done on our handler, outside
1933 // the activity manager's locks. The new state is determined based on the
1934 // state *now* of the relevant activity record. The object is passed to
1935 // the handler solely for logging detail, not to be consulted/modified.
1936 final boolean nextState = r != null && r.immersive;
1937 mH.post(() -> {
1938 if (mUpdateLock.isHeld() != nextState) {
1939 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1940 "Applying new update lock state '" + nextState + "' for " + r);
1941 if (nextState) {
1942 mUpdateLock.acquire();
1943 } else {
1944 mUpdateLock.release();
1945 }
1946 }
1947 });
1948 }
1949
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001950 @Override
1951 public boolean isImmersive(IBinder token) {
1952 synchronized (mGlobalLock) {
1953 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1954 if (r == null) {
1955 throw new IllegalArgumentException();
1956 }
1957 return r.immersive;
1958 }
1959 }
1960
1961 @Override
1962 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001963 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001964 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001965 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
1966 if (topFocusedStack == null) {
1967 return false;
1968 }
1969
1970 final ActivityRecord r = topFocusedStack.topRunningActivity();
1971 return r != null && r.immersive;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001972 }
1973 }
1974
1975 @Override
1976 public void overridePendingTransition(IBinder token, String packageName,
1977 int enterAnim, int exitAnim) {
1978 synchronized (mGlobalLock) {
1979 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1980 if (self == null) {
1981 return;
1982 }
1983
1984 final long origId = Binder.clearCallingIdentity();
1985
1986 if (self.isState(
1987 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001988 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001989 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001990 }
1991
1992 Binder.restoreCallingIdentity(origId);
1993 }
1994 }
1995
1996 @Override
1997 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001998 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002000 final ActivityStack stack = getTopDisplayFocusedStack();
2001 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002002 if (r == null) {
2003 return ActivityManager.COMPAT_MODE_UNKNOWN;
2004 }
Wale Ogunwale53783742018-09-16 10:21:51 -07002005 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002006 }
2007 }
2008
2009 @Override
2010 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002011 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002012 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002013 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002014 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002015 final ActivityStack stack = getTopDisplayFocusedStack();
2016 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002017 if (r == null) {
2018 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
2019 return;
2020 }
2021 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07002022 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002023 }
2024 }
2025
2026 @Override
2027 public int getLaunchedFromUid(IBinder activityToken) {
2028 ActivityRecord srec;
2029 synchronized (mGlobalLock) {
2030 srec = ActivityRecord.forTokenLocked(activityToken);
2031 }
2032 if (srec == null) {
2033 return -1;
2034 }
2035 return srec.launchedFromUid;
2036 }
2037
2038 @Override
2039 public String getLaunchedFromPackage(IBinder activityToken) {
2040 ActivityRecord srec;
2041 synchronized (mGlobalLock) {
2042 srec = ActivityRecord.forTokenLocked(activityToken);
2043 }
2044 if (srec == null) {
2045 return null;
2046 }
2047 return srec.launchedFromPackage;
2048 }
2049
2050 @Override
2051 public boolean convertFromTranslucent(IBinder token) {
2052 final long origId = Binder.clearCallingIdentity();
2053 try {
2054 synchronized (mGlobalLock) {
2055 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2056 if (r == null) {
2057 return false;
2058 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002059 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 }
2061 } finally {
2062 Binder.restoreCallingIdentity(origId);
2063 }
2064 }
2065
2066 @Override
2067 public boolean convertToTranslucent(IBinder token, Bundle options) {
2068 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2069 final long origId = Binder.clearCallingIdentity();
2070 try {
2071 synchronized (mGlobalLock) {
2072 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2073 if (r == null) {
2074 return false;
2075 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002076 final ActivityRecord under = r.getTask().getActivityBelow(r);
2077 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002078 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2079 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002080 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002081 }
2082 } finally {
2083 Binder.restoreCallingIdentity(origId);
2084 }
2085 }
2086
2087 @Override
2088 public void notifyActivityDrawn(IBinder token) {
2089 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2090 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002091 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002092 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002093 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002094 }
2095 }
2096 }
2097
2098 @Override
2099 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2100 synchronized (mGlobalLock) {
2101 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2102 if (r == null) {
2103 return;
2104 }
2105 r.reportFullyDrawnLocked(restoredFromBundle);
2106 }
2107 }
2108
2109 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002110 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002111 synchronized (mGlobalLock) {
2112 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002113 if (stack != null) {
2114 final int displayId = stack.getDisplayId();
2115 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002116 }
2117 return DEFAULT_DISPLAY;
2118 }
2119 }
2120
2121 @Override
2122 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002123 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002124 long ident = Binder.clearCallingIdentity();
2125 try {
2126 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002127 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002128 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002129 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002130 }
2131 return null;
2132 }
2133 } finally {
2134 Binder.restoreCallingIdentity(ident);
2135 }
2136 }
2137
2138 @Override
2139 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002140 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002141 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2142 final long callingId = Binder.clearCallingIdentity();
2143 try {
2144 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002145 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002146 if (stack == null) {
2147 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2148 return;
2149 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002150 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002151 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002152 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002153 }
2154 }
2155 } finally {
2156 Binder.restoreCallingIdentity(callingId);
2157 }
2158 }
2159
2160 @Override
2161 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002162 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002163 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2164 final long callingId = Binder.clearCallingIdentity();
2165 try {
2166 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002167 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002168 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002169 if (task == null) {
2170 return;
2171 }
2172 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002173 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002174 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002175 }
2176 }
2177 } finally {
2178 Binder.restoreCallingIdentity(callingId);
2179 }
2180 }
2181
2182 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002183 public void restartActivityProcessIfVisible(IBinder activityToken) {
2184 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2185 final long callingId = Binder.clearCallingIdentity();
2186 try {
2187 synchronized (mGlobalLock) {
2188 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2189 if (r == null) {
2190 return;
2191 }
2192 r.restartProcessIfVisible();
2193 }
2194 } finally {
2195 Binder.restoreCallingIdentity(callingId);
2196 }
2197 }
2198
2199 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002200 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002201 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002202 synchronized (mGlobalLock) {
2203 final long ident = Binder.clearCallingIdentity();
2204 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002205 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002206 "remove-task");
2207 } finally {
2208 Binder.restoreCallingIdentity(ident);
2209 }
2210 }
2211 }
2212
2213 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002214 public void removeAllVisibleRecentTasks() {
2215 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2216 synchronized (mGlobalLock) {
2217 final long ident = Binder.clearCallingIdentity();
2218 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002219 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002220 } finally {
2221 Binder.restoreCallingIdentity(ident);
2222 }
2223 }
2224 }
2225
2226 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2228 synchronized (mGlobalLock) {
2229 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2230 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002231 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002232 }
2233 }
2234 return false;
2235 }
2236
2237 @Override
2238 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2239 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002240
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002241 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002242 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2243 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002244 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002245 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002246 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002247 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002248 }
2249 }
2250
2251 /**
2252 * Attempts to move a task backwards in z-order (the order of activities within the task is
2253 * unchanged).
2254 *
2255 * There are several possible results of this call:
2256 * - if the task is locked, then we will show the lock toast
2257 * - if there is a task behind the provided task, then that task is made visible and resumed as
2258 * this task is moved to the back
2259 * - otherwise, if there are no other tasks in the stack:
2260 * - if this task is in the pinned stack, then we remove the stack completely, which will
2261 * have the effect of moving the task to the top or bottom of the fullscreen stack
2262 * (depending on whether it is visible)
2263 * - otherwise, we simply return home and hide this task
2264 *
2265 * @param token A reference to the activity we wish to move
2266 * @param nonRoot If false then this only works if the activity is the root
2267 * of a task; if true it will work for any activity in a task.
2268 * @return Returns true if the move completed, false if not.
2269 */
2270 @Override
2271 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002272 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002273 synchronized (mGlobalLock) {
2274 final long origId = Binder.clearCallingIdentity();
2275 try {
2276 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002277 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002278 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002279 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002280 }
2281 } finally {
2282 Binder.restoreCallingIdentity(origId);
2283 }
2284 }
2285 return false;
2286 }
2287
2288 @Override
2289 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002290 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002291 long ident = Binder.clearCallingIdentity();
2292 Rect rect = new Rect();
2293 try {
2294 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002295 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002296 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2297 if (task == null) {
2298 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2299 return rect;
2300 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002301 if (task.getParent() != null) {
2302 rect.set(task.getBounds());
2303 } else if (task.mLastNonFullscreenBounds != null) {
2304 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002305 }
2306 }
2307 } finally {
2308 Binder.restoreCallingIdentity(ident);
2309 }
2310 return rect;
2311 }
2312
2313 @Override
2314 public ActivityManager.TaskDescription getTaskDescription(int id) {
2315 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002316 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002317 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002318 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002319 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2320 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002321 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002322 }
2323 }
2324 return null;
2325 }
2326
2327 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002328 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002329 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08002330 return setTaskWindowingModeSplitScreenPrimary(taskId, toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002331 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002332 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002333 synchronized (mGlobalLock) {
2334 final long ident = Binder.clearCallingIdentity();
2335 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002336 if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2337 return setTaskWindowingModeSplitScreen(taskId, windowingMode, toTop);
2338 }
Louis Chang149d5c82019-12-30 09:47:39 +08002339 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002340 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002341 if (task == null) {
2342 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002343 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002344 }
2345
2346 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2347 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2348
2349 if (!task.isActivityTypeStandardOrUndefined()) {
2350 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2351 + " non-standard task " + taskId + " to windowing mode="
2352 + windowingMode);
2353 }
2354
2355 final ActivityStack stack = task.getStack();
2356 if (toTop) {
2357 stack.moveToFront("setTaskWindowingMode", task);
2358 }
Louis Changa009c762020-02-26 11:21:31 +08002359 // Convert some windowing-mode changes into root-task reparents for split-screen.
2360 if (stack.inSplitScreenWindowingMode()) {
2361 stack.getDisplay().onSplitScreenModeDismissed();
2362
2363 } else {
2364 stack.setWindowingMode(windowingMode);
2365 stack.getDisplay().ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2366 true /* notifyClients */);
2367 }
Winson Chung7ccc6812020-01-23 16:15:10 -08002368 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002369 } finally {
2370 Binder.restoreCallingIdentity(ident);
2371 }
2372 }
2373 }
2374
2375 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002376 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002377 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002378 ActivityRecord r = getCallingRecordLocked(token);
2379 return r != null ? r.info.packageName : null;
2380 }
2381 }
2382
2383 @Override
2384 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002385 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002386 ActivityRecord r = getCallingRecordLocked(token);
2387 return r != null ? r.intent.getComponent() : null;
2388 }
2389 }
2390
2391 private ActivityRecord getCallingRecordLocked(IBinder token) {
2392 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2393 if (r == null) {
2394 return null;
2395 }
2396 return r.resultTo;
2397 }
2398
2399 @Override
2400 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002401 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002402
2403 synchronized (mGlobalLock) {
2404 final long origId = Binder.clearCallingIdentity();
2405 try {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002406 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
2407 if (topFocusedStack != null) {
2408 topFocusedStack.unhandledBackLocked();
2409 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002410 } finally {
2411 Binder.restoreCallingIdentity(origId);
2412 }
2413 }
2414 }
2415
Mark Renouf446251d2019-04-26 10:22:41 -04002416 @Override
2417 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2418 synchronized (mGlobalLock) {
2419 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2420 if (r == null) {
2421 return;
2422 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002423 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002424 if (stack != null && stack.isSingleTaskInstance()) {
2425 // Single-task stacks are used for activities which are presented in floating
2426 // windows above full screen activities. Instead of directly finishing the
2427 // task, a task change listener is used to notify SystemUI so the action can be
2428 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002429 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002430 mTaskChangeNotificationController
2431 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2432 } else {
2433 try {
2434 callback.requestFinish();
2435 } catch (RemoteException e) {
2436 Slog.e(TAG, "Failed to invoke request finish callback", e);
2437 }
2438 }
2439 }
2440 }
2441
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002442 /**
2443 * TODO: Add mController hook
2444 */
2445 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002446 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2447 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002448 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002449
2450 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2451 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002452 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2453 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002454 }
2455 }
2456
Ricky Waiaca8a772019-04-04 16:01:06 +01002457 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2458 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002459 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002460 final int callingPid = Binder.getCallingPid();
2461 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002462 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002463 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002464 SafeActivityOptions.abort(options);
2465 return;
2466 }
2467 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002468 WindowProcessController callerApp = null;
2469 if (appThread != null) {
2470 callerApp = getProcessController(appThread);
2471 }
2472 final ActivityStarter starter = getActivityStartController().obtainStarter(
2473 null /* intent */, "moveTaskToFront");
2474 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
Galia Peycheva6861e912019-08-21 10:20:23 +02002475 -1, callerApp, null, false, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002476 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002477 return;
2478 }
2479 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002480 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002481 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002482 if (task == null) {
2483 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002484 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002485 return;
2486 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002487 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002488 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002489 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002490 return;
2491 }
2492 ActivityOptions realOptions = options != null
2493 ? options.getOptions(mStackSupervisor)
2494 : null;
2495 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2496 false /* forceNonResizable */);
2497
Wale Ogunwale21e06482019-11-18 05:14:15 -08002498 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002499 if (topActivity != null) {
2500
2501 // We are reshowing a task, use a starting window to hide the initial draw delay
2502 // so the transition can start earlier.
2503 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2504 true /* taskSwitch */, fromRecents);
2505 }
2506 } finally {
2507 Binder.restoreCallingIdentity(origId);
2508 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002509 }
2510
Ricky Waiaca8a772019-04-04 16:01:06 +01002511 /**
2512 * Return true if callingUid is system, or packageName belongs to that callingUid.
2513 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002514 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002515 try {
2516 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2517 if (packageName == null) {
2518 return false;
2519 }
2520 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2521 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2522 UserHandle.getUserId(callingUid));
2523 return UserHandle.isSameApp(callingUid, uid);
2524 }
2525 } catch (RemoteException e) {
2526 // Should not happen
2527 }
2528 return true;
2529 }
2530
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002531 /**
2532 * Checks that the provided package name matches the current calling UID, throws a security
2533 * exception if it doesn't.
2534 */
2535 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2536 final int callingUid = Binder.getCallingUid();
2537 if (isSameApp(callingUid, packageName)) {
2538 return;
2539 }
2540 final String msg = "Permission Denial: package=" + packageName
2541 + " does not belong to uid=" + callingUid;
2542 Slog.w(TAG, msg);
2543 throw new SecurityException(msg);
2544 }
2545
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002546 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2547 int callingPid, int callingUid, String name) {
2548 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2549 return true;
2550 }
2551
2552 if (getRecentTasks().isCallerRecents(sourceUid)) {
2553 return true;
2554 }
2555
2556 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2557 if (perm == PackageManager.PERMISSION_GRANTED) {
2558 return true;
2559 }
2560 if (checkAllowAppSwitchUid(sourceUid)) {
2561 return true;
2562 }
2563
2564 // If the actual IPC caller is different from the logical source, then
2565 // also see if they are allowed to control app switches.
2566 if (callingUid != -1 && callingUid != sourceUid) {
2567 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2568 if (perm == PackageManager.PERMISSION_GRANTED) {
2569 return true;
2570 }
2571 if (checkAllowAppSwitchUid(callingUid)) {
2572 return true;
2573 }
2574 }
2575
2576 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2577 return false;
2578 }
2579
2580 private boolean checkAllowAppSwitchUid(int uid) {
2581 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2582 if (types != null) {
2583 for (int i = types.size() - 1; i >= 0; i--) {
2584 if (types.valueAt(i).intValue() == uid) {
2585 return true;
2586 }
2587 }
2588 }
2589 return false;
2590 }
2591
2592 @Override
2593 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2594 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2595 "setActivityController()");
2596 synchronized (mGlobalLock) {
2597 mController = controller;
2598 mControllerIsAMonkey = imAMonkey;
2599 Watchdog.getInstance().setActivityController(controller);
2600 }
2601 }
2602
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002603 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002604 synchronized (mGlobalLock) {
2605 return mController != null && mControllerIsAMonkey;
2606 }
2607 }
2608
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002609 @Override
2610 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2611 synchronized (mGlobalLock) {
2612 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2613 }
2614 }
2615
2616 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002617 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2618 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2619 }
2620
2621 @Override
2622 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2623 @WindowConfiguration.ActivityType int ignoreActivityType,
2624 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2625 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002626 final int callingPid = Binder.getCallingPid();
2627 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002628 final int[] profileIds = getUserManager().getProfileIds(
2629 UserHandle.getUserId(callingUid), true);
2630 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2631 for (int i = 0; i < profileIds.length; i++) {
2632 callingProfileIds.add(profileIds[i]);
2633 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002634 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2635
2636 synchronized (mGlobalLock) {
2637 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2638
Nicholas Sauer0259e532019-08-30 08:24:55 -07002639 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002640 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002641 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002642 }
2643
2644 return list;
2645 }
2646
2647 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002648 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2649 synchronized (mGlobalLock) {
2650 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002651 try {
2652 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2653 if (r == null) return;
2654
2655 final PooledConsumer c = PooledLambda.obtainConsumer(
2656 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2657 r, resultWho, requestCode);
2658 // TODO: This should probably only loop over the task since you need to be in the
2659 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002660 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002661 c.recycle();
2662
2663 updateOomAdj();
2664 } finally {
2665 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002666 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002667 }
2668 }
2669
2670 @Override
2671 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002672 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002673 ActivityStack stack = ActivityRecord.getStackLocked(token);
2674 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002675 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002676 }
2677 return false;
2678 }
2679 }
2680
2681 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002682 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002683 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002684 synchronized (mGlobalLock) {
2685 final long ident = Binder.clearCallingIdentity();
2686 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002687 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002688 if (task == null) {
2689 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2690 return;
2691 }
2692
2693 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2694 + " to stackId=" + stackId + " toTop=" + toTop);
2695
Louis Chang149d5c82019-12-30 09:47:39 +08002696 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002697 if (stack == null) {
2698 throw new IllegalStateException(
2699 "moveTaskToStack: No stack for stackId=" + stackId);
2700 }
2701 if (!stack.isActivityTypeStandardOrUndefined()) {
2702 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2703 + taskId + " to stack " + stackId);
2704 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002705 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2706 "moveTaskToStack");
2707 } finally {
2708 Binder.restoreCallingIdentity(ident);
2709 }
2710 }
2711 }
2712
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002713 /**
2714 * Moves the specified task to the primary-split-screen stack.
2715 *
2716 * @param taskId Id of task to move.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002717 * @param toTop If the task and stack should be moved to the top.
Winson Chung7ccc6812020-01-23 16:15:10 -08002718 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002719 */
2720 @Override
Evan Rosky73a7fe92019-11-18 18:28:01 -08002721 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002722 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002723 "setTaskWindowingModeSplitScreenPrimary()");
2724 synchronized (mGlobalLock) {
2725 final long ident = Binder.clearCallingIdentity();
2726 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002727 return setTaskWindowingModeSplitScreen(taskId, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY,
2728 toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002729 } finally {
2730 Binder.restoreCallingIdentity(ident);
2731 }
2732 }
2733 }
2734
2735 /**
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002736 * Moves the specified task into a split-screen tile.
2737 */
2738 private boolean setTaskWindowingModeSplitScreen(int taskId, int windowingMode, boolean toTop) {
2739 if (!WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2740 throw new IllegalArgumentException("Calling setTaskWindowingModeSplitScreen with non"
2741 + "split-screen mode: " + windowingMode);
2742 }
2743 if (isInLockTaskMode()) {
2744 Slog.w(TAG, "setTaskWindowingModeSplitScreen: Is in lock task mode="
2745 + getLockTaskModeState());
2746 return false;
2747 }
2748
2749 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2750 MATCH_TASK_IN_STACKS_ONLY);
2751 if (task == null) {
2752 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2753 return false;
2754 }
2755 if (!task.isActivityTypeStandardOrUndefined()) {
2756 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2757 + " non-standard task " + taskId + " to split-screen windowing mode");
2758 }
Wale Ogunwale0d465192020-01-23 19:14:44 -08002759 if (!task.supportsSplitScreenWindowingMode()) {
2760 return false;
2761 }
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002762
2763 final int prevMode = task.getWindowingMode();
Louis Changa009c762020-02-26 11:21:31 +08002764 moveTaskToSplitScreenPrimaryTask(task, toTop);
Wale Ogunwale0d465192020-01-23 19:14:44 -08002765 return prevMode != task.getWindowingMode();
2766 }
2767
Louis Changa009c762020-02-26 11:21:31 +08002768 void moveTaskToSplitScreenPrimaryTask(Task task, boolean toTop) {
2769 final DisplayContent display = task.getDisplayContent();
2770 final ActivityStack primarySplitTask = display.getRootSplitScreenPrimaryTask();
2771 if (primarySplitTask == null) {
2772 throw new IllegalStateException("Can't enter split without associated organized task");
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002773 }
Louis Changa009c762020-02-26 11:21:31 +08002774
2775 if (toTop) {
2776 display.positionStackAt(POSITION_TOP, primarySplitTask, false /* includingParents */);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002777 }
2778 WindowContainerTransaction wct = new WindowContainerTransaction();
Louis Changa009c762020-02-26 11:21:31 +08002779 wct.reparent(task.getStack().mRemoteToken, primarySplitTask.mRemoteToken, toTop);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07002780 mWindowOrganizerController.applyTransaction(wct);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002781 }
2782
2783 /**
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002784 * Removes stacks in the input windowing modes from the system if they are of activity type
2785 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2786 */
2787 @Override
2788 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002789 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002790 "removeStacksInWindowingModes()");
2791
2792 synchronized (mGlobalLock) {
2793 final long ident = Binder.clearCallingIdentity();
2794 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002795 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002796 } finally {
2797 Binder.restoreCallingIdentity(ident);
2798 }
2799 }
2800 }
2801
2802 @Override
2803 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002804 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002805 "removeStacksWithActivityTypes()");
2806
2807 synchronized (mGlobalLock) {
2808 final long ident = Binder.clearCallingIdentity();
2809 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002810 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002811 } finally {
2812 Binder.restoreCallingIdentity(ident);
2813 }
2814 }
2815 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002816
2817 @Override
2818 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2819 int userId) {
2820 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002821 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2822 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002823 callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002824 synchronized (mGlobalLock) {
Winson Chung66b08f02020-03-03 14:32:35 -08002825 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, userId, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 }
2827 }
2828
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002829 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002830 @Override
2831 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002832 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002833 long ident = Binder.clearCallingIdentity();
2834 try {
2835 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002836 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002837 }
2838 } finally {
2839 Binder.restoreCallingIdentity(ident);
2840 }
2841 }
2842
2843 @Override
2844 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002845 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002846 long ident = Binder.clearCallingIdentity();
2847 try {
2848 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002849 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002850 }
2851 } finally {
2852 Binder.restoreCallingIdentity(ident);
2853 }
2854 }
2855
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002856 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002857 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002858 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2859 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2860 long ident = Binder.clearCallingIdentity();
2861 try {
2862 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002863 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002864 }
2865 } finally {
2866 Binder.restoreCallingIdentity(ident);
2867 }
2868 }
2869
2870 @Override
2871 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2872 int displayId) {
2873 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2874 long ident = Binder.clearCallingIdentity();
2875 try {
2876 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002877 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002878 }
2879 } finally {
2880 Binder.restoreCallingIdentity(ident);
2881 }
2882 }
2883
2884 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002885 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002886 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002887 final long callingUid = Binder.getCallingUid();
2888 final long origId = Binder.clearCallingIdentity();
2889 try {
2890 synchronized (mGlobalLock) {
2891 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002892 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002893 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2894 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2895 }
2896 } finally {
2897 Binder.restoreCallingIdentity(origId);
2898 }
2899 }
2900
2901 @Override
2902 public void startLockTaskModeByToken(IBinder token) {
2903 synchronized (mGlobalLock) {
2904 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2905 if (r == null) {
2906 return;
2907 }
Louis Changcdec0802019-11-11 11:45:07 +08002908 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002909 }
2910 }
2911
2912 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002913 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002914 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002915 // This makes inner call to look as if it was initiated by system.
2916 long ident = Binder.clearCallingIdentity();
2917 try {
2918 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002919 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002920 MATCH_TASK_IN_STACKS_ONLY);
2921 if (task == null) {
2922 return;
2923 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002924
2925 // When starting lock task mode the stack must be in front and focused
2926 task.getStack().moveToFront("startSystemLockTaskMode");
2927 startLockTaskModeLocked(task, true /* isSystemCaller */);
2928 }
2929 } finally {
2930 Binder.restoreCallingIdentity(ident);
2931 }
2932 }
2933
2934 @Override
2935 public void stopLockTaskModeByToken(IBinder token) {
2936 synchronized (mGlobalLock) {
2937 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2938 if (r == null) {
2939 return;
2940 }
Louis Changcdec0802019-11-11 11:45:07 +08002941 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002942 }
2943 }
2944
2945 /**
2946 * This API should be called by SystemUI only when user perform certain action to dismiss
2947 * lock task mode. We should only dismiss pinned lock task mode in this case.
2948 */
2949 @Override
2950 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002951 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2953 }
2954
Louis Changcdec0802019-11-11 11:45:07 +08002955 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002956 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2957 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2958 return;
2959 }
2960
Louis Chang149d5c82019-12-30 09:47:39 +08002961 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002962 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002963 throw new IllegalArgumentException("Invalid task, not in foreground");
2964 }
2965
2966 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2967 // system or a specific app.
2968 // * System-initiated requests will only start the pinned mode (screen pinning)
2969 // * App-initiated requests
2970 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2971 // - will start the pinned mode, otherwise
2972 final int callingUid = Binder.getCallingUid();
2973 long ident = Binder.clearCallingIdentity();
2974 try {
2975 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002976 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002977
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002978 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002979 } finally {
2980 Binder.restoreCallingIdentity(ident);
2981 }
2982 }
2983
Louis Changcdec0802019-11-11 11:45:07 +08002984 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002985 final int callingUid = Binder.getCallingUid();
2986 long ident = Binder.clearCallingIdentity();
2987 try {
2988 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002989 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002990 }
2991 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2992 // task and jumping straight into a call in the case of emergency call back.
2993 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2994 if (tm != null) {
2995 tm.showInCallScreen(false);
2996 }
2997 } finally {
2998 Binder.restoreCallingIdentity(ident);
2999 }
3000 }
3001
3002 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003003 public void updateLockTaskPackages(int userId, String[] packages) {
3004 final int callingUid = Binder.getCallingUid();
3005 if (callingUid != 0 && callingUid != SYSTEM_UID) {
3006 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
3007 "updateLockTaskPackages()");
3008 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08003009 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003010 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
3011 + Arrays.toString(packages));
3012 getLockTaskController().updateLockTaskPackages(userId, packages);
3013 }
3014 }
3015
3016 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003017 public boolean isInLockTaskMode() {
3018 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3019 }
3020
3021 @Override
3022 public int getLockTaskModeState() {
3023 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003024 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003025 }
3026 }
3027
3028 @Override
3029 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3030 synchronized (mGlobalLock) {
3031 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3032 if (r != null) {
3033 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003034 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003035 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003036 }
3037 }
3038 }
3039
3040 @Override
3041 public Bundle getActivityOptions(IBinder token) {
3042 final long origId = Binder.clearCallingIdentity();
3043 try {
3044 synchronized (mGlobalLock) {
3045 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3046 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003047 final ActivityOptions activityOptions = r.takeOptionsLocked(
3048 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003049 return activityOptions == null ? null : activityOptions.toBundle();
3050 }
3051 return null;
3052 }
3053 } finally {
3054 Binder.restoreCallingIdentity(origId);
3055 }
3056 }
3057
3058 @Override
3059 public List<IBinder> getAppTasks(String callingPackage) {
3060 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003061 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003062 long ident = Binder.clearCallingIdentity();
3063 try {
3064 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003065 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003066 }
3067 } finally {
3068 Binder.restoreCallingIdentity(ident);
3069 }
3070 }
3071
3072 @Override
3073 public void finishVoiceTask(IVoiceInteractionSession session) {
3074 synchronized (mGlobalLock) {
3075 final long origId = Binder.clearCallingIdentity();
3076 try {
3077 // TODO: VI Consider treating local voice interactions and voice tasks
3078 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003079 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003080 } finally {
3081 Binder.restoreCallingIdentity(origId);
3082 }
3083 }
3084
3085 }
3086
3087 @Override
3088 public boolean isTopOfTask(IBinder token) {
3089 synchronized (mGlobalLock) {
3090 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003091 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003092 }
3093 }
3094
3095 @Override
3096 public void notifyLaunchTaskBehindComplete(IBinder token) {
3097 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3098 }
3099
3100 @Override
3101 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003102 mH.post(() -> {
3103 synchronized (mGlobalLock) {
3104 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003105 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003106 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003107 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003108 } catch (RemoteException e) {
3109 }
3110 }
3111 }
3112
3113 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003114 }
3115
3116 /** Called from an app when assist data is ready. */
3117 @Override
3118 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3119 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003120 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003121 synchronized (pae) {
3122 pae.result = extras;
3123 pae.structure = structure;
3124 pae.content = content;
3125 if (referrer != null) {
3126 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3127 }
3128 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003129 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003130 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003131 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003132 structure.setHomeActivity(pae.isHome);
3133 }
3134 pae.haveResult = true;
3135 pae.notifyAll();
3136 if (pae.intent == null && pae.receiver == null) {
3137 // Caller is just waiting for the result.
3138 return;
3139 }
3140 }
3141 // We are now ready to launch the assist activity.
3142 IAssistDataReceiver sendReceiver = null;
3143 Bundle sendBundle = null;
3144 synchronized (mGlobalLock) {
3145 buildAssistBundleLocked(pae, extras);
3146 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003147 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003148 if (!exists) {
3149 // Timed out.
3150 return;
3151 }
3152
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003153 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003154 // Caller wants result sent back to them.
3155 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003156 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003157 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003158 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3159 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003160 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3161 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3162 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3163 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3164 }
3165 }
3166 if (sendReceiver != null) {
3167 try {
3168 sendReceiver.onHandleAssistData(sendBundle);
3169 } catch (RemoteException e) {
3170 }
3171 return;
3172 }
3173
3174 final long ident = Binder.clearCallingIdentity();
3175 try {
3176 if (TextUtils.equals(pae.intent.getAction(),
3177 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003178 // Start voice interaction through VoiceInteractionManagerService.
3179 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3180 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003181 } else {
3182 pae.intent.replaceExtras(pae.extras);
3183 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3184 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3185 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003186 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003187
3188 try {
3189 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3190 } catch (ActivityNotFoundException e) {
3191 Slog.w(TAG, "No activity to handle assist action.", e);
3192 }
3193 }
3194 } finally {
3195 Binder.restoreCallingIdentity(ident);
3196 }
3197 }
3198
3199 @Override
3200 public int addAppTask(IBinder activityToken, Intent intent,
3201 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3202 final int callingUid = Binder.getCallingUid();
3203 final long callingIdent = Binder.clearCallingIdentity();
3204
3205 try {
3206 synchronized (mGlobalLock) {
3207 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3208 if (r == null) {
3209 throw new IllegalArgumentException("Activity does not exist; token="
3210 + activityToken);
3211 }
3212 ComponentName comp = intent.getComponent();
3213 if (comp == null) {
3214 throw new IllegalArgumentException("Intent " + intent
3215 + " must specify explicit component");
3216 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003217 if (thumbnail.getWidth() != mThumbnailWidth
3218 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003219 throw new IllegalArgumentException("Bad thumbnail size: got "
3220 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003221 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003222 }
3223 if (intent.getSelector() != null) {
3224 intent.setSelector(null);
3225 }
3226 if (intent.getSourceBounds() != null) {
3227 intent.setSourceBounds(null);
3228 }
3229 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3230 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3231 // The caller has added this as an auto-remove task... that makes no
3232 // sense, so turn off auto-remove.
3233 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3234 }
3235 }
3236 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3237 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3238 if (ainfo.applicationInfo.uid != callingUid) {
3239 throw new SecurityException(
3240 "Can't add task for another application: target uid="
3241 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3242 }
3243
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003244 final ActivityStack stack = r.getRootTask();
Wale Ogunwale0d465192020-01-23 19:14:44 -08003245 final Task task = stack.getDisplay().createStack(stack.getWindowingMode(),
Louis Changa009c762020-02-26 11:21:31 +08003246 stack.getActivityType(), !ON_TOP, ainfo, intent,
3247 false /* createdByOrganizer */);
Wale Ogunwale0d465192020-01-23 19:14:44 -08003248
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003249 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003250 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003251 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003252 return INVALID_TASK_ID;
3253 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003254 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003255
3256 // TODO: Send the thumbnail to WM to store it.
3257
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003258 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003259 }
3260 } finally {
3261 Binder.restoreCallingIdentity(callingIdent);
3262 }
3263 }
3264
3265 @Override
3266 public Point getAppTaskThumbnailSize() {
3267 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003268 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003269 }
3270 }
3271
3272 @Override
3273 public void setTaskResizeable(int taskId, int resizeableMode) {
3274 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003275 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003276 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3277 if (task == null) {
3278 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3279 return;
3280 }
3281 task.setResizeMode(resizeableMode);
3282 }
3283 }
3284
3285 @Override
3286 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003287 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003288 long ident = Binder.clearCallingIdentity();
3289 try {
3290 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003291 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003292 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003293 if (task == null) {
3294 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3295 return;
3296 }
3297 // Place the task in the right stack if it isn't there already based on
3298 // the requested bounds.
3299 // The stack transition logic is:
3300 // - a null bounds on a freeform task moves that task to fullscreen
3301 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3302 // that task to freeform
3303 // - otherwise the task is not moved
3304 ActivityStack stack = task.getStack();
3305 if (!task.getWindowConfiguration().canResizeTask()) {
3306 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3307 }
3308 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3309 stack = stack.getDisplay().getOrCreateStack(
3310 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3311 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3312 stack = stack.getDisplay().getOrCreateStack(
3313 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3314 }
3315
3316 // Reparent the task to the right stack if necessary
3317 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3318 if (stack != task.getStack()) {
3319 // Defer resume until the task is resized below
3320 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3321 DEFER_RESUME, "resizeTask");
3322 preserveWindow = false;
3323 }
3324
3325 // After reparenting (which only resizes the task to the stack bounds), resize the
3326 // task to the actual bounds provided
3327 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3328 }
3329 } finally {
3330 Binder.restoreCallingIdentity(ident);
3331 }
3332 }
3333
3334 @Override
3335 public boolean releaseActivityInstance(IBinder token) {
3336 synchronized (mGlobalLock) {
3337 final long origId = Binder.clearCallingIdentity();
3338 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003339 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3340 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003341 return false;
3342 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003343 r.destroyImmediately(true /* removeFromApp */, "app-req");
3344 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003345 } finally {
3346 Binder.restoreCallingIdentity(origId);
3347 }
3348 }
3349 }
3350
3351 @Override
3352 public void releaseSomeActivities(IApplicationThread appInt) {
3353 synchronized (mGlobalLock) {
3354 final long origId = Binder.clearCallingIdentity();
3355 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003356 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003357 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003358 } finally {
3359 Binder.restoreCallingIdentity(origId);
3360 }
3361 }
3362 }
3363
3364 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003365 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003366 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003367 != PackageManager.PERMISSION_GRANTED) {
3368 throw new SecurityException("Requires permission "
3369 + android.Manifest.permission.DEVICE_POWER);
3370 }
3371
3372 synchronized (mGlobalLock) {
3373 long ident = Binder.clearCallingIdentity();
3374 if (mKeyguardShown != keyguardShowing) {
3375 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003376 final Message msg = PooledLambda.obtainMessage(
3377 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3378 keyguardShowing);
3379 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003380 }
3381 try {
wilsonshih177261f2019-02-22 12:02:18 +08003382 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383 } finally {
3384 Binder.restoreCallingIdentity(ident);
3385 }
3386 }
3387
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003388 mH.post(() -> {
3389 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3390 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3391 }
3392 });
3393 }
3394
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003395 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003396 mH.post(() -> {
3397 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3398 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3399 }
3400 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003401 }
3402
3403 @Override
3404 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003405 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3406 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003407
3408 final File passedIconFile = new File(filePath);
3409 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3410 passedIconFile.getName());
3411 if (!legitIconFile.getPath().equals(filePath)
3412 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3413 throw new IllegalArgumentException("Bad file path: " + filePath
3414 + " passed for userId " + userId);
3415 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003416 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003417 }
3418
3419 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003420 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003421 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422 synchronized (mGlobalLock) {
3423 final long ident = Binder.clearCallingIdentity();
3424 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003425 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003426 if (stack == null) {
3427 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3428 return;
3429 }
3430 if (!stack.isActivityTypeStandardOrUndefined()) {
3431 throw new IllegalArgumentException(
3432 "Removing non-standard stack is not allowed.");
3433 }
3434 mStackSupervisor.removeStack(stack);
3435 } finally {
3436 Binder.restoreCallingIdentity(ident);
3437 }
3438 }
3439 }
3440
3441 @Override
3442 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003443 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003444
3445 synchronized (mGlobalLock) {
3446 final long ident = Binder.clearCallingIdentity();
3447 try {
3448 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3449 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003450 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003451 } finally {
3452 Binder.restoreCallingIdentity(ident);
3453 }
3454 }
3455 }
3456
3457 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003458 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003459 synchronized (mGlobalLock) {
3460 long ident = Binder.clearCallingIdentity();
3461 try {
3462 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3463 if (r == null) {
3464 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003465 "toggleFreeformWindowingMode: No activity record matching token="
3466 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003467 }
3468
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003469 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003470 if (stack == null) {
3471 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3472 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003473 }
3474
Yunfan Chend967af82019-01-17 18:30:18 +09003475 if (!stack.inFreeformWindowingMode()
3476 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3477 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3478 + "toggle between fullscreen and freeform.");
3479 }
3480
3481 if (stack.inFreeformWindowingMode()) {
3482 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003483 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003484 throw new IllegalStateException("Size-compat windows are currently not"
3485 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003486 } else if (stack.getParent().inFreeformWindowingMode()) {
3487 // If the window is on a freeform display, set it to undefined. It will be
3488 // resolved to freeform and it can adjust windowing mode when the display mode
3489 // changes in runtime.
3490 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003491 } else {
3492 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3493 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003494 } finally {
3495 Binder.restoreCallingIdentity(ident);
3496 }
3497 }
3498 }
3499
3500 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3501 @Override
3502 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003503 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003504 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003505 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003506 }
3507
3508 /** Unregister a task stack listener so that it stops receiving callbacks. */
3509 @Override
3510 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003511 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003512 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003513 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003514 }
3515
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003516 @Override
3517 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3518 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3519 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3520 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3521 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3522 }
3523
3524 @Override
3525 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3526 IBinder activityToken, int flags) {
3527 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3528 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3529 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3530 }
3531
3532 @Override
3533 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3534 Bundle args) {
3535 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3536 true /* focused */, true /* newSessionId */, userHandle, args,
3537 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3538 }
3539
3540 @Override
3541 public Bundle getAssistContextExtras(int requestType) {
3542 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3543 null, null, true /* focused */, true /* newSessionId */,
3544 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3545 if (pae == null) {
3546 return null;
3547 }
3548 synchronized (pae) {
3549 while (!pae.haveResult) {
3550 try {
3551 pae.wait();
3552 } catch (InterruptedException e) {
3553 }
3554 }
3555 }
3556 synchronized (mGlobalLock) {
3557 buildAssistBundleLocked(pae, pae.result);
3558 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003559 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003560 }
3561 return pae.extras;
3562 }
3563
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003564 /**
3565 * Binder IPC calls go through the public entry point.
3566 * This can be called with or without the global lock held.
3567 */
3568 private static int checkCallingPermission(String permission) {
3569 return checkPermission(
3570 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3571 }
3572
3573 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003574 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003575 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3576 mAmInternal.enforceCallingPermission(permission, func);
3577 }
3578 }
3579
3580 @VisibleForTesting
3581 int checkGetTasksPermission(String permission, int pid, int uid) {
3582 return checkPermission(permission, pid, uid);
3583 }
3584
3585 static int checkPermission(String permission, int pid, int uid) {
3586 if (permission == null) {
3587 return PackageManager.PERMISSION_DENIED;
3588 }
3589 return checkComponentPermission(permission, pid, uid, -1, true);
3590 }
3591
Wale Ogunwale214f3482018-10-04 11:00:47 -07003592 public static int checkComponentPermission(String permission, int pid, int uid,
3593 int owningUid, boolean exported) {
3594 return ActivityManagerService.checkComponentPermission(
3595 permission, pid, uid, owningUid, exported);
3596 }
3597
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003598 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3599 if (getRecentTasks().isCallerRecents(callingUid)) {
3600 // Always allow the recents component to get tasks
3601 return true;
3602 }
3603
3604 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3605 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3606 if (!allowed) {
3607 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3608 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3609 // Temporary compatibility: some existing apps on the system image may
3610 // still be requesting the old permission and not switched to the new
3611 // one; if so, we'll still allow them full access. This means we need
3612 // to see if they are holding the old permission and are a system app.
3613 try {
3614 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3615 allowed = true;
3616 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3617 + " is using old GET_TASKS but privileged; allowing");
3618 }
3619 } catch (RemoteException e) {
3620 }
3621 }
3622 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3623 + " does not hold REAL_GET_TASKS; limiting output");
3624 }
3625 return allowed;
3626 }
3627
Nicholas Sauer0259e532019-08-30 08:24:55 -07003628 boolean isCrossUserAllowed(int pid, int uid) {
3629 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3630 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3631 }
3632
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003633 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3634 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3635 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3636 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003637 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003638 "enqueueAssistContext()");
3639
3640 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08003641 final ActivityStack stack = getTopDisplayFocusedStack();
3642 ActivityRecord activity = stack != null ? stack.getTopNonFinishingActivity() : null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003643 if (activity == null) {
3644 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3645 return null;
3646 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003647 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003648 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3649 return null;
3650 }
3651 if (focused) {
3652 if (activityToken != null) {
3653 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3654 if (activity != caller) {
3655 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3656 + " is not current top " + activity);
3657 return null;
3658 }
3659 }
3660 } else {
3661 activity = ActivityRecord.forTokenLocked(activityToken);
3662 if (activity == null) {
3663 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3664 + " couldn't be found");
3665 return null;
3666 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003667 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003668 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3669 return null;
3670 }
3671 }
3672
3673 PendingAssistExtras pae;
3674 Bundle extras = new Bundle();
3675 if (args != null) {
3676 extras.putAll(args);
3677 }
3678 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003679 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003680
3681 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3682 userHandle);
3683 pae.isHome = activity.isActivityTypeHome();
3684
3685 // Increment the sessionId if necessary
3686 if (newSessionId) {
3687 mViSessionId++;
3688 }
3689 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003690 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3691 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003692 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003693 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003694 } catch (RemoteException e) {
3695 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3696 return null;
3697 }
3698 return pae;
3699 }
3700 }
3701
3702 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3703 if (result != null) {
3704 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3705 }
3706 if (pae.hint != null) {
3707 pae.extras.putBoolean(pae.hint, true);
3708 }
3709 }
3710
3711 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3712 IAssistDataReceiver receiver;
3713 synchronized (mGlobalLock) {
3714 mPendingAssistExtras.remove(pae);
3715 receiver = pae.receiver;
3716 }
3717 if (receiver != null) {
3718 // Caller wants result sent back to them.
3719 Bundle sendBundle = new Bundle();
3720 // At least return the receiver extras
3721 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3722 try {
3723 pae.receiver.onHandleAssistData(sendBundle);
3724 } catch (RemoteException e) {
3725 }
3726 }
3727 }
3728
3729 public class PendingAssistExtras extends Binder implements Runnable {
3730 public final ActivityRecord activity;
3731 public boolean isHome;
3732 public final Bundle extras;
3733 public final Intent intent;
3734 public final String hint;
3735 public final IAssistDataReceiver receiver;
3736 public final int userHandle;
3737 public boolean haveResult = false;
3738 public Bundle result = null;
3739 public AssistStructure structure = null;
3740 public AssistContent content = null;
3741 public Bundle receiverExtras;
3742
3743 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3744 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3745 int _userHandle) {
3746 activity = _activity;
3747 extras = _extras;
3748 intent = _intent;
3749 hint = _hint;
3750 receiver = _receiver;
3751 receiverExtras = _receiverExtras;
3752 userHandle = _userHandle;
3753 }
3754
3755 @Override
3756 public void run() {
3757 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3758 synchronized (this) {
3759 haveResult = true;
3760 notifyAll();
3761 }
3762 pendingAssistExtrasTimedOut(this);
3763 }
3764 }
3765
3766 @Override
3767 public boolean isAssistDataAllowedOnCurrentActivity() {
3768 int userId;
3769 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003770 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003771 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3772 return false;
3773 }
3774
Wale Ogunwale21e06482019-11-18 05:14:15 -08003775 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003776 if (activity == null) {
3777 return false;
3778 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003779 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003780 }
3781 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3782 }
3783
3784 @Override
3785 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3786 long ident = Binder.clearCallingIdentity();
3787 try {
3788 synchronized (mGlobalLock) {
3789 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003790 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003791 if (top != caller) {
3792 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3793 + " is not current top " + top);
3794 return false;
3795 }
3796 if (!top.nowVisible) {
3797 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3798 + " is not visible");
3799 return false;
3800 }
3801 }
3802 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3803 token);
3804 } finally {
3805 Binder.restoreCallingIdentity(ident);
3806 }
3807 }
3808
3809 @Override
3810 public boolean isRootVoiceInteraction(IBinder token) {
3811 synchronized (mGlobalLock) {
3812 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3813 if (r == null) {
3814 return false;
3815 }
3816 return r.rootVoiceInteraction;
3817 }
3818 }
3819
Wale Ogunwalef6733932018-06-27 05:14:34 -07003820 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3821 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3822 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3823 if (activityToCallback == null) return;
3824 activityToCallback.setVoiceSessionLocked(voiceSession);
3825
3826 // Inform the activity
3827 try {
3828 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3829 voiceInteractor);
3830 long token = Binder.clearCallingIdentity();
3831 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003832 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003833 } finally {
3834 Binder.restoreCallingIdentity(token);
3835 }
3836 // TODO: VI Should we cache the activity so that it's easier to find later
3837 // rather than scan through all the stacks and activities?
3838 } catch (RemoteException re) {
3839 activityToCallback.clearVoiceSessionLocked();
3840 // TODO: VI Should this terminate the voice session?
3841 }
3842 }
3843
3844 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3845 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3846 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3847 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3848 boolean wasRunningVoice = mRunningVoice != null;
3849 mRunningVoice = session;
3850 if (!wasRunningVoice) {
3851 mVoiceWakeLock.acquire();
3852 updateSleepIfNeededLocked();
3853 }
3854 }
3855 }
3856
3857 void finishRunningVoiceLocked() {
3858 if (mRunningVoice != null) {
3859 mRunningVoice = null;
3860 mVoiceWakeLock.release();
3861 updateSleepIfNeededLocked();
3862 }
3863 }
3864
3865 @Override
3866 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3867 synchronized (mGlobalLock) {
3868 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3869 if (keepAwake) {
3870 mVoiceWakeLock.acquire();
3871 } else {
3872 mVoiceWakeLock.release();
3873 }
3874 }
3875 }
3876 }
3877
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003878 @Override
3879 public ComponentName getActivityClassForToken(IBinder token) {
3880 synchronized (mGlobalLock) {
3881 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3882 if (r == null) {
3883 return null;
3884 }
3885 return r.intent.getComponent();
3886 }
3887 }
3888
3889 @Override
3890 public String getPackageForToken(IBinder token) {
3891 synchronized (mGlobalLock) {
3892 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3893 if (r == null) {
3894 return null;
3895 }
3896 return r.packageName;
3897 }
3898 }
3899
3900 @Override
3901 public void showLockTaskEscapeMessage(IBinder token) {
3902 synchronized (mGlobalLock) {
3903 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3904 if (r == null) {
3905 return;
3906 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003907 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003908 }
3909 }
3910
3911 @Override
3912 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003913 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003914 final long token = Binder.clearCallingIdentity();
3915 try {
3916 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003917 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003918 }
3919 } finally {
3920 Binder.restoreCallingIdentity(token);
3921 }
3922 }
3923
3924 /**
3925 * Try to place task to provided position. The final position might be different depending on
3926 * current user and stacks state. The task will be moved to target stack if it's currently in
3927 * different stack.
3928 */
3929 @Override
3930 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003931 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003932 synchronized (mGlobalLock) {
3933 long ident = Binder.clearCallingIdentity();
3934 try {
3935 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3936 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003937 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003938 if (task == null) {
3939 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3940 + taskId);
3941 }
3942
Louis Chang149d5c82019-12-30 09:47:39 +08003943 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003944
3945 if (stack == null) {
3946 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3947 + stackId);
3948 }
3949 if (!stack.isActivityTypeStandardOrUndefined()) {
3950 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3951 + " the position of task " + taskId + " in/to non-standard stack");
3952 }
3953
3954 // TODO: Have the callers of this API call a separate reparent method if that is
3955 // what they intended to do vs. having this method also do reparenting.
3956 if (task.getStack() == stack) {
3957 // Change position in current stack.
3958 stack.positionChildAt(task, position);
3959 } else {
3960 // Reparent to new stack.
3961 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3962 !DEFER_RESUME, "positionTaskInStack");
3963 }
3964 } finally {
3965 Binder.restoreCallingIdentity(ident);
3966 }
3967 }
3968 }
3969
3970 @Override
3971 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3972 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3973 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003974 + Arrays.toString(horizontalSizeConfiguration) + " "
3975 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003976 synchronized (mGlobalLock) {
3977 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3978 if (record == null) {
3979 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3980 + "found for: " + token);
3981 }
3982 record.setSizeConfigurations(horizontalSizeConfiguration,
3983 verticalSizeConfigurations, smallestSizeConfigurations);
3984 }
3985 }
3986
3987 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003988 * Dismisses Pip
3989 * @param animate True if the dismissal should be animated.
3990 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3991 * default animation duration should be used.
3992 */
3993 @Override
3994 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003995 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003996 final long ident = Binder.clearCallingIdentity();
3997 try {
3998 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003999 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08004000 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004001 if (stack == null) {
4002 Slog.w(TAG, "dismissPip: pinned stack not found.");
4003 return;
4004 }
4005 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4006 throw new IllegalArgumentException("Stack: " + stack
4007 + " doesn't support animated resize.");
4008 }
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004009 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004010 }
4011 } finally {
4012 Binder.restoreCallingIdentity(ident);
4013 }
4014 }
4015
4016 @Override
4017 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004018 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004019 synchronized (mGlobalLock) {
4020 mSuppressResizeConfigChanges = suppress;
4021 }
4022 }
4023
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004024 @Override
4025 // TODO: API should just be about changing windowing modes...
4026 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004027 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004028 "moveTasksToFullscreenStack()");
4029 synchronized (mGlobalLock) {
4030 final long origId = Binder.clearCallingIdentity();
4031 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004032 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004033 if (stack != null){
4034 if (!stack.isActivityTypeStandardOrUndefined()) {
4035 throw new IllegalArgumentException(
4036 "You can't move tasks from non-standard stacks.");
4037 }
4038 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4039 }
4040 } finally {
4041 Binder.restoreCallingIdentity(origId);
4042 }
4043 }
4044 }
4045
4046 /**
4047 * Moves the top activity in the input stackId to the pinned stack.
4048 *
4049 * @param stackId Id of stack to move the top activity to pinned stack.
4050 * @param bounds Bounds to use for pinned stack.
4051 *
4052 * @return True if the top activity of the input stack was successfully moved to the pinned
4053 * stack.
4054 */
4055 @Override
4056 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004057 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004058 "moveTopActivityToPinnedStack()");
4059 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004060 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004061 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4062 + "Device doesn't support picture-in-picture mode");
4063 }
4064
4065 long ident = Binder.clearCallingIdentity();
4066 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004067 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004068 } finally {
4069 Binder.restoreCallingIdentity(ident);
4070 }
4071 }
4072 }
4073
4074 @Override
4075 public boolean isInMultiWindowMode(IBinder token) {
4076 final long origId = Binder.clearCallingIdentity();
4077 try {
4078 synchronized (mGlobalLock) {
4079 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4080 if (r == null) {
4081 return false;
4082 }
4083 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4084 return r.inMultiWindowMode();
4085 }
4086 } finally {
4087 Binder.restoreCallingIdentity(origId);
4088 }
4089 }
4090
4091 @Override
4092 public boolean isInPictureInPictureMode(IBinder token) {
4093 final long origId = Binder.clearCallingIdentity();
4094 try {
4095 synchronized (mGlobalLock) {
4096 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4097 }
4098 } finally {
4099 Binder.restoreCallingIdentity(origId);
4100 }
4101 }
4102
4103 private boolean isInPictureInPictureMode(ActivityRecord r) {
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004104 return r != null
4105 && r.getRootTask() != null
4106 && r.inPinnedWindowingMode()
4107 && r.getRootTask().isInStackLocked(r) != null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004108 }
4109
4110 @Override
4111 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4112 final long origId = Binder.clearCallingIdentity();
4113 try {
4114 synchronized (mGlobalLock) {
4115 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4116 "enterPictureInPictureMode", token, params);
4117
4118 // If the activity is already in picture in picture mode, then just return early
4119 if (isInPictureInPictureMode(r)) {
4120 return true;
4121 }
4122
4123 // Activity supports picture-in-picture, now check that we can enter PiP at this
4124 // point, if it is
4125 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4126 false /* beforeStopping */)) {
4127 return false;
4128 }
4129
4130 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004131 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004132 if (r.getParent() == null) {
4133 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4134 return;
4135 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004136 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004137 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004138 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4139 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4140 // Adjust the source bounds by the insets for the transition down
4141 final Rect sourceBounds = new Rect(
4142 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004143 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004144 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004145 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004146 stack.setPictureInPictureAspectRatio(aspectRatio);
4147 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004148 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4149 r.info.applicationInfo.uid, r.shortComponentName,
4150 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004151 logPictureInPictureArgs(params);
4152 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004153 };
4154
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004155 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004156 // If the keyguard is showing or occluded, then try and dismiss it before
4157 // entering picture-in-picture (this will prompt the user to authenticate if the
4158 // device is currently locked).
4159 dismissKeyguard(token, new KeyguardDismissCallback() {
4160 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004161 public void onDismissSucceeded() {
4162 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004163 }
4164 }, null /* message */);
4165 } else {
4166 // Enter picture in picture immediately otherwise
4167 enterPipRunnable.run();
4168 }
4169 return true;
4170 }
4171 } finally {
4172 Binder.restoreCallingIdentity(origId);
4173 }
4174 }
4175
4176 @Override
4177 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4178 final long origId = Binder.clearCallingIdentity();
4179 try {
4180 synchronized (mGlobalLock) {
4181 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4182 "setPictureInPictureParams", token, params);
4183
4184 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004185 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004186 if (r.inPinnedWindowingMode()) {
4187 // If the activity is already in picture-in-picture, update the pinned stack now
4188 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4189 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004190 final ActivityStack stack = r.getRootTask();
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004191 stack.setPictureInPictureAspectRatio(
4192 r.pictureInPictureArgs.getAspectRatio());
4193 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004194 }
4195 logPictureInPictureArgs(params);
4196 }
4197 } finally {
4198 Binder.restoreCallingIdentity(origId);
4199 }
4200 }
4201
4202 @Override
4203 public int getMaxNumPictureInPictureActions(IBinder token) {
4204 // Currently, this is a static constant, but later, we may change this to be dependent on
4205 // the context of the activity
4206 return 3;
4207 }
4208
4209 private void logPictureInPictureArgs(PictureInPictureParams params) {
4210 if (params.hasSetActions()) {
4211 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4212 params.getActions().size());
4213 }
4214 if (params.hasSetAspectRatio()) {
4215 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4216 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4217 MetricsLogger.action(lm);
4218 }
4219 }
4220
4221 /**
4222 * Checks the state of the system and the activity associated with the given {@param token} to
4223 * verify that picture-in-picture is supported for that activity.
4224 *
4225 * @return the activity record for the given {@param token} if all the checks pass.
4226 */
4227 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4228 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004229 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004230 throw new IllegalStateException(caller
4231 + ": Device doesn't support picture-in-picture mode.");
4232 }
4233
4234 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4235 if (r == null) {
4236 throw new IllegalStateException(caller
4237 + ": Can't find activity for token=" + token);
4238 }
4239
4240 if (!r.supportsPictureInPicture()) {
4241 throw new IllegalStateException(caller
4242 + ": Current activity does not support picture-in-picture.");
4243 }
4244
4245 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004246 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004247 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004248 final float minAspectRatio = mContext.getResources().getFloat(
4249 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4250 final float maxAspectRatio = mContext.getResources().getFloat(
4251 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4252 throw new IllegalArgumentException(String.format(caller
4253 + ": Aspect ratio is too extreme (must be between %f and %f).",
4254 minAspectRatio, maxAspectRatio));
4255 }
4256
4257 // Truncate the number of actions if necessary
4258 params.truncateActions(getMaxNumPictureInPictureActions(token));
4259
4260 return r;
4261 }
4262
4263 @Override
4264 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004265 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004266 synchronized (mGlobalLock) {
4267 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4268 if (r == null) {
4269 throw new IllegalArgumentException("Activity does not exist; token="
4270 + activityToken);
4271 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004272 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004273 }
4274 }
4275
Evan Rosky73a7fe92019-11-18 18:28:01 -08004276 // TODO(b/149338177): remove when CTS no-longer requires it
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004277 @Override
4278 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4279 Rect tempDockedTaskInsetBounds,
4280 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004281 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004282 long ident = Binder.clearCallingIdentity();
4283 try {
4284 synchronized (mGlobalLock) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08004285 final DisplayContent dc = mRootWindowContainer.getDefaultDisplay();
Louis Changa009c762020-02-26 11:21:31 +08004286 final Task primary = dc.getRootSplitScreenPrimaryTask();
4287 final Task secondary = dc.getTask(t -> t.mCreatedByOrganizer && t.isRootTask()
4288 && t.inSplitScreenSecondaryWindowingMode());
Evan Rosky73a7fe92019-11-18 18:28:01 -08004289 if (primary == null || secondary == null) {
4290 return;
4291 }
4292 final WindowContainerTransaction wct = new WindowContainerTransaction();
4293 final Rect primaryRect =
4294 tempDockedTaskInsetBounds != null ? tempDockedTaskInsetBounds
4295 : (tempDockedTaskBounds != null ? tempDockedTaskBounds
4296 : dockedBounds);
4297 wct.setBounds(primary.mRemoteToken, primaryRect);
4298 Rect otherRect = tempOtherTaskInsetBounds != null ? tempOtherTaskInsetBounds
4299 : tempOtherTaskBounds;
4300 if (otherRect == null) {
4301 // Temporary estimation... again this is just for tests.
4302 otherRect = new Rect(secondary.getBounds());
4303 if (dc.getBounds().width() > dc.getBounds().height()) {
4304 otherRect.left = primaryRect.right + 6;
4305 } else {
4306 otherRect.top = primaryRect.bottom + 6;
4307 }
4308 }
4309 wct.setBounds(secondary.mRemoteToken, otherRect);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004310 mWindowOrganizerController.applyTransaction(wct);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004311 }
4312 } finally {
4313 Binder.restoreCallingIdentity(ident);
4314 }
4315 }
4316
4317 @Override
4318 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004319 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004320 final long ident = Binder.clearCallingIdentity();
4321 try {
4322 synchronized (mGlobalLock) {
4323 mStackSupervisor.setSplitScreenResizing(resizing);
4324 }
4325 } finally {
4326 Binder.restoreCallingIdentity(ident);
4327 }
4328 }
4329
Evan Rosky0037e5f2019-11-05 10:26:24 -08004330 @Override
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004331 public IWindowOrganizerController getWindowOrganizerController() {
Evan Rosky0037e5f2019-11-05 10:26:24 -08004332 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004333 "getWindowOrganizerController()");
4334 return mWindowOrganizerController;
Evan Rosky0037e5f2019-11-05 10:26:24 -08004335 }
4336
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004337 /**
4338 * Check that we have the features required for VR-related API calls, and throw an exception if
4339 * not.
4340 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004341 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004342 if (!mContext.getPackageManager().hasSystemFeature(
4343 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4344 throw new UnsupportedOperationException("VR mode not supported on this device!");
4345 }
4346 }
4347
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004348 @Override
4349 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004350 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004351
4352 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4353
4354 ActivityRecord r;
4355 synchronized (mGlobalLock) {
4356 r = ActivityRecord.isInStackLocked(token);
4357 }
4358
4359 if (r == null) {
4360 throw new IllegalArgumentException();
4361 }
4362
4363 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004364 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004365 VrManagerInternal.NO_ERROR) {
4366 return err;
4367 }
4368
4369 // Clear the binder calling uid since this path may call moveToTask().
4370 final long callingId = Binder.clearCallingIdentity();
4371 try {
4372 synchronized (mGlobalLock) {
4373 r.requestedVrComponent = (enabled) ? packageName : null;
4374
4375 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004376 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004377 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004378 }
4379 return 0;
4380 }
4381 } finally {
4382 Binder.restoreCallingIdentity(callingId);
4383 }
4384 }
4385
4386 @Override
4387 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4388 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4389 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004390 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004391 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4392 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4393 }
Louis Changcdec0802019-11-11 11:45:07 +08004394 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004395 || activity.voiceSession != null) {
4396 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4397 return;
4398 }
4399 if (activity.pendingVoiceInteractionStart) {
4400 Slog.w(TAG, "Pending start of voice interaction already.");
4401 return;
4402 }
4403 activity.pendingVoiceInteractionStart = true;
4404 }
4405 LocalServices.getService(VoiceInteractionManagerInternal.class)
4406 .startLocalVoiceInteraction(callingActivity, options);
4407 }
4408
4409 @Override
4410 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4411 LocalServices.getService(VoiceInteractionManagerInternal.class)
4412 .stopLocalVoiceInteraction(callingActivity);
4413 }
4414
4415 @Override
4416 public boolean supportsLocalVoiceInteraction() {
4417 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4418 .supportsLocalVoiceInteraction();
4419 }
4420
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004421 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004422 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004423 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004424
4425 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004426 if (mWindowManager == null) {
4427 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4428 return false;
4429 }
4430
4431 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004432 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004433 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004434 }
4435
Riddle Hsua0022cd2019-09-09 21:12:41 +08004436 mH.sendMessage(PooledLambda.obtainMessage(
4437 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4438 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004439
4440 final long origId = Binder.clearCallingIdentity();
4441 try {
4442 if (values != null) {
4443 Settings.System.clearConfiguration(values);
4444 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004445 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004446 UserHandle.USER_NULL, false /* deferResume */,
4447 mTmpUpdateConfigurationResult);
4448 return mTmpUpdateConfigurationResult.changes != 0;
4449 } finally {
4450 Binder.restoreCallingIdentity(origId);
4451 }
4452 }
4453 }
4454
4455 @Override
4456 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4457 CharSequence message) {
4458 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004459 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004460 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4461 }
4462 final long callingId = Binder.clearCallingIdentity();
4463 try {
4464 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004465 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004466 }
4467 } finally {
4468 Binder.restoreCallingIdentity(callingId);
4469 }
4470 }
4471
4472 @Override
4473 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004474 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004475 "cancelTaskWindowTransition()");
4476 final long ident = Binder.clearCallingIdentity();
4477 try {
4478 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004479 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004480 MATCH_TASK_IN_STACKS_ONLY);
4481 if (task == null) {
4482 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4483 return;
4484 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004485 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004486 }
4487 } finally {
4488 Binder.restoreCallingIdentity(ident);
4489 }
4490 }
4491
4492 @Override
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004493 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004494 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004495 final long ident = Binder.clearCallingIdentity();
4496 try {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004497 return getTaskSnapshot(taskId, isLowResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004498 } finally {
4499 Binder.restoreCallingIdentity(ident);
4500 }
4501 }
4502
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004503 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004504 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004505 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004506 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004507 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004508 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4509 if (task == null) {
4510 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4511 return null;
4512 }
4513 }
4514 // Don't call this while holding the lock as this operation might hit the disk.
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004515 return task.getSnapshot(isLowResolution, restoreFromDisk);
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004516 }
4517
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004518 @Override
4519 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4520 synchronized (mGlobalLock) {
4521 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4522 if (r == null) {
4523 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4524 + token);
4525 return;
4526 }
4527 final long origId = Binder.clearCallingIdentity();
4528 try {
4529 r.setDisablePreviewScreenshots(disable);
4530 } finally {
4531 Binder.restoreCallingIdentity(origId);
4532 }
4533 }
4534 }
4535
Riddle Hsu440f88b2019-11-06 22:17:35 +08004536 @Override
4537 public void invalidateHomeTaskSnapshot(IBinder token) {
4538 synchronized (mGlobalLock) {
4539 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4540 if (r == null || !r.isActivityTypeHome()) {
4541 return;
4542 }
4543 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4544 }
4545 }
4546
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004547 /** Return the user id of the last resumed activity. */
4548 @Override
4549 public @UserIdInt
4550 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004551 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004552 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4553 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004554 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004555 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004556 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004557 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004558 }
4559 }
4560
4561 @Override
4562 public void updateLockTaskFeatures(int userId, int flags) {
4563 final int callingUid = Binder.getCallingUid();
4564 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004565 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004566 "updateLockTaskFeatures()");
4567 }
4568 synchronized (mGlobalLock) {
4569 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4570 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004571 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004572 }
4573 }
4574
4575 @Override
4576 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4577 synchronized (mGlobalLock) {
4578 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4579 if (r == null) {
4580 return;
4581 }
4582 final long origId = Binder.clearCallingIdentity();
4583 try {
4584 r.setShowWhenLocked(showWhenLocked);
4585 } finally {
4586 Binder.restoreCallingIdentity(origId);
4587 }
4588 }
4589 }
4590
4591 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004592 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4593 synchronized (mGlobalLock) {
4594 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4595 if (r == null) {
4596 return;
4597 }
4598 final long origId = Binder.clearCallingIdentity();
4599 try {
4600 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4601 } finally {
4602 Binder.restoreCallingIdentity(origId);
4603 }
4604 }
4605 }
4606
4607 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004608 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4609 synchronized (mGlobalLock) {
4610 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4611 if (r == null) {
4612 return;
4613 }
4614 final long origId = Binder.clearCallingIdentity();
4615 try {
4616 r.setTurnScreenOn(turnScreenOn);
4617 } finally {
4618 Binder.restoreCallingIdentity(origId);
4619 }
4620 }
4621 }
4622
4623 @Override
4624 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004625 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004626 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004627 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004628 synchronized (mGlobalLock) {
4629 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4630 if (r == null) {
4631 return;
4632 }
4633 final long origId = Binder.clearCallingIdentity();
4634 try {
4635 r.registerRemoteAnimations(definition);
4636 } finally {
4637 Binder.restoreCallingIdentity(origId);
4638 }
4639 }
4640 }
4641
4642 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004643 public void unregisterRemoteAnimations(IBinder token) {
4644 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4645 "unregisterRemoteAnimations");
4646 synchronized (mGlobalLock) {
4647 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4648 if (r == null) {
4649 return;
4650 }
4651 final long origId = Binder.clearCallingIdentity();
4652 try {
4653 r.unregisterRemoteAnimations();
4654 } finally {
4655 Binder.restoreCallingIdentity(origId);
4656 }
4657 }
4658 }
4659
4660 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004661 public void registerRemoteAnimationForNextActivityStart(String packageName,
4662 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004663 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004664 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004665 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004666 synchronized (mGlobalLock) {
4667 final long origId = Binder.clearCallingIdentity();
4668 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004669 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004670 packageName, adapter);
4671 } finally {
4672 Binder.restoreCallingIdentity(origId);
4673 }
4674 }
4675 }
4676
Evan Rosky966759f2019-01-15 10:33:58 -08004677 @Override
4678 public void registerRemoteAnimationsForDisplay(int displayId,
4679 RemoteAnimationDefinition definition) {
4680 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4681 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004682 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004683 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004684 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004685 if (display == null) {
4686 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4687 return;
4688 }
4689 final long origId = Binder.clearCallingIdentity();
4690 try {
4691 display.mDisplayContent.registerRemoteAnimations(definition);
4692 } finally {
4693 Binder.restoreCallingIdentity(origId);
4694 }
4695 }
4696 }
4697
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004698 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4699 @Override
4700 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4701 synchronized (mGlobalLock) {
4702 final long origId = Binder.clearCallingIdentity();
4703 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004704 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004705 } finally {
4706 Binder.restoreCallingIdentity(origId);
4707 }
4708 }
4709 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004710
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004711 @Override
4712 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004713 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004714 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004715 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004716 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004717 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004718 }
4719 }
4720
4721 @Override
4722 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004723 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004724 != PERMISSION_GRANTED) {
4725 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4726 + Binder.getCallingPid()
4727 + ", uid=" + Binder.getCallingUid()
4728 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4729 Slog.w(TAG, msg);
4730 throw new SecurityException(msg);
4731 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004732 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004733 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004734 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004735 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004736 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004737 }
4738 }
4739
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004740 @Override
4741 public void stopAppSwitches() {
4742 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4743 synchronized (mGlobalLock) {
4744 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004745 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004746 mDidAppSwitch = false;
4747 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4748 }
4749 }
4750
4751 @Override
4752 public void resumeAppSwitches() {
4753 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4754 synchronized (mGlobalLock) {
4755 // Note that we don't execute any pending app switches... we will
4756 // let those wait until either the timeout, or the next start
4757 // activity request.
4758 mAppSwitchesAllowedTime = 0;
4759 }
4760 }
4761
Ricky Wai906af482019-06-03 17:25:28 +01004762 long getLastStopAppSwitchesTime() {
4763 return mLastStopAppSwitchesTime;
4764 }
4765
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004766 void onStartActivitySetDidAppSwitch() {
4767 if (mDidAppSwitch) {
4768 // This is the second allowed switch since we stopped switches, so now just generally
4769 // allow switches. Use case:
4770 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4771 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4772 // anyone to switch again).
4773 mAppSwitchesAllowedTime = 0;
4774 } else {
4775 mDidAppSwitch = true;
4776 }
4777 }
4778
4779 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004780 boolean shouldDisableNonVrUiLocked() {
4781 return mVrController.shouldDisableNonVrUiLocked();
4782 }
4783
Wale Ogunwale53783742018-09-16 10:21:51 -07004784 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004785 // 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 +00004786 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004787 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004788 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4789 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004790 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004791 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004792 }
4793 mH.post(() -> {
4794 if (!mVrController.onVrModeChanged(r)) {
4795 return;
4796 }
4797 synchronized (mGlobalLock) {
4798 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4799 mWindowManager.disableNonVrUi(disableNonVrUi);
4800 if (disableNonVrUi) {
4801 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4802 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004803 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004804 }
4805 }
4806 });
4807 }
4808
Wale Ogunwale53783742018-09-16 10:21:51 -07004809 @Override
4810 public int getPackageScreenCompatMode(String packageName) {
4811 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4812 synchronized (mGlobalLock) {
4813 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4814 }
4815 }
4816
4817 @Override
4818 public void setPackageScreenCompatMode(String packageName, int mode) {
4819 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4820 "setPackageScreenCompatMode");
4821 synchronized (mGlobalLock) {
4822 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4823 }
4824 }
4825
4826 @Override
4827 public boolean getPackageAskScreenCompat(String packageName) {
4828 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4829 synchronized (mGlobalLock) {
4830 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4831 }
4832 }
4833
4834 @Override
4835 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4836 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4837 "setPackageAskScreenCompat");
4838 synchronized (mGlobalLock) {
4839 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4840 }
4841 }
4842
Wale Ogunwale64258362018-10-16 15:13:37 -07004843 public static String relaunchReasonToString(int relaunchReason) {
4844 switch (relaunchReason) {
4845 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4846 return "window_resize";
4847 case RELAUNCH_REASON_FREE_RESIZE:
4848 return "free_resize";
4849 default:
4850 return null;
4851 }
4852 }
4853
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004854 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004855 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004856 }
4857
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004858 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004859 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004860 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4861 }
4862
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004863 boolean isKeyguardLocked() {
4864 return mKeyguardController.isKeyguardLocked();
4865 }
4866
Garfield Tan01548632018-11-27 10:15:48 -08004867 /**
4868 * Clears launch params for the given package.
4869 * @param packageNames the names of the packages of which the launch params are to be cleared
4870 */
4871 @Override
4872 public void clearLaunchParamsForPackages(List<String> packageNames) {
4873 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4874 "clearLaunchParamsForPackages");
4875 synchronized (mGlobalLock) {
4876 for (int i = 0; i < packageNames.size(); ++i) {
4877 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4878 }
4879 }
4880 }
4881
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004882 /**
4883 * Makes the display with the given id a single task instance display. I.e the display can only
4884 * contain one task.
4885 */
4886 @Override
4887 public void setDisplayToSingleTaskInstance(int displayId) {
4888 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4889 "setDisplayToSingleTaskInstance");
4890 final long origId = Binder.clearCallingIdentity();
4891 try {
Louis Chang677921f2019-12-06 16:44:24 +08004892 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004893 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004894 if (display != null) {
4895 display.setDisplayToSingleTaskInstance();
4896 }
4897 } finally {
4898 Binder.restoreCallingIdentity(origId);
4899 }
4900 }
4901
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004902 /**
4903 * Requests that an activity should enter picture-in-picture mode if possible.
4904 */
4905 @Override
4906 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4907 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4908 "requestPictureInPictureMode");
4909 final long origId = Binder.clearCallingIdentity();
4910 try {
4911 synchronized (mGlobalLock) {
4912 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4913 if (activity == null) {
4914 return;
4915 }
4916
4917 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4918 "requestPictureInPictureMode", /* beforeStopping */ false);
4919 if (!canEnterPictureInPicture) {
4920 throw new IllegalStateException(
4921 "Requested PIP on an activity that doesn't support it");
4922 }
4923
4924 try {
4925 final ClientTransaction transaction = ClientTransaction.obtain(
4926 activity.app.getThread(),
4927 activity.token);
4928 transaction.addCallback(EnterPipRequestedItem.obtain());
4929 getLifecycleManager().scheduleTransaction(transaction);
4930 } catch (Exception e) {
4931 Slog.w(TAG, "Failed to send enter pip requested item: "
4932 + activity.intent.getComponent(), e);
4933 }
4934 }
4935 } finally {
4936 Binder.restoreCallingIdentity(origId);
4937 }
4938 }
4939
Wale Ogunwale31913b52018-10-13 08:29:31 -07004940 void dumpLastANRLocked(PrintWriter pw) {
4941 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4942 if (mLastANRState == null) {
4943 pw.println(" <no ANR has occurred since boot>");
4944 } else {
4945 pw.println(mLastANRState);
4946 }
4947 }
4948
4949 void dumpLastANRTracesLocked(PrintWriter pw) {
4950 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4951
4952 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4953 if (ArrayUtils.isEmpty(files)) {
4954 pw.println(" <no ANR has occurred since boot>");
4955 return;
4956 }
4957 // Find the latest file.
4958 File latest = null;
4959 for (File f : files) {
4960 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4961 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004962 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004963 }
4964 pw.print("File: ");
4965 pw.print(latest.getName());
4966 pw.println();
4967 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4968 String line;
4969 while ((line = in.readLine()) != null) {
4970 pw.println(line);
4971 }
4972 } catch (IOException e) {
4973 pw.print("Unable to read: ");
4974 pw.print(e);
4975 pw.println();
4976 }
4977 }
4978
4979 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4980 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4981 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4982 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4983 }
4984
4985 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4986 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4987 pw.println(header);
4988
Louis Chang149d5c82019-12-30 09:47:39 +08004989 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004990 dumpPackage);
4991 boolean needSep = printedAnything;
4992
4993 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08004994 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004995 " ResumedActivity: ");
4996 if (printed) {
4997 printedAnything = true;
4998 needSep = false;
4999 }
5000
5001 if (dumpPackage == null) {
5002 if (needSep) {
5003 pw.println();
5004 }
5005 printedAnything = true;
5006 mStackSupervisor.dump(pw, " ");
5007 }
5008
5009 if (!printedAnything) {
5010 pw.println(" (nothing)");
5011 }
5012 }
5013
5014 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005015 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005016 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005017 pw.println(" ");
5018 }
5019
5020 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5021 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5022 getActivityStartController().dump(pw, "", dumpPackage);
5023 }
5024
5025 /**
5026 * There are three things that cmd can be:
5027 * - a flattened component name that matches an existing activity
5028 * - the cmd arg isn't the flattened component name of an existing activity:
5029 * dump all activity whose component contains the cmd as a substring
5030 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005031 * <p>
5032 * The caller should not hold lock when calling this method because it will wait for the
5033 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005034 *
5035 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5036 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5037 */
5038 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5039 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5040 ArrayList<ActivityRecord> activities;
5041
5042 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005043 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005044 dumpFocusedStackOnly);
5045 }
5046
5047 if (activities.size() <= 0) {
5048 return false;
5049 }
5050
5051 String[] newArgs = new String[args.length - opti];
5052 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5053
Louis Changcdec0802019-11-11 11:45:07 +08005054 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005055 boolean needSep = false;
5056 for (int i = activities.size() - 1; i >= 0; i--) {
5057 ActivityRecord r = activities.get(i);
5058 if (needSep) {
5059 pw.println();
5060 }
5061 needSep = true;
5062 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005063 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005064 if (lastTask != task) {
5065 lastTask = task;
5066 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005067 pw.print(" id="); pw.print(lastTask.mTaskId);
5068 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005069 if (dumpAll) {
5070 lastTask.dump(pw, " ");
5071 }
5072 }
5073 }
5074 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5075 }
5076 return true;
5077 }
5078
5079 /**
5080 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5081 * there is a thread associated with the activity.
5082 */
5083 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5084 final ActivityRecord r, String[] args, boolean dumpAll) {
5085 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005086 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005087 synchronized (mGlobalLock) {
5088 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5089 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5090 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005091 if (r.hasProcess()) {
5092 pw.println(r.app.getPid());
5093 appThread = r.app.getThread();
5094 } else {
5095 pw.println("(not running)");
5096 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005097 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005098 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005099 }
5100 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005101 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005102 // flush anything that is already in the PrintWriter since the thread is going
5103 // to write to the file descriptor directly
5104 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005105 try (TransferPipe tp = new TransferPipe()) {
5106 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5107 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005108 } catch (IOException e) {
5109 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5110 } catch (RemoteException e) {
5111 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5112 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005113 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005114 }
5115
sanryhuang498e77e2018-12-06 14:57:01 +08005116 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5117 boolean testPssMode) {
5118 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5119 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5120 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005121 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005122 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5123 st.toString());
5124 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005125 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5126 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5127 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005128 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5129 testPssMode);
5130 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005131 }
5132
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005133 int getCurrentUserId() {
5134 return mAmInternal.getCurrentUserId();
5135 }
5136
5137 private void enforceNotIsolatedCaller(String caller) {
5138 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5139 throw new SecurityException("Isolated process not allowed to call " + caller);
5140 }
5141 }
5142
Wale Ogunwalef6733932018-06-27 05:14:34 -07005143 public Configuration getConfiguration() {
5144 Configuration ci;
5145 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005146 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005147 ci.userSetLocale = false;
5148 }
5149 return ci;
5150 }
5151
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005152 /**
5153 * Current global configuration information. Contains general settings for the entire system,
5154 * also corresponds to the merged configuration of the default display.
5155 */
5156 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005157 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005158 // while initializing process record for system, see {@link
5159 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005160 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005161 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005162 }
5163
5164 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5165 boolean initLocale) {
5166 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5167 }
5168
5169 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5170 boolean initLocale, boolean deferResume) {
5171 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5172 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5173 UserHandle.USER_NULL, deferResume);
5174 }
5175
Wale Ogunwale59507092018-10-29 09:00:30 -07005176 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005177 final long origId = Binder.clearCallingIdentity();
5178 try {
5179 synchronized (mGlobalLock) {
5180 updateConfigurationLocked(values, null, false, true, userId,
5181 false /* deferResume */);
5182 }
5183 } finally {
5184 Binder.restoreCallingIdentity(origId);
5185 }
5186 }
5187
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005188 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5189 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5190 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5191 deferResume, null /* result */);
5192 }
5193
5194 /**
5195 * Do either or both things: (1) change the current configuration, and (2)
5196 * make sure the given activity is running with the (now) current
5197 * configuration. Returns true if the activity has been left running, or
5198 * false if <var>starting</var> is being destroyed to match the new
5199 * configuration.
5200 *
5201 * @param userId is only used when persistent parameter is set to true to persist configuration
5202 * for that particular user
5203 */
5204 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5205 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5206 ActivityTaskManagerService.UpdateConfigurationResult result) {
5207 int changes = 0;
5208 boolean kept = true;
5209
Riddle Hsua0022cd2019-09-09 21:12:41 +08005210 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005211 try {
5212 if (values != null) {
5213 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5214 deferResume);
5215 }
5216
5217 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5218 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005219 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005220 }
5221
5222 if (result != null) {
5223 result.changes = changes;
5224 result.activityRelaunched = !kept;
5225 }
5226 return kept;
5227 }
5228
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005229 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005230 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005231 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005232
Louis Chang677921f2019-12-06 16:44:24 +08005233 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005234 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005235
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005236 mTempConfig.setTo(getGlobalConfiguration());
5237 final int changes = mTempConfig.updateFrom(values);
5238 if (changes == 0) {
5239 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5240 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5241 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5242 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005243 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005244 return 0;
5245 }
5246
5247 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5248 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005249 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005250 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005251 values.colorMode,
5252 values.densityDpi,
5253 values.fontScale,
5254 values.hardKeyboardHidden,
5255 values.keyboard,
5256 values.keyboardHidden,
5257 values.mcc,
5258 values.mnc,
5259 values.navigation,
5260 values.navigationHidden,
5261 values.orientation,
5262 values.screenHeightDp,
5263 values.screenLayout,
5264 values.screenWidthDp,
5265 values.smallestScreenWidthDp,
5266 values.touchscreen,
5267 values.uiMode);
5268
5269
5270 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5271 final LocaleList locales = values.getLocales();
5272 int bestLocaleIndex = 0;
5273 if (locales.size() > 1) {
5274 if (mSupportedSystemLocales == null) {
5275 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5276 }
5277 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5278 }
5279 SystemProperties.set("persist.sys.locale",
5280 locales.get(bestLocaleIndex).toLanguageTag());
5281 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005282
5283 final Message m = PooledLambda.obtainMessage(
5284 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5285 locales.get(bestLocaleIndex));
5286 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005287 }
5288
Yunfan Chen75157d72018-07-27 14:47:21 +09005289 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005290
5291 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005292 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005293
5294 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5295 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005296 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005297
5298 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005299 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005300
5301 AttributeCache ac = AttributeCache.instance();
5302 if (ac != null) {
5303 ac.updateConfiguration(mTempConfig);
5304 }
5305
5306 // Make sure all resources in our process are updated right now, so that anyone who is going
5307 // to retrieve resource values after we return will be sure to get the new ones. This is
5308 // especially important during boot, where the first config change needs to guarantee all
5309 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005310 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005311
5312 // We need another copy of global config because we're scheduling some calls instead of
5313 // running them in place. We need to be sure that object we send will be handled unchanged.
5314 final Configuration configCopy = new Configuration(mTempConfig);
5315 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005316 final Message msg = PooledLambda.obtainMessage(
5317 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5318 this, userId, configCopy);
5319 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005320 }
5321
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005322 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5323 for (int i = pidMap.size() - 1; i >= 0; i--) {
5324 final int pid = pidMap.keyAt(i);
5325 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005326 if (DEBUG_CONFIGURATION) {
5327 Slog.v(TAG_CONFIGURATION, "Update process config of "
5328 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005329 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005330 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005331 }
5332
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005333 final Message msg = PooledLambda.obtainMessage(
5334 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5335 mAmInternal, changes, initLocale);
5336 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005337
5338 // Override configuration of the default display duplicates global config, so we need to
5339 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005340 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005341 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005342
5343 return changes;
5344 }
5345
Riddle Hsua0022cd2019-09-09 21:12:41 +08005346 /** @see WindowSurfacePlacer#deferLayout */
5347 void deferWindowLayout() {
5348 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5349 // Reset the reasons at the first entrance because we only care about the changes in the
5350 // deferred scope.
5351 mLayoutReasons = 0;
5352 }
5353
5354 mWindowManager.mWindowPlacerLocked.deferLayout();
5355 }
5356
5357 /** @see WindowSurfacePlacer#continueLayout */
5358 void continueWindowLayout() {
5359 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5360 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5361 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5362 }
5363 }
5364
5365 /**
5366 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5367 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5368 * defer count is gone.
5369 */
5370 void addWindowLayoutReasons(@LayoutReason int reasons) {
5371 mLayoutReasons |= reasons;
5372 }
5373
Wale Ogunwalef6733932018-06-27 05:14:34 -07005374 private void updateEventDispatchingLocked(boolean booted) {
5375 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5376 }
5377
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005378 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5379 final ContentResolver resolver = mContext.getContentResolver();
5380 Settings.System.putConfigurationForUser(resolver, config, userId);
5381 }
5382
5383 private void sendLocaleToMountDaemonMsg(Locale l) {
5384 try {
5385 IBinder service = ServiceManager.getService("mount");
5386 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5387 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5388 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5389 } catch (RemoteException e) {
5390 Log.e(TAG, "Error storing locale for decryption UI", e);
5391 }
5392 }
5393
Alison Cichowlas3e340502018-08-07 17:15:01 -04005394 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5395 mStartActivitySources.remove(permissionToken);
5396 mExpiredStartAsCallerTokens.add(permissionToken);
5397 }
5398
5399 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5400 mExpiredStartAsCallerTokens.remove(permissionToken);
5401 }
5402
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005403 boolean isActivityStartsLoggingEnabled() {
5404 return mAmInternal.isActivityStartsLoggingEnabled();
5405 }
5406
Michal Karpinski8596ded2018-11-14 14:43:48 +00005407 boolean isBackgroundActivityStartsEnabled() {
5408 return mAmInternal.isBackgroundActivityStartsEnabled();
5409 }
5410
Wale Ogunwalef6733932018-06-27 05:14:34 -07005411 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005412 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005413 mWindowManager.enableScreenAfterBoot();
5414
5415 synchronized (mGlobalLock) {
5416 updateEventDispatchingLocked(booted);
5417 }
5418 }
5419
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005420 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5421 if (r == null || !r.hasProcess()) {
5422 return KEY_DISPATCHING_TIMEOUT_MS;
5423 }
5424 return getInputDispatchingTimeoutLocked(r.app);
5425 }
5426
5427 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005428 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005429 }
5430
Wale Ogunwalef6733932018-06-27 05:14:34 -07005431 /**
5432 * Decide based on the configuration whether we should show the ANR,
5433 * crash, etc dialogs. The idea is that if there is no affordance to
5434 * press the on-screen buttons, or the user experience would be more
5435 * greatly impacted than the crash itself, we shouldn't show the dialog.
5436 *
5437 * A thought: SystemUI might also want to get told about this, the Power
5438 * dialog / global actions also might want different behaviors.
5439 */
5440 private void updateShouldShowDialogsLocked(Configuration config) {
5441 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5442 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5443 && config.navigation == Configuration.NAVIGATION_NONAV);
5444 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5445 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5446 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5447 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5448 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5449 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5450 HIDE_ERROR_DIALOGS, 0) != 0;
5451 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5452 }
5453
5454 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5455 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5456 FONT_SCALE, 1.0f, userId);
5457
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005458 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005459 if (getGlobalConfiguration().fontScale == scaleFactor) {
5460 return;
5461 }
5462
5463 final Configuration configuration
5464 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5465 configuration.fontScale = scaleFactor;
5466 updatePersistentConfiguration(configuration, userId);
5467 }
5468 }
5469
5470 // Actually is sleeping or shutting down or whatever else in the future
5471 // is an inactive state.
5472 boolean isSleepingOrShuttingDownLocked() {
5473 return isSleepingLocked() || mShuttingDown;
5474 }
5475
5476 boolean isSleepingLocked() {
5477 return mSleeping;
5478 }
5479
Riddle Hsu16567132018-08-16 21:37:47 +08005480 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005481 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005482 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005483 if (task.isActivityTypeStandard()) {
5484 if (mCurAppTimeTracker != r.appTimeTracker) {
5485 // We are switching app tracking. Complete the current one.
5486 if (mCurAppTimeTracker != null) {
5487 mCurAppTimeTracker.stop();
5488 mH.obtainMessage(
5489 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005490 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005491 mCurAppTimeTracker = null;
5492 }
5493 if (r.appTimeTracker != null) {
5494 mCurAppTimeTracker = r.appTimeTracker;
5495 startTimeTrackingFocusedActivityLocked();
5496 }
5497 } else {
5498 startTimeTrackingFocusedActivityLocked();
5499 }
5500 } else {
5501 r.appTimeTracker = null;
5502 }
5503 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5504 // TODO: Probably not, because we don't want to resume voice on switching
5505 // back to this activity
5506 if (task.voiceInteractor != null) {
5507 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5508 } else {
5509 finishRunningVoiceLocked();
5510
5511 if (mLastResumedActivity != null) {
5512 final IVoiceInteractionSession session;
5513
Louis Changcdec0802019-11-11 11:45:07 +08005514 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005515 if (lastResumedActivityTask != null
5516 && lastResumedActivityTask.voiceSession != null) {
5517 session = lastResumedActivityTask.voiceSession;
5518 } else {
5519 session = mLastResumedActivity.voiceSession;
5520 }
5521
5522 if (session != null) {
5523 // We had been in a voice interaction session, but now focused has
5524 // move to something different. Just finish the session, we can't
5525 // return to it and retain the proper state and synchronization with
5526 // the voice interaction service.
5527 finishVoiceTask(session);
5528 }
5529 }
5530 }
5531
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005532 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5533 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005534 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005535 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5536
Wale Ogunwalef6733932018-06-27 05:14:34 -07005537 updateResumedAppTrace(r);
5538 mLastResumedActivity = r;
5539
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005540 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005541
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005542 if (prevTask == null || task != prevTask) {
5543 if (prevTask != null) {
5544 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5545 }
5546 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5547 }
5548
Wale Ogunwalef6733932018-06-27 05:14:34 -07005549 applyUpdateLockStateLocked(r);
5550 applyUpdateVrModeLocked(r);
5551
Jeff Changd136e772019-11-05 20:33:52 +08005552 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005553 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005554 r == null ? "NULL" : r.shortComponentName,
5555 reason);
5556 }
5557
5558 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5559 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005560 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005561 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005562 updateSleepIfNeededLocked();
5563 return token;
5564 }
5565 }
5566
5567 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005568 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005569 final boolean wasSleeping = mSleeping;
5570 boolean updateOomAdj = false;
5571
5572 if (!shouldSleep) {
5573 // If wasSleeping is true, we need to wake up activity manager state from when
5574 // we started sleeping. In either case, we need to apply the sleep tokens, which
5575 // will wake up stacks or put them to sleep as appropriate.
5576 if (wasSleeping) {
5577 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005578 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5579 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005580 startTimeTrackingFocusedActivityLocked();
5581 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005582 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005583 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5584 }
Louis Chang149d5c82019-12-30 09:47:39 +08005585 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005586 if (wasSleeping) {
5587 updateOomAdj = true;
5588 }
5589 } else if (!mSleeping && shouldSleep) {
5590 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005591 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5592 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005593 if (mCurAppTimeTracker != null) {
5594 mCurAppTimeTracker.stop();
5595 }
5596 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005597 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005598 mStackSupervisor.goingToSleepLocked();
5599 updateResumedAppTrace(null /* resumed */);
5600 updateOomAdj = true;
5601 }
5602 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005603 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005604 }
5605 }
5606
5607 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005608 mH.removeCallbacks(mUpdateOomAdjRunnable);
5609 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005610 }
5611
Wale Ogunwale53783742018-09-16 10:21:51 -07005612 void updateCpuStats() {
5613 mH.post(mAmInternal::updateCpuStats);
5614 }
5615
Hui Yu03d12402018-12-06 18:00:37 -08005616 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5617 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005618 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5619 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005620 mH.sendMessage(m);
5621 }
5622
Hui Yu03d12402018-12-06 18:00:37 -08005623 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005624 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005625 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005626 if (task != null) {
5627 final ActivityRecord rootActivity = task.getRootActivity();
5628 if (rootActivity != null) {
5629 taskRoot = rootActivity.mActivityComponent;
5630 }
5631 }
5632
Hui Yu03d12402018-12-06 18:00:37 -08005633 final Message m = PooledLambda.obtainMessage(
5634 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005635 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005636 mH.sendMessage(m);
5637 }
5638
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005639 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5640 String hostingType) {
5641 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005642 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5643 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005644 + activity.processName);
5645 }
5646 // Post message to start process to avoid possible deadlock of calling into AMS with the
5647 // ATMS lock held.
5648 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5649 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5650 isTop, hostingType, activity.intent.getComponent());
5651 mH.sendMessage(m);
5652 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005653 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005654 }
5655 }
5656
Wale Ogunwale53783742018-09-16 10:21:51 -07005657 void setBooting(boolean booting) {
5658 mAmInternal.setBooting(booting);
5659 }
5660
5661 boolean isBooting() {
5662 return mAmInternal.isBooting();
5663 }
5664
5665 void setBooted(boolean booted) {
5666 mAmInternal.setBooted(booted);
5667 }
5668
5669 boolean isBooted() {
5670 return mAmInternal.isBooted();
5671 }
5672
5673 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5674 mH.post(() -> {
5675 if (finishBooting) {
5676 mAmInternal.finishBooting();
5677 }
5678 if (enableScreen) {
5679 mInternal.enableScreenAfterBoot(isBooted());
5680 }
5681 });
5682 }
5683
5684 void setHeavyWeightProcess(ActivityRecord root) {
5685 mHeavyWeightProcess = root.app;
5686 final Message m = PooledLambda.obtainMessage(
5687 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005688 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005689 mH.sendMessage(m);
5690 }
5691
5692 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5693 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5694 return;
5695 }
5696
5697 mHeavyWeightProcess = null;
5698 final Message m = PooledLambda.obtainMessage(
5699 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5700 proc.mUserId);
5701 mH.sendMessage(m);
5702 }
5703
5704 private void cancelHeavyWeightProcessNotification(int userId) {
5705 final INotificationManager inm = NotificationManager.getService();
5706 if (inm == null) {
5707 return;
5708 }
5709 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005710 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005711 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5712 } catch (RuntimeException e) {
5713 Slog.w(TAG, "Error canceling notification for service", e);
5714 } catch (RemoteException e) {
5715 }
5716
5717 }
5718
5719 private void postHeavyWeightProcessNotification(
5720 WindowProcessController proc, Intent intent, int userId) {
5721 if (proc == null) {
5722 return;
5723 }
5724
5725 final INotificationManager inm = NotificationManager.getService();
5726 if (inm == null) {
5727 return;
5728 }
5729
5730 try {
5731 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5732 String text = mContext.getString(R.string.heavy_weight_notification,
5733 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5734 Notification notification =
5735 new Notification.Builder(context,
5736 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5737 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5738 .setWhen(0)
5739 .setOngoing(true)
5740 .setTicker(text)
5741 .setColor(mContext.getColor(
5742 com.android.internal.R.color.system_notification_accent_color))
5743 .setContentTitle(text)
5744 .setContentText(
5745 mContext.getText(R.string.heavy_weight_notification_detail))
5746 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5747 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5748 new UserHandle(userId)))
5749 .build();
5750 try {
5751 inm.enqueueNotificationWithTag("android", "android", null,
5752 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5753 } catch (RuntimeException e) {
5754 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5755 } catch (RemoteException e) {
5756 }
5757 } catch (PackageManager.NameNotFoundException e) {
5758 Slog.w(TAG, "Unable to create context for heavy notification", e);
5759 }
5760
5761 }
5762
Philip P. Moltmannee295092020-02-10 08:46:26 -08005763 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5764 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5765 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005766
5767 ActivityRecord activity = null;
5768 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5769 activity = ActivityRecord.isInStackLocked(token);
5770 if (activity == null) {
5771 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5772 return null;
5773 }
5774 if (activity.finishing) {
5775 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5776 return null;
5777 }
5778 }
5779
5780 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005781 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5782 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005783 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5784 if (noCreate) {
5785 return rec;
5786 }
5787 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5788 if (activity.pendingResults == null) {
5789 activity.pendingResults = new HashSet<>();
5790 }
5791 activity.pendingResults.add(rec.ref);
5792 }
5793 return rec;
5794 }
5795
Andrii Kulian52d255c2018-07-13 11:32:19 -07005796 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005797 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005798 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005799 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5800 mCurAppTimeTracker.start(resumedActivity.packageName);
5801 }
5802 }
5803
5804 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5805 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005806 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005807 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5808 }
5809 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005810 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005811 constructResumedTraceName(resumed.packageName), 0);
5812 }
5813 mTracedResumedActivity = resumed;
5814 }
5815
5816 private String constructResumedTraceName(String packageName) {
5817 return "focused app: " + packageName;
5818 }
5819
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005820 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005821 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005822 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005823 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005824 // mainStack is null during startup.
5825 if (mainStack != null) {
5826 if (changes != 0 && starting == null) {
5827 // If the configuration changed, and the caller is not already
5828 // in the process of starting an activity, then find the top
5829 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005830 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005831 }
5832
5833 if (starting != null) {
5834 kept = starting.ensureActivityConfiguration(changes,
5835 false /* preserveWindow */);
5836 // And we need to make sure at this point that all other activities
5837 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005838 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005839 !PRESERVE_WINDOWS);
5840 }
5841 }
5842
5843 return kept;
5844 }
5845
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005846 void scheduleAppGcsLocked() {
5847 mH.post(() -> mAmInternal.scheduleAppGcs());
5848 }
5849
Wale Ogunwale53783742018-09-16 10:21:51 -07005850 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5851 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5852 }
5853
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005854 /**
5855 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5856 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5857 * on demand.
5858 */
5859 IPackageManager getPackageManager() {
5860 return AppGlobals.getPackageManager();
5861 }
5862
5863 PackageManagerInternal getPackageManagerInternalLocked() {
5864 if (mPmInternal == null) {
5865 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5866 }
5867 return mPmInternal;
5868 }
5869
Darryl L Johnsona0982222020-02-18 18:21:51 -08005870 ComponentName getSysUiServiceComponentLocked() {
5871 if (mSysUiServiceComponent == null) {
5872 final PackageManagerInternal pm = getPackageManagerInternalLocked();
5873 mSysUiServiceComponent = pm.getSystemUiServiceComponent();
5874 }
5875 return mSysUiServiceComponent;
5876 }
5877
Hai Zhangf4da9be2019-05-01 13:46:06 +08005878 PermissionPolicyInternal getPermissionPolicyInternal() {
5879 if (mPermissionPolicyInternal == null) {
5880 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5881 }
5882 return mPermissionPolicyInternal;
5883 }
5884
Wale Ogunwale008163e2018-07-23 23:11:08 -07005885 AppWarnings getAppWarningsLocked() {
5886 return mAppWarnings;
5887 }
5888
Wale Ogunwale214f3482018-10-04 11:00:47 -07005889 Intent getHomeIntent() {
5890 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5891 intent.setComponent(mTopComponent);
5892 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5893 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5894 intent.addCategory(Intent.CATEGORY_HOME);
5895 }
5896 return intent;
5897 }
5898
Chilun2ef71f72018-11-16 17:57:15 +08005899 /**
5900 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5901 * activities.
5902 *
Chilun939b05c2020-02-19 14:50:59 +08005903 * @param preferredPackage Specify a preferred package name, otherwise use the package name
5904 * defined in config_secondaryHomePackage.
Chilun2ef71f72018-11-16 17:57:15 +08005905 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5906 */
5907 Intent getSecondaryHomeIntent(String preferredPackage) {
5908 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005909 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5910 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5911 if (preferredPackage == null || useSystemProvidedLauncher) {
Chilun939b05c2020-02-19 14:50:59 +08005912 // Using the package name stored in config if no preferred package name or forced.
5913 final String secondaryHomePackage = mContext.getResources().getString(
5914 com.android.internal.R.string.config_secondaryHomePackage);
5915 intent.setPackage(secondaryHomePackage);
Chilun2ef71f72018-11-16 17:57:15 +08005916 } else {
5917 intent.setPackage(preferredPackage);
5918 }
5919 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5920 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5921 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5922 }
5923 return intent;
5924 }
5925
Wale Ogunwale214f3482018-10-04 11:00:47 -07005926 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5927 if (info == null) return null;
5928 ApplicationInfo newInfo = new ApplicationInfo(info);
5929 newInfo.initForUser(userId);
5930 return newInfo;
5931 }
5932
Wale Ogunwale9c103022018-10-18 07:44:54 -07005933 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005934 if (uid == SYSTEM_UID) {
5935 // The system gets to run in any process. If there are multiple processes with the same
5936 // uid, just pick the first (this should never happen).
5937 final SparseArray<WindowProcessController> procs =
5938 mProcessNames.getMap().get(processName);
5939 if (procs == null) return null;
5940 final int procCount = procs.size();
5941 for (int i = 0; i < procCount; i++) {
5942 final int procUid = procs.keyAt(i);
5943 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5944 // Don't use an app process or different user process for system component.
5945 continue;
5946 }
5947 return procs.valueAt(i);
5948 }
5949 }
5950
5951 return mProcessNames.get(processName, uid);
5952 }
5953
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005954 WindowProcessController getProcessController(IApplicationThread thread) {
5955 if (thread == null) {
5956 return null;
5957 }
5958
5959 final IBinder threadBinder = thread.asBinder();
5960 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5961 for (int i = pmap.size()-1; i >= 0; i--) {
5962 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5963 for (int j = procs.size() - 1; j >= 0; j--) {
5964 final WindowProcessController proc = procs.valueAt(j);
5965 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5966 return proc;
5967 }
5968 }
5969 }
5970
5971 return null;
5972 }
5973
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005974 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005975 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005976 if (proc == null) return null;
5977 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5978 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005979 }
5980 return null;
5981 }
5982
Riddle Hsua0536432019-02-16 00:38:59 +08005983 int getUidState(int uid) {
5984 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005985 }
5986
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005987 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005988 // A uid is considered to be foreground if it has a visible non-toast window.
5989 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005990 }
5991
Ricky Wai96f5c352019-04-10 18:40:17 +01005992 boolean isDeviceOwner(int uid) {
5993 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005994 }
5995
Ricky Wai96f5c352019-04-10 18:40:17 +01005996 void setDeviceOwnerUid(int uid) {
5997 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005998 }
5999
Wale Ogunwale9de19442018-10-18 19:05:03 -07006000 /**
6001 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6002 * the whitelist
6003 */
6004 String getPendingTempWhitelistTagForUidLocked(int uid) {
6005 return mPendingTempWhitelist.get(uid);
6006 }
6007
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006008 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6009 if (true || Build.IS_USER) {
6010 return;
6011 }
6012
6013 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6014 StrictMode.allowThreadDiskWrites();
6015 try {
6016 File tracesDir = new File("/data/anr");
6017 File tracesFile = null;
6018 try {
6019 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6020
6021 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006022 String timeString =
6023 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6024 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006025 sb.append(": ");
6026 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6027 sb.append(" since ");
6028 sb.append(msg);
6029 FileOutputStream fos = new FileOutputStream(tracesFile);
6030 fos.write(sb.toString().getBytes());
6031 if (app == null) {
6032 fos.write("\n*** No application process!".getBytes());
6033 }
6034 fos.close();
6035 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6036 } catch (IOException e) {
6037 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6038 return;
6039 }
6040
6041 if (app != null && app.getPid() > 0) {
6042 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6043 firstPids.add(app.getPid());
6044 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6045 }
6046
6047 File lastTracesFile = null;
6048 File curTracesFile = null;
6049 for (int i=9; i>=0; i--) {
6050 String name = String.format(Locale.US, "slow%02d.txt", i);
6051 curTracesFile = new File(tracesDir, name);
6052 if (curTracesFile.exists()) {
6053 if (lastTracesFile != null) {
6054 curTracesFile.renameTo(lastTracesFile);
6055 } else {
6056 curTracesFile.delete();
6057 }
6058 }
6059 lastTracesFile = curTracesFile;
6060 }
6061 tracesFile.renameTo(curTracesFile);
6062 } finally {
6063 StrictMode.setThreadPolicy(oldPolicy);
6064 }
6065 }
6066
Michal Karpinskida34cd42019-04-02 19:46:52 +01006067 boolean isAssociatedCompanionApp(int userId, int uid) {
6068 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6069 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006070 return false;
6071 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006072 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006073 }
6074
Issei Suzuki734bc942019-06-05 13:59:52 +02006075 void notifySingleTaskDisplayEmpty(int displayId) {
6076 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6077 }
6078
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006079 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006080 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006081
6082
Wale Ogunwale98875612018-10-12 07:53:02 -07006083 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6084 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006085
Riddle Hsud93a6c42018-11-29 21:50:06 +08006086 H(Looper looper) {
6087 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006088 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006089
6090 @Override
6091 public void handleMessage(Message msg) {
6092 switch (msg.what) {
6093 case REPORT_TIME_TRACKER_MSG: {
6094 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6095 tracker.deliverResult(mContext);
6096 } break;
6097 }
6098 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006099 }
6100
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006101 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006102 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006103
6104 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006105 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006106 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006107
6108 @Override
6109 public void handleMessage(Message msg) {
6110 switch (msg.what) {
6111 case DISMISS_DIALOG_UI_MSG: {
6112 final Dialog d = (Dialog) msg.obj;
6113 d.dismiss();
6114 break;
6115 }
6116 }
6117 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006118 }
6119
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006120 final class LocalService extends ActivityTaskManagerInternal {
6121 @Override
6122 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006123 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006124 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006125 }
6126
6127 @Override
6128 public ComponentName getHomeActivityForUser(int userId) {
6129 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006130 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006131 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006132 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006133 }
6134 }
6135
6136 @Override
6137 public void onLocalVoiceInteractionStarted(IBinder activity,
6138 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6139 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006140 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006141 }
6142 }
6143
6144 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006145 public void notifySingleTaskDisplayDrawn(int displayId) {
6146 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6147 }
6148
6149 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006150 public void notifyAppTransitionFinished() {
6151 synchronized (mGlobalLock) {
6152 mStackSupervisor.notifyAppTransitionDone();
6153 }
6154 }
6155
6156 @Override
6157 public void notifyAppTransitionCancelled() {
6158 synchronized (mGlobalLock) {
6159 mStackSupervisor.notifyAppTransitionDone();
6160 }
6161 }
6162
6163 @Override
6164 public List<IBinder> getTopVisibleActivities() {
6165 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006166 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006167 }
6168 }
6169
6170 @Override
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00006171 public boolean hasResumedActivity(int uid) {
6172 synchronized (mGlobalLock) {
6173 final ArraySet<WindowProcessController> processes = mProcessMap.getProcesses(uid);
6174 for (int i = 0, n = processes.size(); i < n; i++) {
6175 final WindowProcessController process = processes.valueAt(i);
6176 if (process.hasResumedActivity()) {
6177 return true;
6178 }
6179 }
6180 }
6181 return false;
6182 }
6183
6184 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006185 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6186 int userId, Intent[] intents, 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(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006211 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006212 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,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006220 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6221 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6222 boolean validateIncomingUser, 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,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006227 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6228 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006229 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006230 }
6231 }
6232
6233 @Override
6234 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006235 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6236 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6237 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6238 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006239 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,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006243 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6244 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6245 reason, validateIncomingUser, originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006246 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006247 }
6248 }
6249
6250 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006251 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006252 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6253 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006254 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006255 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006256 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006257 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006258 false /*validateIncomingUser*/);
6259 }
6260
6261 @Override
lumark588a3e82018-07-20 18:53:54 +08006262 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006263 synchronized (mGlobalLock) {
6264
6265 // We might change the visibilities here, so prepare an empty app transition which
6266 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006267 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006268 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006269 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006270 return;
6271 }
Louis Chang677921f2019-12-06 16:44:24 +08006272 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006273 final boolean wasTransitionSet =
6274 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006275 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006276 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006277 }
Louis Chang149d5c82019-12-30 09:47:39 +08006278 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006279
6280 // If there was a transition set already we don't want to interfere with it as we
6281 // might be starting it too early.
6282 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006283 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006284 }
6285 }
6286 if (callback != null) {
6287 callback.run();
6288 }
6289 }
6290
6291 @Override
6292 public void notifyKeyguardTrustedChanged() {
6293 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006294 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006295 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006296 }
6297 }
6298 }
6299
6300 /**
6301 * Called after virtual display Id is updated by
6302 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6303 * {@param vrVr2dDisplayId}.
6304 */
6305 @Override
6306 public void setVr2dDisplayId(int vr2dDisplayId) {
6307 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6308 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006309 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006310 }
6311 }
6312
6313 @Override
6314 public void setFocusedActivity(IBinder token) {
6315 synchronized (mGlobalLock) {
6316 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6317 if (r == null) {
6318 throw new IllegalArgumentException(
6319 "setFocusedActivity: No activity record matching token=" + token);
6320 }
Louis Chang19443452018-10-09 12:10:21 +08006321 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006322 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006323 }
6324 }
6325 }
6326
6327 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006328 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006329 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006330 }
6331
6332 @Override
6333 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006334 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006335 }
6336
6337 @Override
6338 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006339 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006340 }
6341
6342 @Override
6343 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6344 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6345 }
6346
6347 @Override
6348 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006349 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006350 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006351
6352 @Override
6353 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6354 synchronized (mGlobalLock) {
6355 mActiveVoiceInteractionServiceComponent = component;
6356 }
6357 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006358
6359 @Override
6360 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6361 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6362 return;
6363 }
6364 synchronized (mGlobalLock) {
6365 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6366 if (types == null) {
6367 if (uid < 0) {
6368 return;
6369 }
6370 types = new ArrayMap<>();
6371 mAllowAppSwitchUids.put(userId, types);
6372 }
6373 if (uid < 0) {
6374 types.remove(type);
6375 } else {
6376 types.put(type, uid);
6377 }
6378 }
6379 }
6380
6381 @Override
6382 public void onUserStopped(int userId) {
6383 synchronized (mGlobalLock) {
6384 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6385 mAllowAppSwitchUids.remove(userId);
6386 }
6387 }
6388
6389 @Override
6390 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6391 synchronized (mGlobalLock) {
6392 return ActivityTaskManagerService.this.isGetTasksAllowed(
6393 caller, callingPid, callingUid);
6394 }
6395 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006396
Riddle Hsua0536432019-02-16 00:38:59 +08006397 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006398 @Override
6399 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006400 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006401 mProcessNames.put(proc.mName, proc.mUid, proc);
6402 }
6403 }
6404
Riddle Hsua0536432019-02-16 00:38:59 +08006405 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006406 @Override
6407 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006408 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006409 mProcessNames.remove(name, uid);
6410 }
6411 }
6412
Riddle Hsua0536432019-02-16 00:38:59 +08006413 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006414 @Override
6415 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006416 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006417 if (proc == mHomeProcess) {
6418 mHomeProcess = null;
6419 }
6420 if (proc == mPreviousProcess) {
6421 mPreviousProcess = null;
6422 }
6423 }
6424 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006425
Riddle Hsua0536432019-02-16 00:38:59 +08006426 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006427 @Override
6428 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006429 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006430 return mTopProcessState;
6431 }
6432 }
6433
Riddle Hsua0536432019-02-16 00:38:59 +08006434 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006435 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006436 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006437 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006438 return proc == mHeavyWeightProcess;
6439 }
6440 }
6441
Riddle Hsua0536432019-02-16 00:38:59 +08006442 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006443 @Override
6444 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006445 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006446 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6447 }
6448 }
6449
6450 @Override
6451 public void finishHeavyWeightApp() {
6452 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006453 if (mHeavyWeightProcess != null) {
6454 mHeavyWeightProcess.finishActivities();
6455 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006456 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6457 mHeavyWeightProcess);
6458 }
6459 }
6460
Riddle Hsua0536432019-02-16 00:38:59 +08006461 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006462 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006463 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006464 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006465 return isSleepingLocked();
6466 }
6467 }
6468
6469 @Override
6470 public boolean isShuttingDown() {
6471 synchronized (mGlobalLock) {
6472 return mShuttingDown;
6473 }
6474 }
6475
6476 @Override
6477 public boolean shuttingDown(boolean booted, int timeout) {
6478 synchronized (mGlobalLock) {
6479 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006480 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006481 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006482 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006483 return mStackSupervisor.shutdownLocked(timeout);
6484 }
6485 }
6486
6487 @Override
6488 public void enableScreenAfterBoot(boolean booted) {
6489 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006490 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006491 mWindowManager.enableScreenAfterBoot();
6492 updateEventDispatchingLocked(booted);
6493 }
6494 }
6495
6496 @Override
6497 public boolean showStrictModeViolationDialog() {
6498 synchronized (mGlobalLock) {
6499 return mShowDialogs && !mSleeping && !mShuttingDown;
6500 }
6501 }
6502
6503 @Override
6504 public void showSystemReadyErrorDialogsIfNeeded() {
6505 synchronized (mGlobalLock) {
6506 try {
6507 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6508 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6509 + " data partition or your device will be unstable.");
6510 mUiHandler.post(() -> {
6511 if (mShowDialogs) {
6512 AlertDialog d = new BaseErrorDialog(mUiContext);
6513 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6514 d.setCancelable(false);
6515 d.setTitle(mUiContext.getText(R.string.android_system_label));
6516 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6517 d.setButton(DialogInterface.BUTTON_POSITIVE,
6518 mUiContext.getText(R.string.ok),
6519 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6520 d.show();
6521 }
6522 });
6523 }
6524 } catch (RemoteException e) {
6525 }
6526
6527 if (!Build.isBuildConsistent()) {
6528 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6529 mUiHandler.post(() -> {
6530 if (mShowDialogs) {
6531 AlertDialog d = new BaseErrorDialog(mUiContext);
6532 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6533 d.setCancelable(false);
6534 d.setTitle(mUiContext.getText(R.string.android_system_label));
6535 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6536 d.setButton(DialogInterface.BUTTON_POSITIVE,
6537 mUiContext.getText(R.string.ok),
6538 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6539 d.show();
6540 }
6541 });
6542 }
6543 }
6544 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006545
6546 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006547 public void onProcessMapped(int pid, WindowProcessController proc) {
6548 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006549 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006550 }
6551 }
6552
6553 @Override
6554 public void onProcessUnMapped(int pid) {
6555 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006556 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006557 }
6558 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006559
6560 @Override
6561 public void onPackageDataCleared(String name) {
6562 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006563 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006564 mAppWarnings.onPackageDataCleared(name);
6565 }
6566 }
6567
6568 @Override
6569 public void onPackageUninstalled(String name) {
6570 synchronized (mGlobalLock) {
6571 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006572 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006573 }
6574 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006575
6576 @Override
6577 public void onPackageAdded(String name, boolean replacing) {
6578 synchronized (mGlobalLock) {
6579 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6580 }
6581 }
6582
6583 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006584 public void onPackageReplaced(ApplicationInfo aInfo) {
6585 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006586 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006587 }
6588 }
6589
6590 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006591 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6592 synchronized (mGlobalLock) {
6593 return compatibilityInfoForPackageLocked(ai);
6594 }
6595 }
6596
Yunfan Chen75157d72018-07-27 14:47:21 +09006597 /**
6598 * Set the corresponding display information for the process global configuration. To be
6599 * called when we need to show IME on a different display.
6600 *
6601 * @param pid The process id associated with the IME window.
6602 * @param displayId The ID of the display showing the IME.
6603 */
6604 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006605 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006606 // Don't update process-level configuration for Multi-Client IME process since other
6607 // IMEs on other displays will also receive this configuration change due to IME
6608 // services use the same application config/context.
6609 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006610
Yunfan Chen75157d72018-07-27 14:47:21 +09006611 if (pid == MY_PID || pid < 0) {
6612 if (DEBUG_CONFIGURATION) {
6613 Slog.w(TAG,
6614 "Trying to update display configuration for system/invalid process.");
6615 }
6616 return;
6617 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006618 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006619 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006620 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006621 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006622 // Call might come when display is not yet added or has been removed.
6623 if (DEBUG_CONFIGURATION) {
6624 Slog.w(TAG, "Trying to update display configuration for non-existing "
6625 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006626 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006627 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006628 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006629 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006630 if (process == null) {
6631 if (DEBUG_CONFIGURATION) {
6632 Slog.w(TAG, "Trying to update display configuration for invalid "
6633 + "process, pid=" + pid);
6634 }
6635 return;
6636 }
lumarkddc77fb2019-06-27 22:22:23 +08006637 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006638 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006639 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006640 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006641
6642 @Override
6643 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006644 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006645 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006646 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006647 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006648 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006649 }
6650 }
6651 }
6652
6653 @Override
6654 public void clearPendingResultForActivity(IBinder activityToken,
6655 WeakReference<PendingIntentRecord> pir) {
6656 synchronized (mGlobalLock) {
6657 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6658 if (r != null && r.pendingResults != null) {
6659 r.pendingResults.remove(pir);
6660 }
6661 }
6662 }
6663
6664 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006665 public ActivityTokens getTopActivityForTask(int taskId) {
6666 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006667 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006668 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006669 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6670 + " Requested task not found");
6671 return null;
6672 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006673 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006674 if (activity == null) {
6675 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6676 + " Requested activity not found");
6677 return null;
6678 }
6679 if (!activity.attachedToProcess()) {
6680 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6681 + activity);
6682 return null;
6683 }
6684 return new ActivityTokens(activity.appToken, activity.assistToken,
6685 activity.app.getThread());
6686 }
6687 }
6688
6689 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006690 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006691 @Nullable String featureId, int callingUid, int userId, IBinder token,
6692 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6693 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006694 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006695 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6696 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006697 }
6698 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006699
6700 @Override
6701 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6702 synchronized (mGlobalLock) {
6703 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6704 if (r == null) {
6705 return null;
6706 }
6707 if (r.mServiceConnectionsHolder == null) {
6708 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6709 ActivityTaskManagerService.this, r);
6710 }
6711
6712 return r.mServiceConnectionsHolder;
6713 }
6714 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006715
6716 @Override
6717 public Intent getHomeIntent() {
6718 synchronized (mGlobalLock) {
6719 return ActivityTaskManagerService.this.getHomeIntent();
6720 }
6721 }
6722
6723 @Override
6724 public boolean startHomeActivity(int userId, String reason) {
6725 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006726 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006727 }
6728 }
6729
6730 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006731 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006732 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006733 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006734 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006735 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006736 }
Chilun8b1f1be2019-03-13 17:14:36 +08006737 }
6738
6739 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006740 public boolean startHomeOnAllDisplays(int userId, String reason) {
6741 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006742 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006743 }
6744 }
6745
Riddle Hsua0536432019-02-16 00:38:59 +08006746 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006747 @Override
6748 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006749 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006750 if (mFactoryTest == FACTORY_TEST_OFF) {
6751 return false;
6752 }
6753 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6754 && wpc.mName.equals(mTopComponent.getPackageName())) {
6755 return true;
6756 }
6757 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6758 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6759 }
6760 }
6761
6762 @Override
6763 public void updateTopComponentForFactoryTest() {
6764 synchronized (mGlobalLock) {
6765 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6766 return;
6767 }
6768 final ResolveInfo ri = mContext.getPackageManager()
6769 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6770 final CharSequence errorMsg;
6771 if (ri != null) {
6772 final ActivityInfo ai = ri.activityInfo;
6773 final ApplicationInfo app = ai.applicationInfo;
6774 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6775 mTopAction = Intent.ACTION_FACTORY_TEST;
6776 mTopData = null;
6777 mTopComponent = new ComponentName(app.packageName, ai.name);
6778 errorMsg = null;
6779 } else {
6780 errorMsg = mContext.getResources().getText(
6781 com.android.internal.R.string.factorytest_not_system);
6782 }
6783 } else {
6784 errorMsg = mContext.getResources().getText(
6785 com.android.internal.R.string.factorytest_no_action);
6786 }
6787 if (errorMsg == null) {
6788 return;
6789 }
6790
6791 mTopAction = null;
6792 mTopData = null;
6793 mTopComponent = null;
6794 mUiHandler.post(() -> {
6795 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6796 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006797 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006798 });
6799 }
6800 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006801
Riddle Hsua0536432019-02-16 00:38:59 +08006802 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006803 @Override
6804 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6805 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006806 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006807 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006808 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006809
6810 wpc.clearRecentTasks();
6811 wpc.clearActivities();
6812
6813 if (wpc.isInstrumenting()) {
6814 finishInstrumentationCallback.run();
6815 }
6816
Jorim Jaggid0752812018-10-16 16:07:20 +02006817 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006818 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006819 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006820 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006821 // If there was nothing to resume, and we are not already restarting
6822 // this process, but there is a visible activity that is hosted by the
6823 // process...then make sure all visible activities are running, taking
6824 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006825 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006826 !PRESERVE_WINDOWS);
6827 }
6828 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006829 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006830 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006831 }
6832 }
6833 }
6834
6835 @Override
6836 public void closeSystemDialogs(String reason) {
6837 enforceNotIsolatedCaller("closeSystemDialogs");
6838
6839 final int pid = Binder.getCallingPid();
6840 final int uid = Binder.getCallingUid();
6841 final long origId = Binder.clearCallingIdentity();
6842 try {
6843 synchronized (mGlobalLock) {
6844 // Only allow this from foreground processes, so that background
6845 // applications can't abuse it to prevent system UI from being shown.
6846 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006847 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006848 if (!proc.isPerceptible()) {
6849 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6850 + " from background process " + proc);
6851 return;
6852 }
6853 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006854 mWindowManager.closeSystemDialogs(reason);
6855
Louis Chang149d5c82019-12-30 09:47:39 +08006856 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006857 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006858 // Call into AM outside the synchronized block.
6859 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006860 } finally {
6861 Binder.restoreCallingIdentity(origId);
6862 }
6863 }
6864
6865 @Override
6866 public void cleanupDisabledPackageComponents(
6867 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6868 synchronized (mGlobalLock) {
6869 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006870 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006871 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006872 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006873 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006874 }
6875
6876 // Clean-up disabled tasks
6877 getRecentTasks().cleanupDisabledPackageTasksLocked(
6878 packageName, disabledClasses, userId);
6879 }
6880 }
6881
6882 @Override
6883 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6884 int userId) {
6885 synchronized (mGlobalLock) {
6886
6887 boolean didSomething =
6888 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006889 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006890 null, doit, evenPersistent, userId);
6891 return didSomething;
6892 }
6893 }
6894
6895 @Override
6896 public void resumeTopActivities(boolean scheduleIdle) {
6897 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006898 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006899 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006900 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006901 }
6902 }
6903 }
6904
Riddle Hsua0536432019-02-16 00:38:59 +08006905 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006906 @Override
6907 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006908 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006909 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6910 }
6911 }
6912
Riddle Hsua0536432019-02-16 00:38:59 +08006913 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006914 @Override
6915 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006916 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006917 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6918 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6919 }
6920 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006921 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006922 } finally {
6923 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6924 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006925 }
6926 }
6927
6928 @Override
6929 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6930 try {
6931 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6932 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6933 }
6934 } catch (RemoteException ex) {
6935 throw new SecurityException("Fail to check is caller a privileged app", ex);
6936 }
6937
6938 synchronized (mGlobalLock) {
6939 final long ident = Binder.clearCallingIdentity();
6940 try {
6941 if (mAmInternal.shouldConfirmCredentials(userId)) {
6942 if (mKeyguardController.isKeyguardLocked()) {
6943 // Showing launcher to avoid user entering credential twice.
6944 startHomeActivity(currentUserId, "notifyLockedProfile");
6945 }
Louis Chang149d5c82019-12-30 09:47:39 +08006946 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006947 }
6948 } finally {
6949 Binder.restoreCallingIdentity(ident);
6950 }
6951 }
6952 }
6953
6954 @Override
6955 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6956 mAmInternal.enforceCallingPermission(
6957 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6958
6959 synchronized (mGlobalLock) {
6960 final long ident = Binder.clearCallingIdentity();
6961 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006962 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6963 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006964 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006965 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6966 UserHandle.CURRENT);
6967 } finally {
6968 Binder.restoreCallingIdentity(ident);
6969 }
6970 }
6971 }
6972
6973 @Override
6974 public void writeActivitiesToProto(ProtoOutputStream proto) {
6975 synchronized (mGlobalLock) {
6976 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006977 mRootWindowContainer.dumpDebug(
6978 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006979 }
6980 }
6981
6982 @Override
6983 public void saveANRState(String reason) {
6984 synchronized (mGlobalLock) {
6985 final StringWriter sw = new StringWriter();
6986 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6987 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6988 if (reason != null) {
6989 pw.println(" Reason: " + reason);
6990 }
6991 pw.println();
6992 getActivityStartController().dump(pw, " ", null);
6993 pw.println();
6994 pw.println("-------------------------------------------------------------------------------");
6995 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6996 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6997 "" /* header */);
6998 pw.println();
6999 pw.close();
7000
7001 mLastANRState = sw.toString();
7002 }
7003 }
7004
7005 @Override
7006 public void clearSavedANRState() {
7007 synchronized (mGlobalLock) {
7008 mLastANRState = null;
7009 }
7010 }
7011
7012 @Override
7013 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7014 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7015 synchronized (mGlobalLock) {
7016 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7017 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7018 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7019 dumpLastANRLocked(pw);
7020 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7021 dumpLastANRTracesLocked(pw);
7022 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7023 dumpActivityStarterLocked(pw, dumpPackage);
7024 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7025 dumpActivityContainersLocked(pw);
7026 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7027 if (getRecentTasks() != null) {
7028 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7029 }
7030 }
7031 }
7032 }
7033
7034 @Override
7035 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7036 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7037 int wakefulness) {
7038 synchronized (mGlobalLock) {
7039 if (mHomeProcess != null && (dumpPackage == null
7040 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7041 if (needSep) {
7042 pw.println();
7043 needSep = false;
7044 }
7045 pw.println(" mHomeProcess: " + mHomeProcess);
7046 }
7047 if (mPreviousProcess != null && (dumpPackage == null
7048 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7049 if (needSep) {
7050 pw.println();
7051 needSep = false;
7052 }
7053 pw.println(" mPreviousProcess: " + mPreviousProcess);
7054 }
7055 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7056 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7057 StringBuilder sb = new StringBuilder(128);
7058 sb.append(" mPreviousProcessVisibleTime: ");
7059 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7060 pw.println(sb);
7061 }
7062 if (mHeavyWeightProcess != null && (dumpPackage == null
7063 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7064 if (needSep) {
7065 pw.println();
7066 needSep = false;
7067 }
7068 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7069 }
7070 if (dumpPackage == null) {
7071 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007072 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007073 }
7074 if (dumpAll) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007075 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7076 if (dumpPackage == null && topFocusedStack != null) {
7077 pw.println(" mConfigWillChange: " + topFocusedStack.mConfigWillChange);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007078 }
7079 if (mCompatModePackages.getPackages().size() > 0) {
7080 boolean printed = false;
7081 for (Map.Entry<String, Integer> entry
7082 : mCompatModePackages.getPackages().entrySet()) {
7083 String pkg = entry.getKey();
7084 int mode = entry.getValue();
7085 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7086 continue;
7087 }
7088 if (!printed) {
7089 pw.println(" mScreenCompatPackages:");
7090 printed = true;
7091 }
7092 pw.println(" " + pkg + ": " + mode);
7093 }
7094 }
7095 }
7096
7097 if (dumpPackage == null) {
7098 pw.println(" mWakefulness="
7099 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007100 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007101 if (mRunningVoice != null) {
7102 pw.println(" mRunningVoice=" + mRunningVoice);
7103 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7104 }
7105 pw.println(" mSleeping=" + mSleeping);
7106 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7107 pw.println(" mVrController=" + mVrController);
7108 }
7109 if (mCurAppTimeTracker != null) {
7110 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7111 }
7112 if (mAllowAppSwitchUids.size() > 0) {
7113 boolean printed = false;
7114 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7115 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7116 for (int j = 0; j < types.size(); j++) {
7117 if (dumpPackage == null ||
7118 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7119 if (needSep) {
7120 pw.println();
7121 needSep = false;
7122 }
7123 if (!printed) {
7124 pw.println(" mAllowAppSwitchUids:");
7125 printed = true;
7126 }
7127 pw.print(" User ");
7128 pw.print(mAllowAppSwitchUids.keyAt(i));
7129 pw.print(": Type ");
7130 pw.print(types.keyAt(j));
7131 pw.print(" = ");
7132 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7133 pw.println();
7134 }
7135 }
7136 }
7137 }
7138 if (dumpPackage == null) {
7139 if (mController != null) {
7140 pw.println(" mController=" + mController
7141 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7142 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007143 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7144 pw.println(" mLaunchingActivityWakeLock="
7145 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007146 }
7147
7148 return needSep;
7149 }
7150 }
7151
7152 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007153 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7154 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007155 synchronized (mGlobalLock) {
7156 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007157 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007158 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7159 if (topFocusedStack != null) {
7160 proto.write(CONFIG_WILL_CHANGE, topFocusedStack.mConfigWillChange);
7161 }
sanryhuang498e77e2018-12-06 14:57:01 +08007162 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7163 if (mRunningVoice != null) {
7164 final long vrToken = proto.start(
7165 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7166 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7167 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007168 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007169 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7170 proto.end(vrToken);
7171 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007172 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007173 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007174 if (mController != null) {
7175 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007176 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7177 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007178 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7179 proto.end(token);
7180 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007181 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7182 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007183 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007184 }
7185
7186 if (mHomeProcess != null && (dumpPackage == null
7187 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007188 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007189 }
7190
7191 if (mPreviousProcess != null && (dumpPackage == null
7192 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007193 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007194 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7195 }
7196
7197 if (mHeavyWeightProcess != null && (dumpPackage == null
7198 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007199 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007200 }
7201
7202 for (Map.Entry<String, Integer> entry
7203 : mCompatModePackages.getPackages().entrySet()) {
7204 String pkg = entry.getKey();
7205 int mode = entry.getValue();
7206 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7207 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7208 proto.write(PACKAGE, pkg);
7209 proto.write(MODE, mode);
7210 proto.end(compatToken);
7211 }
7212 }
7213
7214 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007215 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007216 }
7217
7218 }
7219 }
7220
7221 @Override
7222 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7223 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7224 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007225 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7226 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007227 }
7228
7229 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007230 public void dumpForOom(PrintWriter pw) {
7231 synchronized (mGlobalLock) {
7232 pw.println(" mHomeProcess: " + mHomeProcess);
7233 pw.println(" mPreviousProcess: " + mPreviousProcess);
7234 if (mHeavyWeightProcess != null) {
7235 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7236 }
7237 }
7238 }
7239
7240 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007241 public boolean canGcNow() {
7242 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007243 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007244 }
7245 }
7246
Riddle Hsua0536432019-02-16 00:38:59 +08007247 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007248 @Override
7249 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007250 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007251 if (mRootWindowContainer == null) {
7252 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007253 // oomadj after AMS created.
7254 return null;
7255 }
Louis Chang149d5c82019-12-30 09:47:39 +08007256 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007257 return top != null ? top.app : null;
7258 }
7259 }
7260
Riddle Hsua0536432019-02-16 00:38:59 +08007261 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007262 @Override
7263 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007264 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007265 if (mRootWindowContainer != null) {
7266 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007267 }
7268 }
7269 }
7270
7271 @Override
7272 public void scheduleDestroyAllActivities(String reason) {
7273 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007274 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007275 }
7276 }
7277
7278 @Override
7279 public void removeUser(int userId) {
7280 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007281 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007282 }
7283 }
7284
7285 @Override
7286 public boolean switchUser(int userId, UserState userState) {
7287 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007288 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007289 }
7290 }
7291
7292 @Override
7293 public void onHandleAppCrash(WindowProcessController wpc) {
7294 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007295 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007296 }
7297 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007298
7299 @Override
7300 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7301 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007302 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007303 }
7304 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007305
Riddle Hsua0536432019-02-16 00:38:59 +08007306 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007307 @Override
7308 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007309 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007310 }
7311
Riddle Hsua0536432019-02-16 00:38:59 +08007312 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007313 @Override
7314 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007315 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007316 }
7317
Riddle Hsua0536432019-02-16 00:38:59 +08007318 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007319 @Override
7320 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007321 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007322 }
7323
Riddle Hsua0536432019-02-16 00:38:59 +08007324 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007325 @Override
7326 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007327 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007328 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007329
7330 @Override
7331 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007332 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007333 mPendingTempWhitelist.put(uid, tag);
7334 }
7335 }
7336
7337 @Override
7338 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007339 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007340 mPendingTempWhitelist.remove(uid);
7341 }
7342 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007343
7344 @Override
7345 public boolean handleAppCrashInActivityController(String processName, int pid,
7346 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7347 Runnable killCrashingAppCallback) {
7348 synchronized (mGlobalLock) {
7349 if (mController == null) {
7350 return false;
7351 }
7352
7353 try {
7354 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7355 stackTrace)) {
7356 killCrashingAppCallback.run();
7357 return true;
7358 }
7359 } catch (RemoteException e) {
7360 mController = null;
7361 Watchdog.getInstance().setActivityController(null);
7362 }
7363 return false;
7364 }
7365 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007366
7367 @Override
7368 public void removeRecentTasksByPackageName(String packageName, int userId) {
7369 synchronized (mGlobalLock) {
7370 mRecentTasks.removeTasksByPackageName(packageName, userId);
7371 }
7372 }
7373
7374 @Override
7375 public void cleanupRecentTasksForUser(int userId) {
7376 synchronized (mGlobalLock) {
7377 mRecentTasks.cleanupLocked(userId);
7378 }
7379 }
7380
7381 @Override
7382 public void loadRecentTasksForUser(int userId) {
7383 synchronized (mGlobalLock) {
7384 mRecentTasks.loadUserRecentsLocked(userId);
7385 }
7386 }
7387
7388 @Override
7389 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7390 synchronized (mGlobalLock) {
7391 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7392 }
7393 }
7394
7395 @Override
7396 public void flushRecentTasks() {
7397 mRecentTasks.flush();
7398 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007399
7400 @Override
7401 public WindowProcessController getHomeProcess() {
7402 synchronized (mGlobalLock) {
7403 return mHomeProcess;
7404 }
7405 }
7406
7407 @Override
7408 public WindowProcessController getPreviousProcess() {
7409 synchronized (mGlobalLock) {
7410 return mPreviousProcess;
7411 }
7412 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007413
7414 @Override
7415 public void clearLockedTasks(String reason) {
7416 synchronized (mGlobalLock) {
7417 getLockTaskController().clearLockedTasks(reason);
7418 }
7419 }
7420
7421 @Override
7422 public void updateUserConfiguration() {
7423 synchronized (mGlobalLock) {
7424 final Configuration configuration = new Configuration(getGlobalConfiguration());
7425 final int currentUserId = mAmInternal.getCurrentUserId();
7426 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7427 configuration, currentUserId, Settings.System.canWrite(mContext));
7428 updateConfigurationLocked(configuration, null /* starting */,
7429 false /* initLocale */, false /* persistent */, currentUserId,
7430 false /* deferResume */);
7431 }
7432 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007433
7434 @Override
7435 public boolean canShowErrorDialogs() {
7436 synchronized (mGlobalLock) {
7437 return mShowDialogs && !mSleeping && !mShuttingDown
7438 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7439 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7440 mAmInternal.getCurrentUserId())
7441 && !(UserManager.isDeviceInDemoMode(mContext)
7442 && mAmInternal.getCurrentUser().isDemo());
7443 }
7444 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007445
7446 @Override
7447 public void setProfileApp(String profileApp) {
7448 synchronized (mGlobalLock) {
7449 mProfileApp = profileApp;
7450 }
7451 }
7452
7453 @Override
7454 public void setProfileProc(WindowProcessController wpc) {
7455 synchronized (mGlobalLock) {
7456 mProfileProc = wpc;
7457 }
7458 }
7459
7460 @Override
7461 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7462 synchronized (mGlobalLock) {
7463 mProfilerInfo = profilerInfo;
7464 }
7465 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007466
7467 @Override
7468 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7469 synchronized (mGlobalLock) {
7470 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7471 }
7472 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007473
7474 @Override
Zak Cohen84b43182020-03-09 14:36:01 -07007475 public ActivityManager.TaskSnapshot getTaskSnapshotBlocking(
7476 int taskId, boolean isLowResolution) {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08007477 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution,
Zak Cohen84b43182020-03-09 14:36:01 -07007478 true /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007479 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007480
7481 @Override
7482 public boolean isUidForeground(int uid) {
7483 synchronized (mGlobalLock) {
7484 return ActivityTaskManagerService.this.isUidForeground(uid);
7485 }
7486 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007487
7488 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007489 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007490 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007491 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007492 }
7493 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007494
7495 @Override
7496 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007497 // Translate package names into UIDs
7498 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007499 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007500 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7501 if (uid >= 0) {
7502 result.add(uid);
7503 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007504 }
7505 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007506 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007507 }
7508 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007509 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007510}