blob: f7278e70cedeccab1e62d0dc4ed12ac5397b45c8 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Jonathan Scott92335342019-12-17 14:46:26 +000031import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070035import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
36import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070037import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
38import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Evan Rosky73a7fe92019-11-18 18:28:01 -080039import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070040import 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;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800127import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700128import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.annotation.Nullable;
130import android.annotation.UserIdInt;
131import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700132import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700133import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.ActivityOptions;
135import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700136import android.app.ActivityThread;
137import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700138import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100139import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700140import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700141import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700142import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.IApplicationThread;
144import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400146import android.app.IRequestFinishCallback;
Wale Ogunwale57946582020-03-21 14:29:07 -0700147import android.window.ITaskOrganizerController;
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;
Wale Ogunwale568f9f412020-03-21 22:27:35 -0700233import android.window.IWindowOrganizerController;
Wale Ogunwale57946582020-03-21 14:29:07 -0700234import android.window.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700235import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700236
Evan Rosky4505b352018-09-06 11:20:40 -0700237import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700238import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.app.AssistUtils;
240import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700241import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700243import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700244import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
245import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700246import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700247import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700248import com.android.internal.policy.IKeyguardDismissCallback;
249import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700250import com.android.internal.util.ArrayUtils;
251import com.android.internal.util.FastPrintWriter;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800252import com.android.internal.util.FrameworkStatsLog;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800253import com.android.internal.util.function.pooled.PooledConsumer;
254import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700255import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700256import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700257import com.android.server.LocalServices;
258import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700259import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800260import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700261import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700262import com.android.server.am.ActivityManagerService;
Wale Ogunwale59507092018-10-29 09:00:30 -0700263import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
264import com.android.server.am.AppTimeTracker;
265import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700266import com.android.server.am.PendingIntentController;
267import com.android.server.am.PendingIntentRecord;
268import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700269import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700270import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700271import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800272import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700273import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700275
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700277import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700279import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700280import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700281import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700282import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700283import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800284import java.lang.annotation.ElementType;
285import java.lang.annotation.Retention;
286import java.lang.annotation.RetentionPolicy;
287import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700288import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700291import java.util.Arrays;
Jeff Sharkey8b0cff72020-03-09 15:49:01 -0600292import java.util.Collection;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700293import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400294import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700295import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700296import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700297import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700298import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000299import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700300import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301
302/**
303 * System service for managing activities and their containers (task, stacks, displays,... ).
304 *
305 * {@hide}
306 */
307public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700308 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800309 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000310 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700311 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
312 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
313 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
314 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700315 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700316
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700318 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700319 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700320 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100321 // How long we permit background activity starts after an activity in the process
322 // started or finished.
323 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700324
Wale Ogunwale98875612018-10-12 07:53:02 -0700325 /** Used to indicate that an app transition should be animated. */
326 static final boolean ANIMATE = true;
327
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700328 /** Hardware-reported OpenGLES version. */
329 final int GL_ES_VERSION;
330
Wale Ogunwale31913b52018-10-13 08:29:31 -0700331 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
332 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
333 public static final String DUMP_LASTANR_CMD = "lastanr" ;
334 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
335 public static final String DUMP_STARTER_CMD = "starter" ;
336 public static final String DUMP_CONTAINERS_CMD = "containers" ;
337 public static final String DUMP_RECENTS_CMD = "recents" ;
338 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
339
Wale Ogunwale64258362018-10-16 15:13:37 -0700340 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
341 public static final int RELAUNCH_REASON_NONE = 0;
342 /** This activity is being relaunched due to windowing mode change. */
343 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
344 /** This activity is being relaunched due to a free-resize operation. */
345 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
346
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700347 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700348
Wale Ogunwalef6733932018-06-27 05:14:34 -0700349 /**
350 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
351 * change at runtime. Use mContext for non-UI purposes.
352 */
353 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700354 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700355 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700356 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700357 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700358 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700359 private PackageManagerInternal mPmInternal;
Darryl L Johnsona0982222020-02-18 18:21:51 -0800360 /** The cached sys ui service component name from package manager. */
361 private ComponentName mSysUiServiceComponent;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800362 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800363 @VisibleForTesting
364 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700365 PowerManagerInternal mPowerManagerInternal;
366 private UsageStatsManagerInternal mUsageStatsInternal;
367
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700368 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700369 IntentFirewall mIntentFirewall;
370
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700371 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800372 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800373 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700374 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800375 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
376 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
377 *
378 * @see WindowManagerThreadPriorityBooster
379 */
380 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700381 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800382 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700383 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700384 private UserManagerService mUserManager;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800385 private AppOpsManager mAppOpsManager;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700386 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800387 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700388 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700389 /** All processes currently running that might have a window organized by name. */
390 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100391 /** All processes we currently have running mapped by pid and uid */
392 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700393 /** This is the process holding what we currently consider to be the "home" activity. */
394 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700395 /** The currently running heavy-weight process, if any. */
396 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700397 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700398 /**
399 * This is the process holding the activity the user last visited that is in a different process
400 * from the one they are currently in.
401 */
402 WindowProcessController mPreviousProcess;
403 /** The time at which the previous process was last visible. */
404 long mPreviousProcessVisibleTime;
405
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700406 /** List of intents that were used to start the most recent tasks. */
407 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700408 /** State of external calls telling us if the device is awake or asleep. */
409 private boolean mKeyguardShown = false;
410
411 // Wrapper around VoiceInteractionServiceManager
412 private AssistUtils mAssistUtils;
413
414 // VoiceInteraction session ID that changes for each new request except when
415 // being called for multi-window assist in a single session.
416 private int mViSessionId = 1000;
417
418 // How long to wait in getAssistContextExtras for the activity and foreground services
419 // to respond with the result.
420 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
421
422 // How long top wait when going through the modern assist (which doesn't need to block
423 // on getting this result before starting to launch its UI).
424 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
425
426 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
427 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
428
Alison Cichowlas3e340502018-08-07 17:15:01 -0400429 // Permission tokens are used to temporarily granted a trusted app the ability to call
430 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
431 // showing any appropriate error messages to the user.
432 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
433 10 * MINUTE_IN_MILLIS;
434
435 // How long before the service actually expires a token. This is slightly longer than
436 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
437 // expiration exception.
438 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
439 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
440
441 // How long the service will remember expired tokens, for the purpose of providing error
442 // messaging when a client uses an expired token.
443 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
444 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
445
446 // Activity tokens of system activities that are delegating their call to
447 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
448 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
449
450 // Permission tokens that have expired, but we remember for error reporting.
451 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
452
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700453 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
454
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700455 // Keeps track of the active voice interaction service component, notified from
456 // VoiceInteractionManagerService
457 ComponentName mActiveVoiceInteractionServiceComponent;
458
Michal Karpinskida34cd42019-04-02 19:46:52 +0100459 // A map userId and all its companion app uids
460 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000461
Wale Ogunwalee2172292018-10-25 10:11:10 -0700462 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700463 KeyguardController mKeyguardController;
464 private final ClientLifecycleManager mLifecycleManager;
465 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700466 /** The controller for all operations related to locktask. */
467 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700468 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700469
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700470 boolean mSuppressResizeConfigChanges;
471
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700472 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700473 new UpdateConfigurationResult();
474
475 static final class UpdateConfigurationResult {
476 // Configuration changes that were updated.
477 int changes;
478 // If the activity was relaunched to match the new configuration.
479 boolean activityRelaunched;
480
481 void reset() {
482 changes = 0;
483 activityRelaunched = false;
484 }
485 }
486
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700487 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700488 private int mConfigurationSeq;
489 // To cache the list of supported system locales
490 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700491
492 /**
493 * Temp object used when global and/or display override configuration is updated. It is also
494 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
495 * anyone...
496 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700497 private Configuration mTempConfig = new Configuration();
498
Wale Ogunwalef6733932018-06-27 05:14:34 -0700499 /** Temporary to avoid allocations. */
500 final StringBuilder mStringBuilder = new StringBuilder(256);
501
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700502 // Amount of time after a call to stopAppSwitches() during which we will
503 // prevent further untrusted switches from happening.
504 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
505
506 /**
507 * The time at which we will allow normal application switches again,
508 * after a call to {@link #stopAppSwitches()}.
509 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700510 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511 /**
512 * This is set to true after the first switch after mAppSwitchesAllowedTime
513 * is set; any switches after that will clear the time.
514 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700515 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700516
Ricky Wai906af482019-06-03 17:25:28 +0100517 /**
518 * Last stop app switches time, apps finished before this time cannot start background activity
519 * even if they are in grace period.
520 */
521 private long mLastStopAppSwitchesTime;
522
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700523 IActivityController mController = null;
524 boolean mControllerIsAMonkey = false;
525
Wale Ogunwale214f3482018-10-04 11:00:47 -0700526 final int mFactoryTest;
527
528 /** Used to control how we initialize the service. */
529 ComponentName mTopComponent;
530 String mTopAction = Intent.ACTION_MAIN;
531 String mTopData;
532
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800533 /** Profiling app information. */
534 String mProfileApp = null;
535 WindowProcessController mProfileProc = null;
536 ProfilerInfo mProfilerInfo = null;
537
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700538 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700539 * Dump of the activity state at the time of the last ANR. Cleared after
540 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
541 */
542 String mLastANRState;
543
544 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700545 * Used to retain an update lock when the foreground activity is in
546 * immersive mode.
547 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700548 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700549
550 /**
551 * Packages that are being allowed to perform unrestricted app switches. Mapping is
552 * User -> Type -> uid.
553 */
554 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
555
556 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700557 private int mThumbnailWidth;
558 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700559
560 /**
561 * Flag that indicates if multi-window is enabled.
562 *
563 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
564 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
565 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
566 * At least one of the forms of multi-window must be enabled in order for this flag to be
567 * initialized to 'true'.
568 *
569 * @see #mSupportsSplitScreenMultiWindow
570 * @see #mSupportsFreeformWindowManagement
571 * @see #mSupportsPictureInPicture
572 * @see #mSupportsMultiDisplay
573 */
574 boolean mSupportsMultiWindow;
575 boolean mSupportsSplitScreenMultiWindow;
576 boolean mSupportsFreeformWindowManagement;
577 boolean mSupportsPictureInPicture;
578 boolean mSupportsMultiDisplay;
579 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700580 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700581
582 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
583
584 // VR Vr2d Display Id.
585 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700586
Wale Ogunwalef6733932018-06-27 05:14:34 -0700587 /**
588 * Set while we are wanting to sleep, to prevent any
589 * activities from being started/resumed.
590 *
591 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
592 *
593 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
594 * while in the sleep state until there is a pending transition out of sleep, in which case
595 * mSleeping is set to false, and remains false while awake.
596 *
597 * Whether mSleeping can quickly toggled between true/false without the device actually
598 * display changing states is undefined.
599 */
600 private boolean mSleeping = false;
601
602 /**
603 * The process state used for processes that are running the top activities.
604 * This changes between TOP and TOP_SLEEPING to following mSleeping.
605 */
606 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
607
Riddle Hsua0022cd2019-09-09 21:12:41 +0800608 @Retention(RetentionPolicy.SOURCE)
609 @IntDef({
610 LAYOUT_REASON_CONFIG_CHANGED,
611 LAYOUT_REASON_VISIBILITY_CHANGED,
612 })
613 @interface LayoutReason {}
614 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
615 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
616
617 /** The reasons to perform surface placement. */
618 @LayoutReason
619 private int mLayoutReasons;
620
Wale Ogunwalef6733932018-06-27 05:14:34 -0700621 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
622 // automatically. Important for devices without direct input devices.
623 private boolean mShowDialogs = true;
624
625 /** Set if we are shutting down the system, similar to sleeping. */
626 boolean mShuttingDown = false;
627
628 /**
629 * We want to hold a wake lock while running a voice interaction session, since
630 * this may happen with the screen off and we need to keep the CPU running to
631 * be able to continue to interact with the user.
632 */
633 PowerManager.WakeLock mVoiceWakeLock;
634
635 /**
636 * Set while we are running a voice interaction. This overrides sleeping while it is active.
637 */
638 IVoiceInteractionSession mRunningVoice;
639
640 /**
641 * The last resumed activity. This is identical to the current resumed activity most
642 * of the time but could be different when we're pausing one activity before we resume
643 * another activity.
644 */
645 ActivityRecord mLastResumedActivity;
646
647 /**
648 * The activity that is currently being traced as the active resumed activity.
649 *
650 * @see #updateResumedAppTrace
651 */
652 private @Nullable ActivityRecord mTracedResumedActivity;
653
654 /** If non-null, we are tracking the time the user spends in the currently focused app. */
655 AppTimeTracker mCurAppTimeTracker;
656
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700657 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700658
Wale Ogunwale53783742018-09-16 10:21:51 -0700659 /**
660 * Packages that the user has asked to have run in screen size
661 * compatibility mode instead of filling the screen.
662 */
663 CompatModePackages mCompatModePackages;
664
Wale Ogunwalef6733932018-06-27 05:14:34 -0700665 private FontScaleSettingObserver mFontScaleSettingObserver;
666
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 Peycheva6861e912019-08-21 10:20:23 +02001277 try {
1278 getActivityStartController().obtainStarter(intent, "dream")
1279 .setActivityInfo(a)
1280 .setIsDream(true)
1281 .execute();
1282 return true;
1283 } finally {
1284 Binder.restoreCallingIdentity(origId);
1285 }
1286 }
1287
1288 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001289 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001290 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1291 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1292 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001293 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001294 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001295 enforceNotIsolatedCaller("startActivityAndWait");
1296 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1297 userId, "startActivityAndWait");
1298 // TODO: Switch to user app stacks here.
1299 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1300 .setCaller(caller)
1301 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001302 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001303 .setResolvedType(resolvedType)
1304 .setResultTo(resultTo)
1305 .setResultWho(resultWho)
1306 .setRequestCode(requestCode)
1307 .setStartFlags(startFlags)
1308 .setActivityOptions(bOptions)
1309 .setUserId(userId)
1310 .setProfilerInfo(profilerInfo)
1311 .setWaitResult(res)
1312 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001313 return res;
1314 }
1315
1316 @Override
1317 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001318 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1319 String resultWho, int requestCode, int startFlags, Configuration config,
1320 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001321 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001322 enforceNotIsolatedCaller("startActivityWithConfig");
1323 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1324 "startActivityWithConfig");
1325 // TODO: Switch to user app stacks here.
1326 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1327 .setCaller(caller)
1328 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001329 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001330 .setResolvedType(resolvedType)
1331 .setResultTo(resultTo)
1332 .setResultWho(resultWho)
1333 .setRequestCode(requestCode)
1334 .setStartFlags(startFlags)
1335 .setGlobalConfiguration(config)
1336 .setActivityOptions(bOptions)
1337 .setUserId(userId)
1338 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001339 }
1340
Robert Carr8a2f9132019-11-11 15:03:15 -08001341 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001342 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1343 int callingUid = Binder.getCallingUid();
1344 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1345 throw new SecurityException("Only the system process can request a permission token, "
1346 + "received request from uid: " + callingUid);
1347 }
1348 IBinder permissionToken = new Binder();
1349 synchronized (mGlobalLock) {
1350 mStartActivitySources.put(permissionToken, delegatorToken);
1351 }
1352
1353 Message expireMsg = PooledLambda.obtainMessage(
1354 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1355 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1356
1357 Message forgetMsg = PooledLambda.obtainMessage(
1358 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1359 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1360
1361 return permissionToken;
1362 }
1363
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001364 @Override
1365 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1366 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001367 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1368 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001369 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001370 // permission grants) as any app that may launch one of your own activities. So we only
1371 // allow this in two cases:
1372 // 1) The caller is an activity that is part of the core framework, and then only when it
1373 // is running as the system.
1374 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1375 // can only be requested by a system activity, which may then delegate this call to
1376 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377 final ActivityRecord sourceRecord;
1378 final int targetUid;
1379 final String targetPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001380 final String targetFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001381 final boolean isResolver;
1382 synchronized (mGlobalLock) {
1383 if (resultTo == null) {
1384 throw new SecurityException("Must be called from an activity");
1385 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001386 final IBinder sourceToken;
1387 if (permissionToken != null) {
1388 // To even attempt to use a permissionToken, an app must also have this signature
1389 // permission.
1390 mAmInternal.enforceCallingPermission(
1391 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1392 "startActivityAsCaller");
1393 // If called with a permissionToken, we want the sourceRecord from the delegator
1394 // activity that requested this token.
1395 sourceToken = mStartActivitySources.remove(permissionToken);
1396 if (sourceToken == null) {
1397 // Invalid permissionToken, check if it recently expired.
1398 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1399 throw new SecurityException("Called with expired permission token: "
1400 + permissionToken);
1401 } else {
1402 throw new SecurityException("Called with invalid permission token: "
1403 + permissionToken);
1404 }
1405 }
1406 } else {
1407 // This method was called directly by the source.
1408 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001409 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001410
Louis Chang149d5c82019-12-30 09:47:39 +08001411 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001412 if (sourceRecord == null) {
1413 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001414 }
1415 if (sourceRecord.app == null) {
1416 throw new SecurityException("Called without a process attached to activity");
1417 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001418
1419 // Whether called directly or from a delegate, the source activity must be from the
1420 // android package.
1421 if (!sourceRecord.info.packageName.equals("android")) {
1422 throw new SecurityException("Must be called from an activity that is "
1423 + "declared in the android package");
1424 }
1425
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001426 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001427 // This is still okay, as long as this activity is running under the
1428 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001429 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001430 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001431 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001432 + " must be system uid or original calling uid "
1433 + sourceRecord.launchedFromUid);
1434 }
1435 }
1436 if (ignoreTargetSecurity) {
1437 if (intent.getComponent() == null) {
1438 throw new SecurityException(
1439 "Component must be specified with ignoreTargetSecurity");
1440 }
1441 if (intent.getSelector() != null) {
1442 throw new SecurityException(
1443 "Selector not allowed with ignoreTargetSecurity");
1444 }
1445 }
1446 targetUid = sourceRecord.launchedFromUid;
1447 targetPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001448 targetFeatureId = sourceRecord.launchedFromFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001449 isResolver = sourceRecord.isResolverOrChildActivity();
1450 }
1451
1452 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001453 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001454 }
1455
1456 // TODO: Switch to user app stacks here.
1457 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001458 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 .setCallingUid(targetUid)
1460 .setCallingPackage(targetPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001461 .setCallingFeatureId(targetFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001462 .setResolvedType(resolvedType)
1463 .setResultTo(resultTo)
1464 .setResultWho(resultWho)
1465 .setRequestCode(requestCode)
1466 .setStartFlags(startFlags)
1467 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001468 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001469 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1470 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001471 // The target may well be in the background, which would normally prevent it
1472 // from starting an activity. Here we definitely want the start to succeed.
1473 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001474 .execute();
1475 } catch (SecurityException e) {
1476 // XXX need to figure out how to propagate to original app.
1477 // A SecurityException here is generally actually a fault of the original
1478 // calling activity (such as a fairly granting permissions), so propagate it
1479 // back to them.
1480 /*
1481 StringBuilder msg = new StringBuilder();
1482 msg.append("While launching");
1483 msg.append(intent.toString());
1484 msg.append(": ");
1485 msg.append(e.getMessage());
1486 */
1487 throw e;
1488 }
1489 }
1490
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001491 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1492 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001493 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001494 }
1495
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001496 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001497 public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1498 int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001499 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1500 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001501 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001502 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001503 if (session == null || interactor == null) {
1504 throw new NullPointerException("null session or interactor");
1505 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001506 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001507 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001508 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001509 .setCallingUid(callingUid)
1510 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001511 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001512 .setResolvedType(resolvedType)
1513 .setVoiceSession(session)
1514 .setVoiceInteractor(interactor)
1515 .setStartFlags(startFlags)
1516 .setProfilerInfo(profilerInfo)
1517 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001518 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001519 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001520 .execute();
1521 }
1522
1523 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001524 public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1525 int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1526 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001527 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001528 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1529 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001530
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001531 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001532 .setCallingUid(callingUid)
1533 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001534 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001535 .setResolvedType(resolvedType)
1536 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001537 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001538 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001539 .execute();
1540 }
1541
Riddle Hsu609a8e22019-06-27 16:46:29 -06001542 /**
1543 * Start the recents activity to perform the recents animation.
1544 *
1545 * @param intent The intent to start the recents activity.
1546 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1547 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001548 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001549 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1550 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001551 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001552 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001553 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001554 final long origId = Binder.clearCallingIdentity();
1555 try {
1556 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001557 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
Philip P. Moltmannee295092020-02-10 08:46:26 -08001558 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001559 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001560 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001561
1562 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001563 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001564 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001565 recentsFeatureId, recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001566 if (recentsAnimationRunner == null) {
1567 anim.preloadRecentsActivity();
1568 } else {
1569 anim.startRecentsActivity(recentsAnimationRunner);
1570 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001571 }
1572 } finally {
1573 Binder.restoreCallingIdentity(origId);
1574 }
1575 }
1576
1577 @Override
1578 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001579 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001580 "startActivityFromRecents()");
1581
1582 final int callingPid = Binder.getCallingPid();
1583 final int callingUid = Binder.getCallingUid();
1584 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1585 final long origId = Binder.clearCallingIdentity();
1586 try {
1587 synchronized (mGlobalLock) {
1588 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1589 safeOptions);
1590 }
1591 } finally {
1592 Binder.restoreCallingIdentity(origId);
1593 }
1594 }
1595
1596 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001597 * Public API to check if the client is allowed to start an activity on specified display.
1598 *
1599 * If the target display is private or virtual, some restrictions will apply.
1600 *
1601 * @param displayId Target display id.
1602 * @param intent Intent used to launch the activity.
1603 * @param resolvedType The MIME type of the intent.
1604 * @param userId The id of the user for whom the call is made.
1605 * @return {@code true} if a call to start an activity on the target display should succeed and
1606 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1607 */
1608 @Override
1609 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1610 String resolvedType, int userId) {
1611 final int callingUid = Binder.getCallingUid();
1612 final int callingPid = Binder.getCallingPid();
1613 final long origId = Binder.clearCallingIdentity();
1614
1615 try {
1616 // Collect information about the target of the Intent.
1617 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1618 0 /* startFlags */, null /* profilerInfo */, userId,
1619 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1620 UserHandle.USER_NULL));
1621 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1622
1623 synchronized (mGlobalLock) {
1624 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1625 aInfo);
1626 }
1627 } finally {
1628 Binder.restoreCallingIdentity(origId);
1629 }
1630 }
1631
1632 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001633 * This is the internal entry point for handling Activity.finish().
1634 *
1635 * @param token The Binder token referencing the Activity we want to finish.
1636 * @param resultCode Result code, if any, from this Activity.
1637 * @param resultData Result data (Intent), if any, from this Activity.
1638 * @param finishTask Whether to finish the task associated with this Activity.
1639 *
1640 * @return Returns true if the activity successfully finished, or false if it is still running.
1641 */
1642 @Override
1643 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1644 int finishTask) {
1645 // Refuse possible leaked file descriptors
1646 if (resultData != null && resultData.hasFileDescriptors()) {
1647 throw new IllegalArgumentException("File descriptors passed in Intent");
1648 }
1649
1650 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001651 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001652 if (r == null) {
1653 return true;
1654 }
1655 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001656 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001657 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001658 if (rootR == null) {
1659 Slog.w(TAG, "Finishing task with all activities already finished");
1660 }
1661 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1662 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001663 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001664 return false;
1665 }
1666
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001667 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1668 // We should consolidate.
1669 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001670 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001671 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001672 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001673 if (next != null) {
1674 // ask watcher if this is allowed
1675 boolean resumeOK = true;
1676 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001677 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001678 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001679 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001680 Watchdog.getInstance().setActivityController(null);
1681 }
1682
1683 if (!resumeOK) {
1684 Slog.i(TAG, "Not finishing activity because controller resumed");
1685 return false;
1686 }
1687 }
1688 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001689
1690 // note down that the process has finished an activity and is in background activity
1691 // starts grace period
1692 if (r.app != null) {
1693 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1694 }
1695
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001696 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001697 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001698 try {
1699 boolean res;
1700 final boolean finishWithRootActivity =
1701 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1702 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1703 || (finishWithRootActivity && r == rootR)) {
1704 // If requested, remove the task that is associated to this activity only if it
1705 // was the root activity in the task. The result code and data is ignored
1706 // because we don't support returning them across task boundaries. Also, to
1707 // keep backwards compatibility we remove the task from recents when finishing
1708 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001709 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001710 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001711 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001712 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001713 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001714 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001715 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001716 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001717 if (!res) {
1718 Slog.i(TAG, "Failed to finish by app-request");
1719 }
1720 }
1721 return res;
1722 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001723 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001724 Binder.restoreCallingIdentity(origId);
1725 }
1726 }
1727 }
1728
1729 @Override
1730 public boolean finishActivityAffinity(IBinder token) {
1731 synchronized (mGlobalLock) {
1732 final long origId = Binder.clearCallingIdentity();
1733 try {
1734 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1735 if (r == null) {
1736 return false;
1737 }
1738
1739 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1740 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001741 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001742 return false;
1743 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001744
1745 final PooledFunction p = PooledLambda.obtainFunction(
1746 ActivityRecord::finishIfSameAffinity, r,
1747 PooledLambda.__(ActivityRecord.class));
1748 r.getTask().forAllActivities(
1749 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1750 p.recycle();
1751
Andrii Kuliande93eff2019-07-12 12:21:27 -07001752 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001753 } finally {
1754 Binder.restoreCallingIdentity(origId);
1755 }
1756 }
1757 }
1758
1759 @Override
1760 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1761 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001762 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001763 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001764 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001765 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1766 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001767 return;
1768 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001769 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1770 false /* processPausingActivities */, config);
1771 if (stopProfiling && r.hasProcess()) {
1772 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001773 }
1774 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001775 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001776 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001777 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001778 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001779 }
1780
1781 @Override
1782 public final void activityResumed(IBinder token) {
1783 final long origId = Binder.clearCallingIdentity();
1784 synchronized (mGlobalLock) {
1785 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001786 }
1787 Binder.restoreCallingIdentity(origId);
1788 }
1789
1790 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001791 public final void activityTopResumedStateLost() {
1792 final long origId = Binder.clearCallingIdentity();
1793 synchronized (mGlobalLock) {
1794 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1795 }
1796 Binder.restoreCallingIdentity(origId);
1797 }
1798
1799 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 public final void activityPaused(IBinder token) {
1801 final long origId = Binder.clearCallingIdentity();
1802 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001803 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001804 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1805 if (r != null) {
1806 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001807 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001808 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001809 }
1810 Binder.restoreCallingIdentity(origId);
1811 }
1812
1813 @Override
1814 public final void activityStopped(IBinder token, Bundle icicle,
1815 PersistableBundle persistentState, CharSequence description) {
1816 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1817
1818 // Refuse possible leaked file descriptors
1819 if (icicle != null && icicle.hasFileDescriptors()) {
1820 throw new IllegalArgumentException("File descriptors passed in Bundle");
1821 }
1822
1823 final long origId = Binder.clearCallingIdentity();
1824
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001825 String restartingName = null;
1826 int restartingUid = 0;
1827 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001828 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001829 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001830 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001831 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001832 if (r.attachedToProcess()
1833 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1834 // The activity was requested to restart from
1835 // {@link #restartActivityProcessIfVisible}.
1836 restartingName = r.app.mName;
1837 restartingUid = r.app.mUid;
1838 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001839 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001840 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001841 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001842 }
1843
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001844 if (restartingName != null) {
1845 // In order to let the foreground activity can be restarted with its saved state from
1846 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1847 // until the activity reports stopped with the state. And the activity record will be
1848 // kept because the record state is restarting, then the activity will be restarted
1849 // immediately if it is still the top one.
1850 mStackSupervisor.removeRestartTimeouts(r);
1851 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1852 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001853 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001854
1855 Binder.restoreCallingIdentity(origId);
1856 }
1857
1858 @Override
1859 public final void activityDestroyed(IBinder token) {
1860 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1861 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001862 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001863 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001864 try {
1865 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1866 if (activity != null) {
1867 activity.destroyed("activityDestroyed");
1868 }
1869 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001870 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001871 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001872 }
1873 }
1874 }
1875
1876 @Override
1877 public final void activityRelaunched(IBinder token) {
1878 final long origId = Binder.clearCallingIdentity();
1879 synchronized (mGlobalLock) {
1880 mStackSupervisor.activityRelaunchedLocked(token);
1881 }
1882 Binder.restoreCallingIdentity(origId);
1883 }
1884
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001885 @Override
1886 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1887 synchronized (mGlobalLock) {
1888 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1889 if (r == null) {
1890 return;
1891 }
1892 final long origId = Binder.clearCallingIdentity();
1893 try {
1894 r.setRequestedOrientation(requestedOrientation);
1895 } finally {
1896 Binder.restoreCallingIdentity(origId);
1897 }
1898 }
1899 }
1900
1901 @Override
1902 public int getRequestedOrientation(IBinder token) {
1903 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001904 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1905 return (r != null)
1906 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001907 }
1908 }
1909
1910 @Override
1911 public void setImmersive(IBinder token, boolean immersive) {
1912 synchronized (mGlobalLock) {
1913 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1914 if (r == null) {
1915 throw new IllegalArgumentException();
1916 }
1917 r.immersive = immersive;
1918
1919 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001920 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001921 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001922 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001923 }
1924 }
1925 }
1926
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001927 void applyUpdateLockStateLocked(ActivityRecord r) {
1928 // Modifications to the UpdateLock state are done on our handler, outside
1929 // the activity manager's locks. The new state is determined based on the
1930 // state *now* of the relevant activity record. The object is passed to
1931 // the handler solely for logging detail, not to be consulted/modified.
1932 final boolean nextState = r != null && r.immersive;
1933 mH.post(() -> {
1934 if (mUpdateLock.isHeld() != nextState) {
1935 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1936 "Applying new update lock state '" + nextState + "' for " + r);
1937 if (nextState) {
1938 mUpdateLock.acquire();
1939 } else {
1940 mUpdateLock.release();
1941 }
1942 }
1943 });
1944 }
1945
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001946 @Override
1947 public boolean isImmersive(IBinder token) {
1948 synchronized (mGlobalLock) {
1949 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1950 if (r == null) {
1951 throw new IllegalArgumentException();
1952 }
1953 return r.immersive;
1954 }
1955 }
1956
1957 @Override
1958 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001959 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001960 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001961 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
1962 if (topFocusedStack == null) {
1963 return false;
1964 }
1965
1966 final ActivityRecord r = topFocusedStack.topRunningActivity();
1967 return r != null && r.immersive;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001968 }
1969 }
1970
1971 @Override
1972 public void overridePendingTransition(IBinder token, String packageName,
1973 int enterAnim, int exitAnim) {
1974 synchronized (mGlobalLock) {
1975 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1976 if (self == null) {
1977 return;
1978 }
1979
1980 final long origId = Binder.clearCallingIdentity();
1981
1982 if (self.isState(
1983 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001984 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001985 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001986 }
1987
1988 Binder.restoreCallingIdentity(origId);
1989 }
1990 }
1991
1992 @Override
1993 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001994 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001995 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001996 final ActivityStack stack = getTopDisplayFocusedStack();
1997 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001998 if (r == null) {
1999 return ActivityManager.COMPAT_MODE_UNKNOWN;
2000 }
Wale Ogunwale53783742018-09-16 10:21:51 -07002001 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002002 }
2003 }
2004
2005 @Override
2006 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002007 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002008 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002009 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002010 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002011 final ActivityStack stack = getTopDisplayFocusedStack();
2012 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002013 if (r == null) {
2014 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
2015 return;
2016 }
2017 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07002018 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002019 }
2020 }
2021
2022 @Override
2023 public int getLaunchedFromUid(IBinder activityToken) {
2024 ActivityRecord srec;
2025 synchronized (mGlobalLock) {
2026 srec = ActivityRecord.forTokenLocked(activityToken);
2027 }
2028 if (srec == null) {
2029 return -1;
2030 }
2031 return srec.launchedFromUid;
2032 }
2033
2034 @Override
2035 public String getLaunchedFromPackage(IBinder activityToken) {
2036 ActivityRecord srec;
2037 synchronized (mGlobalLock) {
2038 srec = ActivityRecord.forTokenLocked(activityToken);
2039 }
2040 if (srec == null) {
2041 return null;
2042 }
2043 return srec.launchedFromPackage;
2044 }
2045
2046 @Override
2047 public boolean convertFromTranslucent(IBinder token) {
2048 final long origId = Binder.clearCallingIdentity();
2049 try {
2050 synchronized (mGlobalLock) {
2051 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2052 if (r == null) {
2053 return false;
2054 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002055 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002056 }
2057 } finally {
2058 Binder.restoreCallingIdentity(origId);
2059 }
2060 }
2061
2062 @Override
2063 public boolean convertToTranslucent(IBinder token, Bundle options) {
2064 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2065 final long origId = Binder.clearCallingIdentity();
2066 try {
2067 synchronized (mGlobalLock) {
2068 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2069 if (r == null) {
2070 return false;
2071 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002072 final ActivityRecord under = r.getTask().getActivityBelow(r);
2073 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002074 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2075 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002076 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002077 }
2078 } finally {
2079 Binder.restoreCallingIdentity(origId);
2080 }
2081 }
2082
2083 @Override
2084 public void notifyActivityDrawn(IBinder token) {
2085 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2086 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002087 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002088 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002089 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002090 }
2091 }
2092 }
2093
2094 @Override
2095 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2096 synchronized (mGlobalLock) {
2097 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2098 if (r == null) {
2099 return;
2100 }
2101 r.reportFullyDrawnLocked(restoredFromBundle);
2102 }
2103 }
2104
2105 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002106 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002107 synchronized (mGlobalLock) {
2108 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002109 if (stack != null) {
2110 final int displayId = stack.getDisplayId();
2111 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002112 }
2113 return DEFAULT_DISPLAY;
2114 }
2115 }
2116
2117 @Override
2118 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002119 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002120 long ident = Binder.clearCallingIdentity();
2121 try {
2122 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002123 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002124 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002125 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002126 }
2127 return null;
2128 }
2129 } finally {
2130 Binder.restoreCallingIdentity(ident);
2131 }
2132 }
2133
2134 @Override
2135 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002136 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002137 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2138 final long callingId = Binder.clearCallingIdentity();
2139 try {
2140 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002141 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002142 if (stack == null) {
2143 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2144 return;
2145 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002146 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002147 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002148 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002149 }
2150 }
2151 } finally {
2152 Binder.restoreCallingIdentity(callingId);
2153 }
2154 }
2155
2156 @Override
2157 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002158 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002159 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2160 final long callingId = Binder.clearCallingIdentity();
2161 try {
2162 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002163 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002164 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002165 if (task == null) {
2166 return;
2167 }
2168 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002169 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002170 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002171 }
2172 }
2173 } finally {
2174 Binder.restoreCallingIdentity(callingId);
2175 }
2176 }
2177
2178 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002179 public void restartActivityProcessIfVisible(IBinder activityToken) {
2180 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2181 final long callingId = Binder.clearCallingIdentity();
2182 try {
2183 synchronized (mGlobalLock) {
2184 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2185 if (r == null) {
2186 return;
2187 }
2188 r.restartProcessIfVisible();
2189 }
2190 } finally {
2191 Binder.restoreCallingIdentity(callingId);
2192 }
2193 }
2194
2195 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002196 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002197 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002198 synchronized (mGlobalLock) {
2199 final long ident = Binder.clearCallingIdentity();
2200 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002201 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002202 "remove-task");
2203 } finally {
2204 Binder.restoreCallingIdentity(ident);
2205 }
2206 }
2207 }
2208
2209 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002210 public void removeAllVisibleRecentTasks() {
2211 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2212 synchronized (mGlobalLock) {
2213 final long ident = Binder.clearCallingIdentity();
2214 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002215 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002216 } finally {
2217 Binder.restoreCallingIdentity(ident);
2218 }
2219 }
2220 }
2221
2222 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002223 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2224 synchronized (mGlobalLock) {
2225 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2226 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002227 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002228 }
2229 }
2230 return false;
2231 }
2232
2233 @Override
2234 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2235 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002236
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002237 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002238 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2239 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002240 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002241 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002242 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002243 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002244 }
2245 }
2246
2247 /**
2248 * Attempts to move a task backwards in z-order (the order of activities within the task is
2249 * unchanged).
2250 *
2251 * There are several possible results of this call:
2252 * - if the task is locked, then we will show the lock toast
2253 * - if there is a task behind the provided task, then that task is made visible and resumed as
2254 * this task is moved to the back
2255 * - otherwise, if there are no other tasks in the stack:
2256 * - if this task is in the pinned stack, then we remove the stack completely, which will
2257 * have the effect of moving the task to the top or bottom of the fullscreen stack
2258 * (depending on whether it is visible)
2259 * - otherwise, we simply return home and hide this task
2260 *
2261 * @param token A reference to the activity we wish to move
2262 * @param nonRoot If false then this only works if the activity is the root
2263 * of a task; if true it will work for any activity in a task.
2264 * @return Returns true if the move completed, false if not.
2265 */
2266 @Override
2267 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002268 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002269 synchronized (mGlobalLock) {
2270 final long origId = Binder.clearCallingIdentity();
2271 try {
2272 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002273 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002274 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002275 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002276 }
2277 } finally {
2278 Binder.restoreCallingIdentity(origId);
2279 }
2280 }
2281 return false;
2282 }
2283
2284 @Override
2285 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002286 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002287 long ident = Binder.clearCallingIdentity();
2288 Rect rect = new Rect();
2289 try {
2290 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002291 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002292 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2293 if (task == null) {
2294 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2295 return rect;
2296 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002297 if (task.getParent() != null) {
2298 rect.set(task.getBounds());
2299 } else if (task.mLastNonFullscreenBounds != null) {
2300 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002301 }
2302 }
2303 } finally {
2304 Binder.restoreCallingIdentity(ident);
2305 }
2306 return rect;
2307 }
2308
2309 @Override
2310 public ActivityManager.TaskDescription getTaskDescription(int id) {
2311 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002312 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002313 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002314 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002315 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2316 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002317 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002318 }
2319 }
2320 return null;
2321 }
2322
2323 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002324 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002325 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08002326 return setTaskWindowingModeSplitScreenPrimary(taskId, toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002327 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002328 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002329 synchronized (mGlobalLock) {
2330 final long ident = Binder.clearCallingIdentity();
2331 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002332 if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2333 return setTaskWindowingModeSplitScreen(taskId, windowingMode, toTop);
2334 }
Louis Chang149d5c82019-12-30 09:47:39 +08002335 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002336 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002337 if (task == null) {
2338 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002339 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002340 }
2341
2342 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2343 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2344
2345 if (!task.isActivityTypeStandardOrUndefined()) {
2346 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2347 + " non-standard task " + taskId + " to windowing mode="
2348 + windowingMode);
2349 }
2350
2351 final ActivityStack stack = task.getStack();
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002352 // Convert some windowing-mode changes into root-task reparents for split-screen.
2353 if (stack.getTile() != null) {
2354 stack.getDisplay().onSplitScreenModeDismissed();
2355 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002356 if (toTop) {
2357 stack.moveToFront("setTaskWindowingMode", task);
2358 }
2359 stack.setWindowingMode(windowingMode);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002360 stack.getDisplay().ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2361 true /* notifyClients */);
Winson Chung7ccc6812020-01-23 16:15:10 -08002362 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002363 } finally {
2364 Binder.restoreCallingIdentity(ident);
2365 }
2366 }
2367 }
2368
2369 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002370 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002371 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002372 ActivityRecord r = getCallingRecordLocked(token);
2373 return r != null ? r.info.packageName : null;
2374 }
2375 }
2376
2377 @Override
2378 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002379 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002380 ActivityRecord r = getCallingRecordLocked(token);
2381 return r != null ? r.intent.getComponent() : null;
2382 }
2383 }
2384
2385 private ActivityRecord getCallingRecordLocked(IBinder token) {
2386 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2387 if (r == null) {
2388 return null;
2389 }
2390 return r.resultTo;
2391 }
2392
2393 @Override
2394 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002395 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002396
2397 synchronized (mGlobalLock) {
2398 final long origId = Binder.clearCallingIdentity();
2399 try {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002400 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
2401 if (topFocusedStack != null) {
2402 topFocusedStack.unhandledBackLocked();
2403 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002404 } finally {
2405 Binder.restoreCallingIdentity(origId);
2406 }
2407 }
2408 }
2409
Mark Renouf446251d2019-04-26 10:22:41 -04002410 @Override
2411 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2412 synchronized (mGlobalLock) {
2413 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2414 if (r == null) {
2415 return;
2416 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002417 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002418 if (stack != null && stack.isSingleTaskInstance()) {
2419 // Single-task stacks are used for activities which are presented in floating
2420 // windows above full screen activities. Instead of directly finishing the
2421 // task, a task change listener is used to notify SystemUI so the action can be
2422 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002423 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002424 mTaskChangeNotificationController
2425 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2426 } else {
2427 try {
2428 callback.requestFinish();
2429 } catch (RemoteException e) {
2430 Slog.e(TAG, "Failed to invoke request finish callback", e);
2431 }
2432 }
2433 }
2434 }
2435
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002436 /**
2437 * TODO: Add mController hook
2438 */
2439 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002440 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2441 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002442 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002443
2444 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2445 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002446 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2447 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002448 }
2449 }
2450
Ricky Waiaca8a772019-04-04 16:01:06 +01002451 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2452 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002453 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002454 final int callingPid = Binder.getCallingPid();
2455 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002456 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002457 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002458 SafeActivityOptions.abort(options);
2459 return;
2460 }
2461 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002462 WindowProcessController callerApp = null;
2463 if (appThread != null) {
2464 callerApp = getProcessController(appThread);
2465 }
2466 final ActivityStarter starter = getActivityStartController().obtainStarter(
2467 null /* intent */, "moveTaskToFront");
2468 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
Galia Peycheva6861e912019-08-21 10:20:23 +02002469 -1, callerApp, null, false, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002470 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002471 return;
2472 }
2473 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002474 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002475 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002476 if (task == null) {
2477 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002478 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002479 return;
2480 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002481 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002482 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002483 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002484 return;
2485 }
2486 ActivityOptions realOptions = options != null
2487 ? options.getOptions(mStackSupervisor)
2488 : null;
2489 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2490 false /* forceNonResizable */);
2491
Wale Ogunwale21e06482019-11-18 05:14:15 -08002492 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002493 if (topActivity != null) {
2494
2495 // We are reshowing a task, use a starting window to hide the initial draw delay
2496 // so the transition can start earlier.
2497 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2498 true /* taskSwitch */, fromRecents);
2499 }
2500 } finally {
2501 Binder.restoreCallingIdentity(origId);
2502 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002503 }
2504
Ricky Waiaca8a772019-04-04 16:01:06 +01002505 /**
2506 * Return true if callingUid is system, or packageName belongs to that callingUid.
2507 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002508 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002509 try {
2510 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2511 if (packageName == null) {
2512 return false;
2513 }
2514 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2515 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2516 UserHandle.getUserId(callingUid));
2517 return UserHandle.isSameApp(callingUid, uid);
2518 }
2519 } catch (RemoteException e) {
2520 // Should not happen
2521 }
2522 return true;
2523 }
2524
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002525 /**
2526 * Checks that the provided package name matches the current calling UID, throws a security
2527 * exception if it doesn't.
2528 */
2529 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2530 final int callingUid = Binder.getCallingUid();
2531 if (isSameApp(callingUid, packageName)) {
2532 return;
2533 }
2534 final String msg = "Permission Denial: package=" + packageName
2535 + " does not belong to uid=" + callingUid;
2536 Slog.w(TAG, msg);
2537 throw new SecurityException(msg);
2538 }
2539
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002540 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2541 int callingPid, int callingUid, String name) {
2542 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2543 return true;
2544 }
2545
2546 if (getRecentTasks().isCallerRecents(sourceUid)) {
2547 return true;
2548 }
2549
2550 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2551 if (perm == PackageManager.PERMISSION_GRANTED) {
2552 return true;
2553 }
2554 if (checkAllowAppSwitchUid(sourceUid)) {
2555 return true;
2556 }
2557
2558 // If the actual IPC caller is different from the logical source, then
2559 // also see if they are allowed to control app switches.
2560 if (callingUid != -1 && callingUid != sourceUid) {
2561 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2562 if (perm == PackageManager.PERMISSION_GRANTED) {
2563 return true;
2564 }
2565 if (checkAllowAppSwitchUid(callingUid)) {
2566 return true;
2567 }
2568 }
2569
2570 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2571 return false;
2572 }
2573
2574 private boolean checkAllowAppSwitchUid(int uid) {
2575 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2576 if (types != null) {
2577 for (int i = types.size() - 1; i >= 0; i--) {
2578 if (types.valueAt(i).intValue() == uid) {
2579 return true;
2580 }
2581 }
2582 }
2583 return false;
2584 }
2585
2586 @Override
2587 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2588 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2589 "setActivityController()");
2590 synchronized (mGlobalLock) {
2591 mController = controller;
2592 mControllerIsAMonkey = imAMonkey;
2593 Watchdog.getInstance().setActivityController(controller);
2594 }
2595 }
2596
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002597 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002598 synchronized (mGlobalLock) {
2599 return mController != null && mControllerIsAMonkey;
2600 }
2601 }
2602
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002603 @Override
2604 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2605 synchronized (mGlobalLock) {
2606 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2607 }
2608 }
2609
2610 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002611 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2612 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2613 }
2614
2615 @Override
2616 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2617 @WindowConfiguration.ActivityType int ignoreActivityType,
2618 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2619 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002620 final int callingPid = Binder.getCallingPid();
2621 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002622 final int[] profileIds = getUserManager().getProfileIds(
2623 UserHandle.getUserId(callingUid), true);
2624 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2625 for (int i = 0; i < profileIds.length; i++) {
2626 callingProfileIds.add(profileIds[i]);
2627 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002628 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2629
2630 synchronized (mGlobalLock) {
2631 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2632
Nicholas Sauer0259e532019-08-30 08:24:55 -07002633 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002634 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002635 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002636 }
2637
2638 return list;
2639 }
2640
2641 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002642 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2643 synchronized (mGlobalLock) {
2644 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002645 try {
2646 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2647 if (r == null) return;
2648
2649 final PooledConsumer c = PooledLambda.obtainConsumer(
2650 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2651 r, resultWho, requestCode);
2652 // TODO: This should probably only loop over the task since you need to be in the
2653 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002654 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002655 c.recycle();
2656
2657 updateOomAdj();
2658 } finally {
2659 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002660 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002661 }
2662 }
2663
2664 @Override
2665 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002666 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002667 ActivityStack stack = ActivityRecord.getStackLocked(token);
2668 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002669 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002670 }
2671 return false;
2672 }
2673 }
2674
2675 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002676 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002677 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002678 synchronized (mGlobalLock) {
2679 final long ident = Binder.clearCallingIdentity();
2680 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002681 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002682 if (task == null) {
2683 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2684 return;
2685 }
2686
2687 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2688 + " to stackId=" + stackId + " toTop=" + toTop);
2689
Louis Chang149d5c82019-12-30 09:47:39 +08002690 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002691 if (stack == null) {
2692 throw new IllegalStateException(
2693 "moveTaskToStack: No stack for stackId=" + stackId);
2694 }
2695 if (!stack.isActivityTypeStandardOrUndefined()) {
2696 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2697 + taskId + " to stack " + stackId);
2698 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002699 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2700 "moveTaskToStack");
2701 } finally {
2702 Binder.restoreCallingIdentity(ident);
2703 }
2704 }
2705 }
2706
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002707 /**
2708 * Moves the specified task to the primary-split-screen stack.
2709 *
2710 * @param taskId Id of task to move.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002711 * @param toTop If the task and stack should be moved to the top.
Winson Chung7ccc6812020-01-23 16:15:10 -08002712 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002713 */
2714 @Override
Evan Rosky73a7fe92019-11-18 18:28:01 -08002715 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002716 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002717 "setTaskWindowingModeSplitScreenPrimary()");
2718 synchronized (mGlobalLock) {
2719 final long ident = Binder.clearCallingIdentity();
2720 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002721 return setTaskWindowingModeSplitScreen(taskId, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY,
2722 toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002723 } finally {
2724 Binder.restoreCallingIdentity(ident);
2725 }
2726 }
2727 }
2728
2729 /**
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002730 * Moves the specified task into a split-screen tile.
2731 */
2732 private boolean setTaskWindowingModeSplitScreen(int taskId, int windowingMode, boolean toTop) {
2733 if (!WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2734 throw new IllegalArgumentException("Calling setTaskWindowingModeSplitScreen with non"
2735 + "split-screen mode: " + windowingMode);
2736 }
2737 if (isInLockTaskMode()) {
2738 Slog.w(TAG, "setTaskWindowingModeSplitScreen: Is in lock task mode="
2739 + getLockTaskModeState());
2740 return false;
2741 }
2742
2743 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2744 MATCH_TASK_IN_STACKS_ONLY);
2745 if (task == null) {
2746 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2747 return false;
2748 }
2749 if (!task.isActivityTypeStandardOrUndefined()) {
2750 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2751 + " non-standard task " + taskId + " to split-screen windowing mode");
2752 }
Wale Ogunwale0d465192020-01-23 19:14:44 -08002753 if (!task.supportsSplitScreenWindowingMode()) {
2754 return false;
2755 }
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002756
2757 final int prevMode = task.getWindowingMode();
Wale Ogunwale0d465192020-01-23 19:14:44 -08002758 moveTaskToSplitScreenPrimaryTile(task, toTop);
2759 return prevMode != task.getWindowingMode();
2760 }
2761
2762 void moveTaskToSplitScreenPrimaryTile(Task task, boolean toTop) {
2763 ActivityStack stack = task.getStack();
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002764 TaskTile tile = null;
2765 for (int i = stack.getDisplay().getStackCount() - 1; i >= 0; --i) {
2766 tile = stack.getDisplay().getStackAt(i).asTile();
2767 if (tile != null && tile.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2768 break;
2769 }
2770 }
2771 if (tile == null) {
2772 throw new IllegalStateException("Can't enter split without associated tile");
2773 }
2774 WindowContainerTransaction wct = new WindowContainerTransaction();
2775 wct.reparent(stack.mRemoteToken, tile.mRemoteToken, toTop);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07002776 mWindowOrganizerController.applyTransaction(wct);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002777 }
2778
2779 /**
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002780 * Removes stacks in the input windowing modes from the system if they are of activity type
2781 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2782 */
2783 @Override
2784 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002785 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002786 "removeStacksInWindowingModes()");
2787
2788 synchronized (mGlobalLock) {
2789 final long ident = Binder.clearCallingIdentity();
2790 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002791 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002792 } finally {
2793 Binder.restoreCallingIdentity(ident);
2794 }
2795 }
2796 }
2797
2798 @Override
2799 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002800 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002801 "removeStacksWithActivityTypes()");
2802
2803 synchronized (mGlobalLock) {
2804 final long ident = Binder.clearCallingIdentity();
2805 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002806 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002807 } finally {
2808 Binder.restoreCallingIdentity(ident);
2809 }
2810 }
2811 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002812
2813 @Override
2814 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2815 int userId) {
2816 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002817 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2818 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002819 callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002820 synchronized (mGlobalLock) {
Winson Chung66b08f02020-03-03 14:32:35 -08002821 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, userId, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002822 }
2823 }
2824
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002825 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 @Override
2827 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002828 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002829 long ident = Binder.clearCallingIdentity();
2830 try {
2831 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002832 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002833 }
2834 } finally {
2835 Binder.restoreCallingIdentity(ident);
2836 }
2837 }
2838
2839 @Override
2840 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002841 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002842 long ident = Binder.clearCallingIdentity();
2843 try {
2844 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002845 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002846 }
2847 } finally {
2848 Binder.restoreCallingIdentity(ident);
2849 }
2850 }
2851
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002852 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002853 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002854 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2855 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2856 long ident = Binder.clearCallingIdentity();
2857 try {
2858 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002859 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002860 }
2861 } finally {
2862 Binder.restoreCallingIdentity(ident);
2863 }
2864 }
2865
2866 @Override
2867 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2868 int displayId) {
2869 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2870 long ident = Binder.clearCallingIdentity();
2871 try {
2872 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002873 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002874 }
2875 } finally {
2876 Binder.restoreCallingIdentity(ident);
2877 }
2878 }
2879
2880 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002881 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002882 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883 final long callingUid = Binder.getCallingUid();
2884 final long origId = Binder.clearCallingIdentity();
2885 try {
2886 synchronized (mGlobalLock) {
2887 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002888 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002889 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2890 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2891 }
2892 } finally {
2893 Binder.restoreCallingIdentity(origId);
2894 }
2895 }
2896
2897 @Override
2898 public void startLockTaskModeByToken(IBinder token) {
2899 synchronized (mGlobalLock) {
2900 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2901 if (r == null) {
2902 return;
2903 }
Louis Changcdec0802019-11-11 11:45:07 +08002904 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002905 }
2906 }
2907
2908 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002909 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002910 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002911 // This makes inner call to look as if it was initiated by system.
2912 long ident = Binder.clearCallingIdentity();
2913 try {
2914 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002915 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002916 MATCH_TASK_IN_STACKS_ONLY);
2917 if (task == null) {
2918 return;
2919 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002920
2921 // When starting lock task mode the stack must be in front and focused
2922 task.getStack().moveToFront("startSystemLockTaskMode");
2923 startLockTaskModeLocked(task, true /* isSystemCaller */);
2924 }
2925 } finally {
2926 Binder.restoreCallingIdentity(ident);
2927 }
2928 }
2929
2930 @Override
2931 public void stopLockTaskModeByToken(IBinder token) {
2932 synchronized (mGlobalLock) {
2933 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2934 if (r == null) {
2935 return;
2936 }
Louis Changcdec0802019-11-11 11:45:07 +08002937 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002938 }
2939 }
2940
2941 /**
2942 * This API should be called by SystemUI only when user perform certain action to dismiss
2943 * lock task mode. We should only dismiss pinned lock task mode in this case.
2944 */
2945 @Override
2946 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002947 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002948 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2949 }
2950
Louis Changcdec0802019-11-11 11:45:07 +08002951 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2953 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2954 return;
2955 }
2956
Louis Chang149d5c82019-12-30 09:47:39 +08002957 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002958 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002959 throw new IllegalArgumentException("Invalid task, not in foreground");
2960 }
2961
2962 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2963 // system or a specific app.
2964 // * System-initiated requests will only start the pinned mode (screen pinning)
2965 // * App-initiated requests
2966 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2967 // - will start the pinned mode, otherwise
2968 final int callingUid = Binder.getCallingUid();
2969 long ident = Binder.clearCallingIdentity();
2970 try {
2971 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002972 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002973
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002974 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002975 } finally {
2976 Binder.restoreCallingIdentity(ident);
2977 }
2978 }
2979
Louis Changcdec0802019-11-11 11:45:07 +08002980 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002981 final int callingUid = Binder.getCallingUid();
2982 long ident = Binder.clearCallingIdentity();
2983 try {
2984 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002985 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002986 }
2987 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2988 // task and jumping straight into a call in the case of emergency call back.
2989 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2990 if (tm != null) {
2991 tm.showInCallScreen(false);
2992 }
2993 } finally {
2994 Binder.restoreCallingIdentity(ident);
2995 }
2996 }
2997
2998 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002999 public void updateLockTaskPackages(int userId, String[] packages) {
3000 final int callingUid = Binder.getCallingUid();
3001 if (callingUid != 0 && callingUid != SYSTEM_UID) {
3002 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
3003 "updateLockTaskPackages()");
3004 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08003005 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003006 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
3007 + Arrays.toString(packages));
3008 getLockTaskController().updateLockTaskPackages(userId, packages);
3009 }
3010 }
3011
3012 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003013 public boolean isInLockTaskMode() {
3014 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3015 }
3016
3017 @Override
3018 public int getLockTaskModeState() {
3019 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003020 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003021 }
3022 }
3023
3024 @Override
3025 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3026 synchronized (mGlobalLock) {
3027 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3028 if (r != null) {
3029 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003030 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003031 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003032 }
3033 }
3034 }
3035
3036 @Override
3037 public Bundle getActivityOptions(IBinder token) {
3038 final long origId = Binder.clearCallingIdentity();
3039 try {
3040 synchronized (mGlobalLock) {
3041 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3042 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003043 final ActivityOptions activityOptions = r.takeOptionsLocked(
3044 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003045 return activityOptions == null ? null : activityOptions.toBundle();
3046 }
3047 return null;
3048 }
3049 } finally {
3050 Binder.restoreCallingIdentity(origId);
3051 }
3052 }
3053
3054 @Override
3055 public List<IBinder> getAppTasks(String callingPackage) {
3056 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003057 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003058 long ident = Binder.clearCallingIdentity();
3059 try {
3060 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003061 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003062 }
3063 } finally {
3064 Binder.restoreCallingIdentity(ident);
3065 }
3066 }
3067
3068 @Override
3069 public void finishVoiceTask(IVoiceInteractionSession session) {
3070 synchronized (mGlobalLock) {
3071 final long origId = Binder.clearCallingIdentity();
3072 try {
3073 // TODO: VI Consider treating local voice interactions and voice tasks
3074 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003075 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003076 } finally {
3077 Binder.restoreCallingIdentity(origId);
3078 }
3079 }
3080
3081 }
3082
3083 @Override
3084 public boolean isTopOfTask(IBinder token) {
3085 synchronized (mGlobalLock) {
3086 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003087 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003088 }
3089 }
3090
3091 @Override
3092 public void notifyLaunchTaskBehindComplete(IBinder token) {
3093 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3094 }
3095
3096 @Override
3097 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003098 mH.post(() -> {
3099 synchronized (mGlobalLock) {
3100 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003101 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003102 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003103 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003104 } catch (RemoteException e) {
3105 }
3106 }
3107 }
3108
3109 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003110 }
3111
3112 /** Called from an app when assist data is ready. */
3113 @Override
3114 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3115 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003116 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003117 synchronized (pae) {
3118 pae.result = extras;
3119 pae.structure = structure;
3120 pae.content = content;
3121 if (referrer != null) {
3122 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3123 }
3124 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003125 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003126 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003127 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003128 structure.setHomeActivity(pae.isHome);
3129 }
3130 pae.haveResult = true;
3131 pae.notifyAll();
3132 if (pae.intent == null && pae.receiver == null) {
3133 // Caller is just waiting for the result.
3134 return;
3135 }
3136 }
3137 // We are now ready to launch the assist activity.
3138 IAssistDataReceiver sendReceiver = null;
3139 Bundle sendBundle = null;
3140 synchronized (mGlobalLock) {
3141 buildAssistBundleLocked(pae, extras);
3142 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003143 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003144 if (!exists) {
3145 // Timed out.
3146 return;
3147 }
3148
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003149 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003150 // Caller wants result sent back to them.
3151 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003152 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003153 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003154 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3155 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003156 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3157 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3158 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3159 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3160 }
3161 }
3162 if (sendReceiver != null) {
3163 try {
3164 sendReceiver.onHandleAssistData(sendBundle);
3165 } catch (RemoteException e) {
3166 }
3167 return;
3168 }
3169
3170 final long ident = Binder.clearCallingIdentity();
3171 try {
3172 if (TextUtils.equals(pae.intent.getAction(),
3173 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003174 // Start voice interaction through VoiceInteractionManagerService.
3175 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3176 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003177 } else {
3178 pae.intent.replaceExtras(pae.extras);
3179 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3180 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3181 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003182 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003183
3184 try {
3185 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3186 } catch (ActivityNotFoundException e) {
3187 Slog.w(TAG, "No activity to handle assist action.", e);
3188 }
3189 }
3190 } finally {
3191 Binder.restoreCallingIdentity(ident);
3192 }
3193 }
3194
3195 @Override
3196 public int addAppTask(IBinder activityToken, Intent intent,
3197 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3198 final int callingUid = Binder.getCallingUid();
3199 final long callingIdent = Binder.clearCallingIdentity();
3200
3201 try {
3202 synchronized (mGlobalLock) {
3203 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3204 if (r == null) {
3205 throw new IllegalArgumentException("Activity does not exist; token="
3206 + activityToken);
3207 }
3208 ComponentName comp = intent.getComponent();
3209 if (comp == null) {
3210 throw new IllegalArgumentException("Intent " + intent
3211 + " must specify explicit component");
3212 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003213 if (thumbnail.getWidth() != mThumbnailWidth
3214 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003215 throw new IllegalArgumentException("Bad thumbnail size: got "
3216 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003217 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003218 }
3219 if (intent.getSelector() != null) {
3220 intent.setSelector(null);
3221 }
3222 if (intent.getSourceBounds() != null) {
3223 intent.setSourceBounds(null);
3224 }
3225 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3226 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3227 // The caller has added this as an auto-remove task... that makes no
3228 // sense, so turn off auto-remove.
3229 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3230 }
3231 }
3232 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3233 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3234 if (ainfo.applicationInfo.uid != callingUid) {
3235 throw new SecurityException(
3236 "Can't add task for another application: target uid="
3237 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3238 }
3239
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003240 final ActivityStack stack = r.getRootTask();
Wale Ogunwale0d465192020-01-23 19:14:44 -08003241 final Task task = stack.getDisplay().createStack(stack.getWindowingMode(),
3242 stack.getActivityType(), !ON_TOP, ainfo, intent);
3243
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003244 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003245 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003246 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003247 return INVALID_TASK_ID;
3248 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003249 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003250
3251 // TODO: Send the thumbnail to WM to store it.
3252
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003253 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003254 }
3255 } finally {
3256 Binder.restoreCallingIdentity(callingIdent);
3257 }
3258 }
3259
3260 @Override
3261 public Point getAppTaskThumbnailSize() {
3262 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003263 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003264 }
3265 }
3266
3267 @Override
3268 public void setTaskResizeable(int taskId, int resizeableMode) {
3269 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003270 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003271 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3272 if (task == null) {
3273 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3274 return;
3275 }
3276 task.setResizeMode(resizeableMode);
3277 }
3278 }
3279
3280 @Override
3281 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003282 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003283 long ident = Binder.clearCallingIdentity();
3284 try {
3285 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003286 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003287 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003288 if (task == null) {
3289 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3290 return;
3291 }
3292 // Place the task in the right stack if it isn't there already based on
3293 // the requested bounds.
3294 // The stack transition logic is:
3295 // - a null bounds on a freeform task moves that task to fullscreen
3296 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3297 // that task to freeform
3298 // - otherwise the task is not moved
3299 ActivityStack stack = task.getStack();
3300 if (!task.getWindowConfiguration().canResizeTask()) {
3301 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3302 }
3303 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3304 stack = stack.getDisplay().getOrCreateStack(
3305 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3306 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3307 stack = stack.getDisplay().getOrCreateStack(
3308 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3309 }
3310
3311 // Reparent the task to the right stack if necessary
3312 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3313 if (stack != task.getStack()) {
3314 // Defer resume until the task is resized below
3315 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3316 DEFER_RESUME, "resizeTask");
3317 preserveWindow = false;
3318 }
3319
3320 // After reparenting (which only resizes the task to the stack bounds), resize the
3321 // task to the actual bounds provided
3322 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3323 }
3324 } finally {
3325 Binder.restoreCallingIdentity(ident);
3326 }
3327 }
3328
3329 @Override
3330 public boolean releaseActivityInstance(IBinder token) {
3331 synchronized (mGlobalLock) {
3332 final long origId = Binder.clearCallingIdentity();
3333 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003334 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3335 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003336 return false;
3337 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003338 r.destroyImmediately(true /* removeFromApp */, "app-req");
3339 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003340 } finally {
3341 Binder.restoreCallingIdentity(origId);
3342 }
3343 }
3344 }
3345
3346 @Override
3347 public void releaseSomeActivities(IApplicationThread appInt) {
3348 synchronized (mGlobalLock) {
3349 final long origId = Binder.clearCallingIdentity();
3350 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003351 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003352 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003353 } finally {
3354 Binder.restoreCallingIdentity(origId);
3355 }
3356 }
3357 }
3358
3359 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003360 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003361 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003362 != PackageManager.PERMISSION_GRANTED) {
3363 throw new SecurityException("Requires permission "
3364 + android.Manifest.permission.DEVICE_POWER);
3365 }
3366
3367 synchronized (mGlobalLock) {
3368 long ident = Binder.clearCallingIdentity();
3369 if (mKeyguardShown != keyguardShowing) {
3370 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003371 final Message msg = PooledLambda.obtainMessage(
3372 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3373 keyguardShowing);
3374 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003375 }
3376 try {
wilsonshih177261f2019-02-22 12:02:18 +08003377 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378 } finally {
3379 Binder.restoreCallingIdentity(ident);
3380 }
3381 }
3382
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003383 mH.post(() -> {
3384 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3385 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3386 }
3387 });
3388 }
3389
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003390 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003391 mH.post(() -> {
3392 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3393 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3394 }
3395 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003396 }
3397
3398 @Override
3399 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003400 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3401 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003402
3403 final File passedIconFile = new File(filePath);
3404 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3405 passedIconFile.getName());
3406 if (!legitIconFile.getPath().equals(filePath)
3407 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3408 throw new IllegalArgumentException("Bad file path: " + filePath
3409 + " passed for userId " + userId);
3410 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003411 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 }
3413
3414 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003415 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003416 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003417 synchronized (mGlobalLock) {
3418 final long ident = Binder.clearCallingIdentity();
3419 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003420 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003421 if (stack == null) {
3422 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3423 return;
3424 }
3425 if (!stack.isActivityTypeStandardOrUndefined()) {
3426 throw new IllegalArgumentException(
3427 "Removing non-standard stack is not allowed.");
3428 }
3429 mStackSupervisor.removeStack(stack);
3430 } finally {
3431 Binder.restoreCallingIdentity(ident);
3432 }
3433 }
3434 }
3435
3436 @Override
3437 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003438 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003439
3440 synchronized (mGlobalLock) {
3441 final long ident = Binder.clearCallingIdentity();
3442 try {
3443 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3444 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003445 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003446 } finally {
3447 Binder.restoreCallingIdentity(ident);
3448 }
3449 }
3450 }
3451
3452 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003453 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003454 synchronized (mGlobalLock) {
3455 long ident = Binder.clearCallingIdentity();
3456 try {
3457 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3458 if (r == null) {
3459 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003460 "toggleFreeformWindowingMode: No activity record matching token="
3461 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003462 }
3463
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003464 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003465 if (stack == null) {
3466 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3467 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003468 }
3469
Yunfan Chend967af82019-01-17 18:30:18 +09003470 if (!stack.inFreeformWindowingMode()
3471 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3472 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3473 + "toggle between fullscreen and freeform.");
3474 }
3475
3476 if (stack.inFreeformWindowingMode()) {
3477 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003478 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003479 throw new IllegalStateException("Size-compat windows are currently not"
3480 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003481 } else if (stack.getParent().inFreeformWindowingMode()) {
3482 // If the window is on a freeform display, set it to undefined. It will be
3483 // resolved to freeform and it can adjust windowing mode when the display mode
3484 // changes in runtime.
3485 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003486 } else {
3487 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3488 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003489 } finally {
3490 Binder.restoreCallingIdentity(ident);
3491 }
3492 }
3493 }
3494
3495 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3496 @Override
3497 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003498 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003499 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003500 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003501 }
3502
3503 /** Unregister a task stack listener so that it stops receiving callbacks. */
3504 @Override
3505 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003506 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003507 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003508 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003509 }
3510
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003511 @Override
3512 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3513 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3514 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3515 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3516 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3517 }
3518
3519 @Override
3520 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3521 IBinder activityToken, int flags) {
3522 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3523 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3524 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3525 }
3526
3527 @Override
3528 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3529 Bundle args) {
3530 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3531 true /* focused */, true /* newSessionId */, userHandle, args,
3532 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3533 }
3534
3535 @Override
3536 public Bundle getAssistContextExtras(int requestType) {
3537 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3538 null, null, true /* focused */, true /* newSessionId */,
3539 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3540 if (pae == null) {
3541 return null;
3542 }
3543 synchronized (pae) {
3544 while (!pae.haveResult) {
3545 try {
3546 pae.wait();
3547 } catch (InterruptedException e) {
3548 }
3549 }
3550 }
3551 synchronized (mGlobalLock) {
3552 buildAssistBundleLocked(pae, pae.result);
3553 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003554 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003555 }
3556 return pae.extras;
3557 }
3558
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003559 /**
3560 * Binder IPC calls go through the public entry point.
3561 * This can be called with or without the global lock held.
3562 */
3563 private static int checkCallingPermission(String permission) {
3564 return checkPermission(
3565 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3566 }
3567
3568 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003569 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003570 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3571 mAmInternal.enforceCallingPermission(permission, func);
3572 }
3573 }
3574
3575 @VisibleForTesting
3576 int checkGetTasksPermission(String permission, int pid, int uid) {
3577 return checkPermission(permission, pid, uid);
3578 }
3579
3580 static int checkPermission(String permission, int pid, int uid) {
3581 if (permission == null) {
3582 return PackageManager.PERMISSION_DENIED;
3583 }
3584 return checkComponentPermission(permission, pid, uid, -1, true);
3585 }
3586
Wale Ogunwale214f3482018-10-04 11:00:47 -07003587 public static int checkComponentPermission(String permission, int pid, int uid,
3588 int owningUid, boolean exported) {
3589 return ActivityManagerService.checkComponentPermission(
3590 permission, pid, uid, owningUid, exported);
3591 }
3592
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003593 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3594 if (getRecentTasks().isCallerRecents(callingUid)) {
3595 // Always allow the recents component to get tasks
3596 return true;
3597 }
3598
3599 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3600 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3601 if (!allowed) {
3602 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3603 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3604 // Temporary compatibility: some existing apps on the system image may
3605 // still be requesting the old permission and not switched to the new
3606 // one; if so, we'll still allow them full access. This means we need
3607 // to see if they are holding the old permission and are a system app.
3608 try {
3609 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3610 allowed = true;
3611 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3612 + " is using old GET_TASKS but privileged; allowing");
3613 }
3614 } catch (RemoteException e) {
3615 }
3616 }
3617 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3618 + " does not hold REAL_GET_TASKS; limiting output");
3619 }
3620 return allowed;
3621 }
3622
Nicholas Sauer0259e532019-08-30 08:24:55 -07003623 boolean isCrossUserAllowed(int pid, int uid) {
3624 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3625 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3626 }
3627
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003628 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3629 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3630 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3631 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003632 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003633 "enqueueAssistContext()");
3634
3635 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08003636 final ActivityStack stack = getTopDisplayFocusedStack();
3637 ActivityRecord activity = stack != null ? stack.getTopNonFinishingActivity() : null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003638 if (activity == null) {
3639 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3640 return null;
3641 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003642 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003643 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3644 return null;
3645 }
3646 if (focused) {
3647 if (activityToken != null) {
3648 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3649 if (activity != caller) {
3650 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3651 + " is not current top " + activity);
3652 return null;
3653 }
3654 }
3655 } else {
3656 activity = ActivityRecord.forTokenLocked(activityToken);
3657 if (activity == null) {
3658 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3659 + " couldn't be found");
3660 return null;
3661 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003662 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003663 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3664 return null;
3665 }
3666 }
3667
3668 PendingAssistExtras pae;
3669 Bundle extras = new Bundle();
3670 if (args != null) {
3671 extras.putAll(args);
3672 }
3673 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003674 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003675
3676 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3677 userHandle);
3678 pae.isHome = activity.isActivityTypeHome();
3679
3680 // Increment the sessionId if necessary
3681 if (newSessionId) {
3682 mViSessionId++;
3683 }
3684 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003685 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3686 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003687 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003688 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003689 } catch (RemoteException e) {
3690 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3691 return null;
3692 }
3693 return pae;
3694 }
3695 }
3696
3697 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3698 if (result != null) {
3699 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3700 }
3701 if (pae.hint != null) {
3702 pae.extras.putBoolean(pae.hint, true);
3703 }
3704 }
3705
3706 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3707 IAssistDataReceiver receiver;
3708 synchronized (mGlobalLock) {
3709 mPendingAssistExtras.remove(pae);
3710 receiver = pae.receiver;
3711 }
3712 if (receiver != null) {
3713 // Caller wants result sent back to them.
3714 Bundle sendBundle = new Bundle();
3715 // At least return the receiver extras
3716 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3717 try {
3718 pae.receiver.onHandleAssistData(sendBundle);
3719 } catch (RemoteException e) {
3720 }
3721 }
3722 }
3723
3724 public class PendingAssistExtras extends Binder implements Runnable {
3725 public final ActivityRecord activity;
3726 public boolean isHome;
3727 public final Bundle extras;
3728 public final Intent intent;
3729 public final String hint;
3730 public final IAssistDataReceiver receiver;
3731 public final int userHandle;
3732 public boolean haveResult = false;
3733 public Bundle result = null;
3734 public AssistStructure structure = null;
3735 public AssistContent content = null;
3736 public Bundle receiverExtras;
3737
3738 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3739 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3740 int _userHandle) {
3741 activity = _activity;
3742 extras = _extras;
3743 intent = _intent;
3744 hint = _hint;
3745 receiver = _receiver;
3746 receiverExtras = _receiverExtras;
3747 userHandle = _userHandle;
3748 }
3749
3750 @Override
3751 public void run() {
3752 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3753 synchronized (this) {
3754 haveResult = true;
3755 notifyAll();
3756 }
3757 pendingAssistExtrasTimedOut(this);
3758 }
3759 }
3760
3761 @Override
3762 public boolean isAssistDataAllowedOnCurrentActivity() {
3763 int userId;
3764 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003765 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003766 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3767 return false;
3768 }
3769
Wale Ogunwale21e06482019-11-18 05:14:15 -08003770 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003771 if (activity == null) {
3772 return false;
3773 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003774 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003775 }
3776 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3777 }
3778
3779 @Override
3780 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3781 long ident = Binder.clearCallingIdentity();
3782 try {
3783 synchronized (mGlobalLock) {
3784 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003785 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003786 if (top != caller) {
3787 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3788 + " is not current top " + top);
3789 return false;
3790 }
3791 if (!top.nowVisible) {
3792 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3793 + " is not visible");
3794 return false;
3795 }
3796 }
3797 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3798 token);
3799 } finally {
3800 Binder.restoreCallingIdentity(ident);
3801 }
3802 }
3803
3804 @Override
3805 public boolean isRootVoiceInteraction(IBinder token) {
3806 synchronized (mGlobalLock) {
3807 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3808 if (r == null) {
3809 return false;
3810 }
3811 return r.rootVoiceInteraction;
3812 }
3813 }
3814
Wale Ogunwalef6733932018-06-27 05:14:34 -07003815 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3816 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3817 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3818 if (activityToCallback == null) return;
3819 activityToCallback.setVoiceSessionLocked(voiceSession);
3820
3821 // Inform the activity
3822 try {
3823 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3824 voiceInteractor);
3825 long token = Binder.clearCallingIdentity();
3826 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003827 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003828 } finally {
3829 Binder.restoreCallingIdentity(token);
3830 }
3831 // TODO: VI Should we cache the activity so that it's easier to find later
3832 // rather than scan through all the stacks and activities?
3833 } catch (RemoteException re) {
3834 activityToCallback.clearVoiceSessionLocked();
3835 // TODO: VI Should this terminate the voice session?
3836 }
3837 }
3838
3839 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3840 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3841 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3842 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3843 boolean wasRunningVoice = mRunningVoice != null;
3844 mRunningVoice = session;
3845 if (!wasRunningVoice) {
3846 mVoiceWakeLock.acquire();
3847 updateSleepIfNeededLocked();
3848 }
3849 }
3850 }
3851
3852 void finishRunningVoiceLocked() {
3853 if (mRunningVoice != null) {
3854 mRunningVoice = null;
3855 mVoiceWakeLock.release();
3856 updateSleepIfNeededLocked();
3857 }
3858 }
3859
3860 @Override
3861 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3862 synchronized (mGlobalLock) {
3863 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3864 if (keepAwake) {
3865 mVoiceWakeLock.acquire();
3866 } else {
3867 mVoiceWakeLock.release();
3868 }
3869 }
3870 }
3871 }
3872
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003873 @Override
3874 public ComponentName getActivityClassForToken(IBinder token) {
3875 synchronized (mGlobalLock) {
3876 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3877 if (r == null) {
3878 return null;
3879 }
3880 return r.intent.getComponent();
3881 }
3882 }
3883
3884 @Override
3885 public String getPackageForToken(IBinder token) {
3886 synchronized (mGlobalLock) {
3887 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3888 if (r == null) {
3889 return null;
3890 }
3891 return r.packageName;
3892 }
3893 }
3894
3895 @Override
3896 public void showLockTaskEscapeMessage(IBinder token) {
3897 synchronized (mGlobalLock) {
3898 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3899 if (r == null) {
3900 return;
3901 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003902 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003903 }
3904 }
3905
3906 @Override
3907 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003908 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003909 final long token = Binder.clearCallingIdentity();
3910 try {
3911 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003912 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003913 }
3914 } finally {
3915 Binder.restoreCallingIdentity(token);
3916 }
3917 }
3918
3919 /**
3920 * Try to place task to provided position. The final position might be different depending on
3921 * current user and stacks state. The task will be moved to target stack if it's currently in
3922 * different stack.
3923 */
3924 @Override
3925 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003926 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003927 synchronized (mGlobalLock) {
3928 long ident = Binder.clearCallingIdentity();
3929 try {
3930 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3931 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003932 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003933 if (task == null) {
3934 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3935 + taskId);
3936 }
3937
Louis Chang149d5c82019-12-30 09:47:39 +08003938 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003939
3940 if (stack == null) {
3941 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3942 + stackId);
3943 }
3944 if (!stack.isActivityTypeStandardOrUndefined()) {
3945 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3946 + " the position of task " + taskId + " in/to non-standard stack");
3947 }
3948
3949 // TODO: Have the callers of this API call a separate reparent method if that is
3950 // what they intended to do vs. having this method also do reparenting.
3951 if (task.getStack() == stack) {
3952 // Change position in current stack.
3953 stack.positionChildAt(task, position);
3954 } else {
3955 // Reparent to new stack.
3956 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3957 !DEFER_RESUME, "positionTaskInStack");
3958 }
3959 } finally {
3960 Binder.restoreCallingIdentity(ident);
3961 }
3962 }
3963 }
3964
3965 @Override
3966 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3967 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3968 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003969 + Arrays.toString(horizontalSizeConfiguration) + " "
3970 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003971 synchronized (mGlobalLock) {
3972 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3973 if (record == null) {
3974 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3975 + "found for: " + token);
3976 }
3977 record.setSizeConfigurations(horizontalSizeConfiguration,
3978 verticalSizeConfigurations, smallestSizeConfigurations);
3979 }
3980 }
3981
3982 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003983 * Dismisses Pip
3984 * @param animate True if the dismissal should be animated.
3985 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3986 * default animation duration should be used.
3987 */
3988 @Override
3989 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003990 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003991 final long ident = Binder.clearCallingIdentity();
3992 try {
3993 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003994 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08003995 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003996 if (stack == null) {
3997 Slog.w(TAG, "dismissPip: pinned stack not found.");
3998 return;
3999 }
4000 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4001 throw new IllegalArgumentException("Stack: " + stack
4002 + " doesn't support animated resize.");
4003 }
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004004 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004005 }
4006 } finally {
4007 Binder.restoreCallingIdentity(ident);
4008 }
4009 }
4010
4011 @Override
4012 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004013 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004014 synchronized (mGlobalLock) {
4015 mSuppressResizeConfigChanges = suppress;
4016 }
4017 }
4018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004019 @Override
4020 // TODO: API should just be about changing windowing modes...
4021 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004022 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004023 "moveTasksToFullscreenStack()");
4024 synchronized (mGlobalLock) {
4025 final long origId = Binder.clearCallingIdentity();
4026 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004027 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004028 if (stack != null){
4029 if (!stack.isActivityTypeStandardOrUndefined()) {
4030 throw new IllegalArgumentException(
4031 "You can't move tasks from non-standard stacks.");
4032 }
4033 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4034 }
4035 } finally {
4036 Binder.restoreCallingIdentity(origId);
4037 }
4038 }
4039 }
4040
4041 /**
4042 * Moves the top activity in the input stackId to the pinned stack.
4043 *
4044 * @param stackId Id of stack to move the top activity to pinned stack.
4045 * @param bounds Bounds to use for pinned stack.
4046 *
4047 * @return True if the top activity of the input stack was successfully moved to the pinned
4048 * stack.
4049 */
4050 @Override
4051 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004052 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004053 "moveTopActivityToPinnedStack()");
4054 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004055 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004056 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4057 + "Device doesn't support picture-in-picture mode");
4058 }
4059
4060 long ident = Binder.clearCallingIdentity();
4061 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004062 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004063 } finally {
4064 Binder.restoreCallingIdentity(ident);
4065 }
4066 }
4067 }
4068
4069 @Override
4070 public boolean isInMultiWindowMode(IBinder token) {
4071 final long origId = Binder.clearCallingIdentity();
4072 try {
4073 synchronized (mGlobalLock) {
4074 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4075 if (r == null) {
4076 return false;
4077 }
4078 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4079 return r.inMultiWindowMode();
4080 }
4081 } finally {
4082 Binder.restoreCallingIdentity(origId);
4083 }
4084 }
4085
4086 @Override
4087 public boolean isInPictureInPictureMode(IBinder token) {
4088 final long origId = Binder.clearCallingIdentity();
4089 try {
4090 synchronized (mGlobalLock) {
4091 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4092 }
4093 } finally {
4094 Binder.restoreCallingIdentity(origId);
4095 }
4096 }
4097
4098 private boolean isInPictureInPictureMode(ActivityRecord r) {
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004099 return r != null
4100 && r.getRootTask() != null
4101 && r.inPinnedWindowingMode()
4102 && r.getRootTask().isInStackLocked(r) != null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004103 }
4104
4105 @Override
4106 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4107 final long origId = Binder.clearCallingIdentity();
4108 try {
4109 synchronized (mGlobalLock) {
4110 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4111 "enterPictureInPictureMode", token, params);
4112
4113 // If the activity is already in picture in picture mode, then just return early
4114 if (isInPictureInPictureMode(r)) {
4115 return true;
4116 }
4117
4118 // Activity supports picture-in-picture, now check that we can enter PiP at this
4119 // point, if it is
4120 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4121 false /* beforeStopping */)) {
4122 return false;
4123 }
4124
4125 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004126 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004127 if (r.getParent() == null) {
4128 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4129 return;
4130 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004131 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004132 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004133 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4134 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4135 // Adjust the source bounds by the insets for the transition down
4136 final Rect sourceBounds = new Rect(
4137 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004138 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004139 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004140 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004141 stack.setPictureInPictureAspectRatio(aspectRatio);
4142 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004143 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4144 r.info.applicationInfo.uid, r.shortComponentName,
4145 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004146 logPictureInPictureArgs(params);
4147 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004148 };
4149
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004150 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004151 // If the keyguard is showing or occluded, then try and dismiss it before
4152 // entering picture-in-picture (this will prompt the user to authenticate if the
4153 // device is currently locked).
4154 dismissKeyguard(token, new KeyguardDismissCallback() {
4155 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004156 public void onDismissSucceeded() {
4157 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004158 }
4159 }, null /* message */);
4160 } else {
4161 // Enter picture in picture immediately otherwise
4162 enterPipRunnable.run();
4163 }
4164 return true;
4165 }
4166 } finally {
4167 Binder.restoreCallingIdentity(origId);
4168 }
4169 }
4170
4171 @Override
4172 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4173 final long origId = Binder.clearCallingIdentity();
4174 try {
4175 synchronized (mGlobalLock) {
4176 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4177 "setPictureInPictureParams", token, params);
4178
4179 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004180 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004181 if (r.inPinnedWindowingMode()) {
4182 // If the activity is already in picture-in-picture, update the pinned stack now
4183 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4184 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004185 final ActivityStack stack = r.getRootTask();
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004186 stack.setPictureInPictureAspectRatio(
4187 r.pictureInPictureArgs.getAspectRatio());
4188 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004189 }
4190 logPictureInPictureArgs(params);
4191 }
4192 } finally {
4193 Binder.restoreCallingIdentity(origId);
4194 }
4195 }
4196
4197 @Override
4198 public int getMaxNumPictureInPictureActions(IBinder token) {
4199 // Currently, this is a static constant, but later, we may change this to be dependent on
4200 // the context of the activity
4201 return 3;
4202 }
4203
4204 private void logPictureInPictureArgs(PictureInPictureParams params) {
4205 if (params.hasSetActions()) {
4206 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4207 params.getActions().size());
4208 }
4209 if (params.hasSetAspectRatio()) {
4210 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4211 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4212 MetricsLogger.action(lm);
4213 }
4214 }
4215
4216 /**
4217 * Checks the state of the system and the activity associated with the given {@param token} to
4218 * verify that picture-in-picture is supported for that activity.
4219 *
4220 * @return the activity record for the given {@param token} if all the checks pass.
4221 */
4222 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4223 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004224 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004225 throw new IllegalStateException(caller
4226 + ": Device doesn't support picture-in-picture mode.");
4227 }
4228
4229 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4230 if (r == null) {
4231 throw new IllegalStateException(caller
4232 + ": Can't find activity for token=" + token);
4233 }
4234
4235 if (!r.supportsPictureInPicture()) {
4236 throw new IllegalStateException(caller
4237 + ": Current activity does not support picture-in-picture.");
4238 }
4239
4240 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004241 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004242 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004243 final float minAspectRatio = mContext.getResources().getFloat(
4244 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4245 final float maxAspectRatio = mContext.getResources().getFloat(
4246 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4247 throw new IllegalArgumentException(String.format(caller
4248 + ": Aspect ratio is too extreme (must be between %f and %f).",
4249 minAspectRatio, maxAspectRatio));
4250 }
4251
4252 // Truncate the number of actions if necessary
4253 params.truncateActions(getMaxNumPictureInPictureActions(token));
4254
4255 return r;
4256 }
4257
4258 @Override
4259 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004260 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004261 synchronized (mGlobalLock) {
4262 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4263 if (r == null) {
4264 throw new IllegalArgumentException("Activity does not exist; token="
4265 + activityToken);
4266 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004267 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004268 }
4269 }
4270
Evan Rosky73a7fe92019-11-18 18:28:01 -08004271 // TODO(b/149338177): remove when CTS no-longer requires it
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004272 @Override
4273 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4274 Rect tempDockedTaskInsetBounds,
4275 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004276 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004277 long ident = Binder.clearCallingIdentity();
4278 try {
4279 synchronized (mGlobalLock) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08004280 final DisplayContent dc = mRootWindowContainer.getDefaultDisplay();
4281 TaskTile primary = null;
4282 TaskTile secondary = null;
4283 for (int i = dc.getStackCount() - 1; i >= 0; --i) {
4284 final TaskTile t = dc.getStackAt(i).asTile();
4285 if (t == null) {
4286 continue;
4287 }
4288 if (t.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
4289 primary = t;
4290 } else if (t.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY) {
4291 secondary = t;
4292 }
4293 }
4294 if (primary == null || secondary == null) {
4295 return;
4296 }
4297 final WindowContainerTransaction wct = new WindowContainerTransaction();
4298 final Rect primaryRect =
4299 tempDockedTaskInsetBounds != null ? tempDockedTaskInsetBounds
4300 : (tempDockedTaskBounds != null ? tempDockedTaskBounds
4301 : dockedBounds);
4302 wct.setBounds(primary.mRemoteToken, primaryRect);
4303 Rect otherRect = tempOtherTaskInsetBounds != null ? tempOtherTaskInsetBounds
4304 : tempOtherTaskBounds;
4305 if (otherRect == null) {
4306 // Temporary estimation... again this is just for tests.
4307 otherRect = new Rect(secondary.getBounds());
4308 if (dc.getBounds().width() > dc.getBounds().height()) {
4309 otherRect.left = primaryRect.right + 6;
4310 } else {
4311 otherRect.top = primaryRect.bottom + 6;
4312 }
4313 }
4314 wct.setBounds(secondary.mRemoteToken, otherRect);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004315 mWindowOrganizerController.applyTransaction(wct);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004316 }
4317 } finally {
4318 Binder.restoreCallingIdentity(ident);
4319 }
4320 }
4321
4322 @Override
4323 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004324 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004325 final long ident = Binder.clearCallingIdentity();
4326 try {
4327 synchronized (mGlobalLock) {
4328 mStackSupervisor.setSplitScreenResizing(resizing);
4329 }
4330 } finally {
4331 Binder.restoreCallingIdentity(ident);
4332 }
4333 }
4334
Evan Rosky0037e5f2019-11-05 10:26:24 -08004335 @Override
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004336 public IWindowOrganizerController getWindowOrganizerController() {
Evan Rosky0037e5f2019-11-05 10:26:24 -08004337 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004338 "getWindowOrganizerController()");
4339 return mWindowOrganizerController;
Evan Rosky0037e5f2019-11-05 10:26:24 -08004340 }
4341
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004342 /**
4343 * Check that we have the features required for VR-related API calls, and throw an exception if
4344 * not.
4345 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004346 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004347 if (!mContext.getPackageManager().hasSystemFeature(
4348 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4349 throw new UnsupportedOperationException("VR mode not supported on this device!");
4350 }
4351 }
4352
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004353 @Override
4354 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004355 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004356
4357 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4358
4359 ActivityRecord r;
4360 synchronized (mGlobalLock) {
4361 r = ActivityRecord.isInStackLocked(token);
4362 }
4363
4364 if (r == null) {
4365 throw new IllegalArgumentException();
4366 }
4367
4368 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004369 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004370 VrManagerInternal.NO_ERROR) {
4371 return err;
4372 }
4373
4374 // Clear the binder calling uid since this path may call moveToTask().
4375 final long callingId = Binder.clearCallingIdentity();
4376 try {
4377 synchronized (mGlobalLock) {
4378 r.requestedVrComponent = (enabled) ? packageName : null;
4379
4380 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004381 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004382 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004383 }
4384 return 0;
4385 }
4386 } finally {
4387 Binder.restoreCallingIdentity(callingId);
4388 }
4389 }
4390
4391 @Override
4392 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4393 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4394 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004395 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004396 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4397 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4398 }
Louis Changcdec0802019-11-11 11:45:07 +08004399 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004400 || activity.voiceSession != null) {
4401 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4402 return;
4403 }
4404 if (activity.pendingVoiceInteractionStart) {
4405 Slog.w(TAG, "Pending start of voice interaction already.");
4406 return;
4407 }
4408 activity.pendingVoiceInteractionStart = true;
4409 }
4410 LocalServices.getService(VoiceInteractionManagerInternal.class)
4411 .startLocalVoiceInteraction(callingActivity, options);
4412 }
4413
4414 @Override
4415 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4416 LocalServices.getService(VoiceInteractionManagerInternal.class)
4417 .stopLocalVoiceInteraction(callingActivity);
4418 }
4419
4420 @Override
4421 public boolean supportsLocalVoiceInteraction() {
4422 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4423 .supportsLocalVoiceInteraction();
4424 }
4425
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004426 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004427 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004428 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004429
4430 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004431 if (mWindowManager == null) {
4432 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4433 return false;
4434 }
4435
4436 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004437 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004438 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004439 }
4440
Riddle Hsua0022cd2019-09-09 21:12:41 +08004441 mH.sendMessage(PooledLambda.obtainMessage(
4442 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4443 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444
4445 final long origId = Binder.clearCallingIdentity();
4446 try {
4447 if (values != null) {
4448 Settings.System.clearConfiguration(values);
4449 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004450 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004451 UserHandle.USER_NULL, false /* deferResume */,
4452 mTmpUpdateConfigurationResult);
4453 return mTmpUpdateConfigurationResult.changes != 0;
4454 } finally {
4455 Binder.restoreCallingIdentity(origId);
4456 }
4457 }
4458 }
4459
4460 @Override
4461 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4462 CharSequence message) {
4463 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004464 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004465 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4466 }
4467 final long callingId = Binder.clearCallingIdentity();
4468 try {
4469 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004470 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004471 }
4472 } finally {
4473 Binder.restoreCallingIdentity(callingId);
4474 }
4475 }
4476
4477 @Override
4478 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004479 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004480 "cancelTaskWindowTransition()");
4481 final long ident = Binder.clearCallingIdentity();
4482 try {
4483 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004484 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004485 MATCH_TASK_IN_STACKS_ONLY);
4486 if (task == null) {
4487 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4488 return;
4489 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004490 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004491 }
4492 } finally {
4493 Binder.restoreCallingIdentity(ident);
4494 }
4495 }
4496
4497 @Override
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004498 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004499 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004500 final long ident = Binder.clearCallingIdentity();
4501 try {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004502 return getTaskSnapshot(taskId, isLowResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004503 } finally {
4504 Binder.restoreCallingIdentity(ident);
4505 }
4506 }
4507
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004508 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004509 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004510 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004511 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004512 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004513 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4514 if (task == null) {
4515 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4516 return null;
4517 }
4518 }
4519 // Don't call this while holding the lock as this operation might hit the disk.
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004520 return task.getSnapshot(isLowResolution, restoreFromDisk);
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004521 }
4522
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004523 @Override
4524 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4525 synchronized (mGlobalLock) {
4526 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4527 if (r == null) {
4528 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4529 + token);
4530 return;
4531 }
4532 final long origId = Binder.clearCallingIdentity();
4533 try {
4534 r.setDisablePreviewScreenshots(disable);
4535 } finally {
4536 Binder.restoreCallingIdentity(origId);
4537 }
4538 }
4539 }
4540
Riddle Hsu440f88b2019-11-06 22:17:35 +08004541 @Override
4542 public void invalidateHomeTaskSnapshot(IBinder token) {
4543 synchronized (mGlobalLock) {
4544 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4545 if (r == null || !r.isActivityTypeHome()) {
4546 return;
4547 }
4548 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4549 }
4550 }
4551
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004552 /** Return the user id of the last resumed activity. */
4553 @Override
4554 public @UserIdInt
4555 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004556 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004557 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4558 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004559 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004560 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004561 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004562 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004563 }
4564 }
4565
4566 @Override
4567 public void updateLockTaskFeatures(int userId, int flags) {
4568 final int callingUid = Binder.getCallingUid();
4569 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004570 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004571 "updateLockTaskFeatures()");
4572 }
4573 synchronized (mGlobalLock) {
4574 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4575 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004576 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004577 }
4578 }
4579
4580 @Override
4581 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4582 synchronized (mGlobalLock) {
4583 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4584 if (r == null) {
4585 return;
4586 }
4587 final long origId = Binder.clearCallingIdentity();
4588 try {
4589 r.setShowWhenLocked(showWhenLocked);
4590 } finally {
4591 Binder.restoreCallingIdentity(origId);
4592 }
4593 }
4594 }
4595
4596 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004597 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4598 synchronized (mGlobalLock) {
4599 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4600 if (r == null) {
4601 return;
4602 }
4603 final long origId = Binder.clearCallingIdentity();
4604 try {
4605 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4606 } finally {
4607 Binder.restoreCallingIdentity(origId);
4608 }
4609 }
4610 }
4611
4612 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004613 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4614 synchronized (mGlobalLock) {
4615 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4616 if (r == null) {
4617 return;
4618 }
4619 final long origId = Binder.clearCallingIdentity();
4620 try {
4621 r.setTurnScreenOn(turnScreenOn);
4622 } finally {
4623 Binder.restoreCallingIdentity(origId);
4624 }
4625 }
4626 }
4627
4628 @Override
4629 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004630 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004631 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004632 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004633 synchronized (mGlobalLock) {
4634 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4635 if (r == null) {
4636 return;
4637 }
4638 final long origId = Binder.clearCallingIdentity();
4639 try {
4640 r.registerRemoteAnimations(definition);
4641 } finally {
4642 Binder.restoreCallingIdentity(origId);
4643 }
4644 }
4645 }
4646
4647 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004648 public void unregisterRemoteAnimations(IBinder token) {
4649 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4650 "unregisterRemoteAnimations");
4651 synchronized (mGlobalLock) {
4652 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4653 if (r == null) {
4654 return;
4655 }
4656 final long origId = Binder.clearCallingIdentity();
4657 try {
4658 r.unregisterRemoteAnimations();
4659 } finally {
4660 Binder.restoreCallingIdentity(origId);
4661 }
4662 }
4663 }
4664
4665 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004666 public void registerRemoteAnimationForNextActivityStart(String packageName,
4667 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004668 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004669 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004670 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004671 synchronized (mGlobalLock) {
4672 final long origId = Binder.clearCallingIdentity();
4673 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004674 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004675 packageName, adapter);
4676 } finally {
4677 Binder.restoreCallingIdentity(origId);
4678 }
4679 }
4680 }
4681
Evan Rosky966759f2019-01-15 10:33:58 -08004682 @Override
4683 public void registerRemoteAnimationsForDisplay(int displayId,
4684 RemoteAnimationDefinition definition) {
4685 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4686 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004687 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004688 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004689 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004690 if (display == null) {
4691 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4692 return;
4693 }
4694 final long origId = Binder.clearCallingIdentity();
4695 try {
4696 display.mDisplayContent.registerRemoteAnimations(definition);
4697 } finally {
4698 Binder.restoreCallingIdentity(origId);
4699 }
4700 }
4701 }
4702
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004703 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4704 @Override
4705 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4706 synchronized (mGlobalLock) {
4707 final long origId = Binder.clearCallingIdentity();
4708 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004709 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004710 } finally {
4711 Binder.restoreCallingIdentity(origId);
4712 }
4713 }
4714 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004715
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004716 @Override
4717 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004718 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004719 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004720 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004721 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004722 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004723 }
4724 }
4725
4726 @Override
4727 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004728 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004729 != PERMISSION_GRANTED) {
4730 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4731 + Binder.getCallingPid()
4732 + ", uid=" + Binder.getCallingUid()
4733 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4734 Slog.w(TAG, msg);
4735 throw new SecurityException(msg);
4736 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004737 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004738 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004739 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004740 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004741 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004742 }
4743 }
4744
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004745 @Override
4746 public void stopAppSwitches() {
4747 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4748 synchronized (mGlobalLock) {
4749 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004750 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004751 mDidAppSwitch = false;
4752 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4753 }
4754 }
4755
4756 @Override
4757 public void resumeAppSwitches() {
4758 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4759 synchronized (mGlobalLock) {
4760 // Note that we don't execute any pending app switches... we will
4761 // let those wait until either the timeout, or the next start
4762 // activity request.
4763 mAppSwitchesAllowedTime = 0;
4764 }
4765 }
4766
Ricky Wai906af482019-06-03 17:25:28 +01004767 long getLastStopAppSwitchesTime() {
4768 return mLastStopAppSwitchesTime;
4769 }
4770
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004771 void onStartActivitySetDidAppSwitch() {
4772 if (mDidAppSwitch) {
4773 // This is the second allowed switch since we stopped switches, so now just generally
4774 // allow switches. Use case:
4775 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4776 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4777 // anyone to switch again).
4778 mAppSwitchesAllowedTime = 0;
4779 } else {
4780 mDidAppSwitch = true;
4781 }
4782 }
4783
4784 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004785 boolean shouldDisableNonVrUiLocked() {
4786 return mVrController.shouldDisableNonVrUiLocked();
4787 }
4788
Wale Ogunwale53783742018-09-16 10:21:51 -07004789 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004790 // 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 +00004791 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004792 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004793 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4794 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004795 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004796 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004797 }
4798 mH.post(() -> {
4799 if (!mVrController.onVrModeChanged(r)) {
4800 return;
4801 }
4802 synchronized (mGlobalLock) {
4803 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4804 mWindowManager.disableNonVrUi(disableNonVrUi);
4805 if (disableNonVrUi) {
4806 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4807 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004808 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004809 }
4810 }
4811 });
4812 }
4813
Wale Ogunwale53783742018-09-16 10:21:51 -07004814 @Override
4815 public int getPackageScreenCompatMode(String packageName) {
4816 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4817 synchronized (mGlobalLock) {
4818 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4819 }
4820 }
4821
4822 @Override
4823 public void setPackageScreenCompatMode(String packageName, int mode) {
4824 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4825 "setPackageScreenCompatMode");
4826 synchronized (mGlobalLock) {
4827 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4828 }
4829 }
4830
4831 @Override
4832 public boolean getPackageAskScreenCompat(String packageName) {
4833 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4834 synchronized (mGlobalLock) {
4835 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4836 }
4837 }
4838
4839 @Override
4840 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4841 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4842 "setPackageAskScreenCompat");
4843 synchronized (mGlobalLock) {
4844 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4845 }
4846 }
4847
Wale Ogunwale64258362018-10-16 15:13:37 -07004848 public static String relaunchReasonToString(int relaunchReason) {
4849 switch (relaunchReason) {
4850 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4851 return "window_resize";
4852 case RELAUNCH_REASON_FREE_RESIZE:
4853 return "free_resize";
4854 default:
4855 return null;
4856 }
4857 }
4858
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004859 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004860 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004861 }
4862
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004863 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004864 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004865 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4866 }
4867
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004868 boolean isKeyguardLocked() {
4869 return mKeyguardController.isKeyguardLocked();
4870 }
4871
Garfield Tan01548632018-11-27 10:15:48 -08004872 /**
4873 * Clears launch params for the given package.
4874 * @param packageNames the names of the packages of which the launch params are to be cleared
4875 */
4876 @Override
4877 public void clearLaunchParamsForPackages(List<String> packageNames) {
4878 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4879 "clearLaunchParamsForPackages");
4880 synchronized (mGlobalLock) {
4881 for (int i = 0; i < packageNames.size(); ++i) {
4882 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4883 }
4884 }
4885 }
4886
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004887 /**
4888 * Makes the display with the given id a single task instance display. I.e the display can only
4889 * contain one task.
4890 */
4891 @Override
4892 public void setDisplayToSingleTaskInstance(int displayId) {
4893 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4894 "setDisplayToSingleTaskInstance");
4895 final long origId = Binder.clearCallingIdentity();
4896 try {
Louis Chang677921f2019-12-06 16:44:24 +08004897 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004898 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004899 if (display != null) {
4900 display.setDisplayToSingleTaskInstance();
4901 }
4902 } finally {
4903 Binder.restoreCallingIdentity(origId);
4904 }
4905 }
4906
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004907 /**
4908 * Requests that an activity should enter picture-in-picture mode if possible.
4909 */
4910 @Override
4911 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4912 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4913 "requestPictureInPictureMode");
4914 final long origId = Binder.clearCallingIdentity();
4915 try {
4916 synchronized (mGlobalLock) {
4917 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4918 if (activity == null) {
4919 return;
4920 }
4921
4922 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4923 "requestPictureInPictureMode", /* beforeStopping */ false);
4924 if (!canEnterPictureInPicture) {
4925 throw new IllegalStateException(
4926 "Requested PIP on an activity that doesn't support it");
4927 }
4928
4929 try {
4930 final ClientTransaction transaction = ClientTransaction.obtain(
4931 activity.app.getThread(),
4932 activity.token);
4933 transaction.addCallback(EnterPipRequestedItem.obtain());
4934 getLifecycleManager().scheduleTransaction(transaction);
4935 } catch (Exception e) {
4936 Slog.w(TAG, "Failed to send enter pip requested item: "
4937 + activity.intent.getComponent(), e);
4938 }
4939 }
4940 } finally {
4941 Binder.restoreCallingIdentity(origId);
4942 }
4943 }
4944
Wale Ogunwale31913b52018-10-13 08:29:31 -07004945 void dumpLastANRLocked(PrintWriter pw) {
4946 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4947 if (mLastANRState == null) {
4948 pw.println(" <no ANR has occurred since boot>");
4949 } else {
4950 pw.println(mLastANRState);
4951 }
4952 }
4953
4954 void dumpLastANRTracesLocked(PrintWriter pw) {
4955 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4956
4957 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4958 if (ArrayUtils.isEmpty(files)) {
4959 pw.println(" <no ANR has occurred since boot>");
4960 return;
4961 }
4962 // Find the latest file.
4963 File latest = null;
4964 for (File f : files) {
4965 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4966 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004967 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004968 }
4969 pw.print("File: ");
4970 pw.print(latest.getName());
4971 pw.println();
4972 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4973 String line;
4974 while ((line = in.readLine()) != null) {
4975 pw.println(line);
4976 }
4977 } catch (IOException e) {
4978 pw.print("Unable to read: ");
4979 pw.print(e);
4980 pw.println();
4981 }
4982 }
4983
4984 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4985 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4986 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4987 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4988 }
4989
4990 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4991 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4992 pw.println(header);
4993
Louis Chang149d5c82019-12-30 09:47:39 +08004994 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004995 dumpPackage);
4996 boolean needSep = printedAnything;
4997
4998 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08004999 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005000 " ResumedActivity: ");
5001 if (printed) {
5002 printedAnything = true;
5003 needSep = false;
5004 }
5005
5006 if (dumpPackage == null) {
5007 if (needSep) {
5008 pw.println();
5009 }
5010 printedAnything = true;
5011 mStackSupervisor.dump(pw, " ");
5012 }
5013
5014 if (!printedAnything) {
5015 pw.println(" (nothing)");
5016 }
5017 }
5018
5019 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005020 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005021 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005022 pw.println(" ");
5023 }
5024
5025 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5026 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5027 getActivityStartController().dump(pw, "", dumpPackage);
5028 }
5029
5030 /**
5031 * There are three things that cmd can be:
5032 * - a flattened component name that matches an existing activity
5033 * - the cmd arg isn't the flattened component name of an existing activity:
5034 * dump all activity whose component contains the cmd as a substring
5035 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005036 * <p>
5037 * The caller should not hold lock when calling this method because it will wait for the
5038 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005039 *
5040 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5041 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5042 */
5043 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5044 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5045 ArrayList<ActivityRecord> activities;
5046
5047 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005048 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005049 dumpFocusedStackOnly);
5050 }
5051
5052 if (activities.size() <= 0) {
5053 return false;
5054 }
5055
5056 String[] newArgs = new String[args.length - opti];
5057 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5058
Louis Changcdec0802019-11-11 11:45:07 +08005059 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005060 boolean needSep = false;
5061 for (int i = activities.size() - 1; i >= 0; i--) {
5062 ActivityRecord r = activities.get(i);
5063 if (needSep) {
5064 pw.println();
5065 }
5066 needSep = true;
5067 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005068 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005069 if (lastTask != task) {
5070 lastTask = task;
5071 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005072 pw.print(" id="); pw.print(lastTask.mTaskId);
5073 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005074 if (dumpAll) {
5075 lastTask.dump(pw, " ");
5076 }
5077 }
5078 }
5079 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5080 }
5081 return true;
5082 }
5083
5084 /**
5085 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5086 * there is a thread associated with the activity.
5087 */
5088 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5089 final ActivityRecord r, String[] args, boolean dumpAll) {
5090 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005091 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005092 synchronized (mGlobalLock) {
5093 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5094 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5095 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005096 if (r.hasProcess()) {
5097 pw.println(r.app.getPid());
5098 appThread = r.app.getThread();
5099 } else {
5100 pw.println("(not running)");
5101 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005102 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005103 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005104 }
5105 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005106 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005107 // flush anything that is already in the PrintWriter since the thread is going
5108 // to write to the file descriptor directly
5109 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005110 try (TransferPipe tp = new TransferPipe()) {
5111 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5112 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005113 } catch (IOException e) {
5114 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5115 } catch (RemoteException e) {
5116 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5117 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005118 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005119 }
5120
sanryhuang498e77e2018-12-06 14:57:01 +08005121 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5122 boolean testPssMode) {
5123 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5124 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5125 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005126 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005127 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5128 st.toString());
5129 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005130 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5131 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5132 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005133 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5134 testPssMode);
5135 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005136 }
5137
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005138 int getCurrentUserId() {
5139 return mAmInternal.getCurrentUserId();
5140 }
5141
5142 private void enforceNotIsolatedCaller(String caller) {
5143 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5144 throw new SecurityException("Isolated process not allowed to call " + caller);
5145 }
5146 }
5147
Wale Ogunwalef6733932018-06-27 05:14:34 -07005148 public Configuration getConfiguration() {
5149 Configuration ci;
5150 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005151 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005152 ci.userSetLocale = false;
5153 }
5154 return ci;
5155 }
5156
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005157 /**
5158 * Current global configuration information. Contains general settings for the entire system,
5159 * also corresponds to the merged configuration of the default display.
5160 */
5161 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005162 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005163 // while initializing process record for system, see {@link
5164 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005165 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005166 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005167 }
5168
5169 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5170 boolean initLocale) {
5171 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5172 }
5173
5174 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5175 boolean initLocale, boolean deferResume) {
5176 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5177 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5178 UserHandle.USER_NULL, deferResume);
5179 }
5180
Wale Ogunwale59507092018-10-29 09:00:30 -07005181 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005182 final long origId = Binder.clearCallingIdentity();
5183 try {
5184 synchronized (mGlobalLock) {
5185 updateConfigurationLocked(values, null, false, true, userId,
5186 false /* deferResume */);
5187 }
5188 } finally {
5189 Binder.restoreCallingIdentity(origId);
5190 }
5191 }
5192
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005193 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5194 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5195 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5196 deferResume, null /* result */);
5197 }
5198
5199 /**
5200 * Do either or both things: (1) change the current configuration, and (2)
5201 * make sure the given activity is running with the (now) current
5202 * configuration. Returns true if the activity has been left running, or
5203 * false if <var>starting</var> is being destroyed to match the new
5204 * configuration.
5205 *
5206 * @param userId is only used when persistent parameter is set to true to persist configuration
5207 * for that particular user
5208 */
5209 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5210 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5211 ActivityTaskManagerService.UpdateConfigurationResult result) {
5212 int changes = 0;
5213 boolean kept = true;
5214
Riddle Hsua0022cd2019-09-09 21:12:41 +08005215 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005216 try {
5217 if (values != null) {
5218 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5219 deferResume);
5220 }
5221
5222 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5223 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005224 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005225 }
5226
5227 if (result != null) {
5228 result.changes = changes;
5229 result.activityRelaunched = !kept;
5230 }
5231 return kept;
5232 }
5233
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005234 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005235 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005236 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005237
Louis Chang677921f2019-12-06 16:44:24 +08005238 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005239 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005240
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005241 mTempConfig.setTo(getGlobalConfiguration());
5242 final int changes = mTempConfig.updateFrom(values);
5243 if (changes == 0) {
5244 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5245 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5246 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5247 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005248 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005249 return 0;
5250 }
5251
5252 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5253 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005254 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005255 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005256 values.colorMode,
5257 values.densityDpi,
5258 values.fontScale,
5259 values.hardKeyboardHidden,
5260 values.keyboard,
5261 values.keyboardHidden,
5262 values.mcc,
5263 values.mnc,
5264 values.navigation,
5265 values.navigationHidden,
5266 values.orientation,
5267 values.screenHeightDp,
5268 values.screenLayout,
5269 values.screenWidthDp,
5270 values.smallestScreenWidthDp,
5271 values.touchscreen,
5272 values.uiMode);
5273
5274
5275 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5276 final LocaleList locales = values.getLocales();
5277 int bestLocaleIndex = 0;
5278 if (locales.size() > 1) {
5279 if (mSupportedSystemLocales == null) {
5280 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5281 }
5282 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5283 }
5284 SystemProperties.set("persist.sys.locale",
5285 locales.get(bestLocaleIndex).toLanguageTag());
5286 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005287
5288 final Message m = PooledLambda.obtainMessage(
5289 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5290 locales.get(bestLocaleIndex));
5291 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005292 }
5293
Yunfan Chen75157d72018-07-27 14:47:21 +09005294 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005295
5296 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005297 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005298
5299 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5300 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005301 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005302
5303 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005304 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005305
5306 AttributeCache ac = AttributeCache.instance();
5307 if (ac != null) {
5308 ac.updateConfiguration(mTempConfig);
5309 }
5310
5311 // Make sure all resources in our process are updated right now, so that anyone who is going
5312 // to retrieve resource values after we return will be sure to get the new ones. This is
5313 // especially important during boot, where the first config change needs to guarantee all
5314 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005315 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005316
5317 // We need another copy of global config because we're scheduling some calls instead of
5318 // running them in place. We need to be sure that object we send will be handled unchanged.
5319 final Configuration configCopy = new Configuration(mTempConfig);
5320 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005321 final Message msg = PooledLambda.obtainMessage(
5322 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5323 this, userId, configCopy);
5324 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005325 }
5326
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005327 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5328 for (int i = pidMap.size() - 1; i >= 0; i--) {
5329 final int pid = pidMap.keyAt(i);
5330 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005331 if (DEBUG_CONFIGURATION) {
5332 Slog.v(TAG_CONFIGURATION, "Update process config of "
5333 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005334 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005335 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005336 }
5337
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005338 final Message msg = PooledLambda.obtainMessage(
5339 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5340 mAmInternal, changes, initLocale);
5341 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005342
5343 // Override configuration of the default display duplicates global config, so we need to
5344 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005345 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005346 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005347
5348 return changes;
5349 }
5350
Riddle Hsua0022cd2019-09-09 21:12:41 +08005351 /** @see WindowSurfacePlacer#deferLayout */
5352 void deferWindowLayout() {
5353 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5354 // Reset the reasons at the first entrance because we only care about the changes in the
5355 // deferred scope.
5356 mLayoutReasons = 0;
5357 }
5358
5359 mWindowManager.mWindowPlacerLocked.deferLayout();
5360 }
5361
5362 /** @see WindowSurfacePlacer#continueLayout */
5363 void continueWindowLayout() {
5364 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5365 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5366 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5367 }
5368 }
5369
5370 /**
5371 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5372 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5373 * defer count is gone.
5374 */
5375 void addWindowLayoutReasons(@LayoutReason int reasons) {
5376 mLayoutReasons |= reasons;
5377 }
5378
Wale Ogunwalef6733932018-06-27 05:14:34 -07005379 private void updateEventDispatchingLocked(boolean booted) {
5380 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5381 }
5382
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005383 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5384 final ContentResolver resolver = mContext.getContentResolver();
5385 Settings.System.putConfigurationForUser(resolver, config, userId);
5386 }
5387
5388 private void sendLocaleToMountDaemonMsg(Locale l) {
5389 try {
5390 IBinder service = ServiceManager.getService("mount");
5391 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5392 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5393 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5394 } catch (RemoteException e) {
5395 Log.e(TAG, "Error storing locale for decryption UI", e);
5396 }
5397 }
5398
Alison Cichowlas3e340502018-08-07 17:15:01 -04005399 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5400 mStartActivitySources.remove(permissionToken);
5401 mExpiredStartAsCallerTokens.add(permissionToken);
5402 }
5403
5404 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5405 mExpiredStartAsCallerTokens.remove(permissionToken);
5406 }
5407
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005408 boolean isActivityStartsLoggingEnabled() {
5409 return mAmInternal.isActivityStartsLoggingEnabled();
5410 }
5411
Michal Karpinski8596ded2018-11-14 14:43:48 +00005412 boolean isBackgroundActivityStartsEnabled() {
5413 return mAmInternal.isBackgroundActivityStartsEnabled();
5414 }
5415
Wale Ogunwalef6733932018-06-27 05:14:34 -07005416 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005417 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005418 mWindowManager.enableScreenAfterBoot();
5419
5420 synchronized (mGlobalLock) {
5421 updateEventDispatchingLocked(booted);
5422 }
5423 }
5424
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005425 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5426 if (r == null || !r.hasProcess()) {
5427 return KEY_DISPATCHING_TIMEOUT_MS;
5428 }
5429 return getInputDispatchingTimeoutLocked(r.app);
5430 }
5431
5432 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005433 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005434 }
5435
Wale Ogunwalef6733932018-06-27 05:14:34 -07005436 /**
5437 * Decide based on the configuration whether we should show the ANR,
5438 * crash, etc dialogs. The idea is that if there is no affordance to
5439 * press the on-screen buttons, or the user experience would be more
5440 * greatly impacted than the crash itself, we shouldn't show the dialog.
5441 *
5442 * A thought: SystemUI might also want to get told about this, the Power
5443 * dialog / global actions also might want different behaviors.
5444 */
5445 private void updateShouldShowDialogsLocked(Configuration config) {
5446 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5447 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5448 && config.navigation == Configuration.NAVIGATION_NONAV);
5449 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5450 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5451 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5452 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5453 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5454 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5455 HIDE_ERROR_DIALOGS, 0) != 0;
5456 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5457 }
5458
5459 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5460 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5461 FONT_SCALE, 1.0f, userId);
5462
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005463 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005464 if (getGlobalConfiguration().fontScale == scaleFactor) {
5465 return;
5466 }
5467
5468 final Configuration configuration
5469 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5470 configuration.fontScale = scaleFactor;
5471 updatePersistentConfiguration(configuration, userId);
5472 }
5473 }
5474
5475 // Actually is sleeping or shutting down or whatever else in the future
5476 // is an inactive state.
5477 boolean isSleepingOrShuttingDownLocked() {
5478 return isSleepingLocked() || mShuttingDown;
5479 }
5480
5481 boolean isSleepingLocked() {
5482 return mSleeping;
5483 }
5484
Riddle Hsu16567132018-08-16 21:37:47 +08005485 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005486 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005487 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005488 if (task.isActivityTypeStandard()) {
5489 if (mCurAppTimeTracker != r.appTimeTracker) {
5490 // We are switching app tracking. Complete the current one.
5491 if (mCurAppTimeTracker != null) {
5492 mCurAppTimeTracker.stop();
5493 mH.obtainMessage(
5494 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005495 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005496 mCurAppTimeTracker = null;
5497 }
5498 if (r.appTimeTracker != null) {
5499 mCurAppTimeTracker = r.appTimeTracker;
5500 startTimeTrackingFocusedActivityLocked();
5501 }
5502 } else {
5503 startTimeTrackingFocusedActivityLocked();
5504 }
5505 } else {
5506 r.appTimeTracker = null;
5507 }
5508 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5509 // TODO: Probably not, because we don't want to resume voice on switching
5510 // back to this activity
5511 if (task.voiceInteractor != null) {
5512 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5513 } else {
5514 finishRunningVoiceLocked();
5515
5516 if (mLastResumedActivity != null) {
5517 final IVoiceInteractionSession session;
5518
Louis Changcdec0802019-11-11 11:45:07 +08005519 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005520 if (lastResumedActivityTask != null
5521 && lastResumedActivityTask.voiceSession != null) {
5522 session = lastResumedActivityTask.voiceSession;
5523 } else {
5524 session = mLastResumedActivity.voiceSession;
5525 }
5526
5527 if (session != null) {
5528 // We had been in a voice interaction session, but now focused has
5529 // move to something different. Just finish the session, we can't
5530 // return to it and retain the proper state and synchronization with
5531 // the voice interaction service.
5532 finishVoiceTask(session);
5533 }
5534 }
5535 }
5536
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005537 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5538 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005539 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005540 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5541
Wale Ogunwalef6733932018-06-27 05:14:34 -07005542 updateResumedAppTrace(r);
5543 mLastResumedActivity = r;
5544
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005545 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005546
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005547 if (prevTask == null || task != prevTask) {
5548 if (prevTask != null) {
5549 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5550 }
5551 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5552 }
5553
Wale Ogunwalef6733932018-06-27 05:14:34 -07005554 applyUpdateLockStateLocked(r);
5555 applyUpdateVrModeLocked(r);
5556
Jeff Changd136e772019-11-05 20:33:52 +08005557 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005558 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005559 r == null ? "NULL" : r.shortComponentName,
5560 reason);
5561 }
5562
5563 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5564 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005565 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005566 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005567 updateSleepIfNeededLocked();
5568 return token;
5569 }
5570 }
5571
5572 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005573 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005574 final boolean wasSleeping = mSleeping;
5575 boolean updateOomAdj = false;
5576
5577 if (!shouldSleep) {
5578 // If wasSleeping is true, we need to wake up activity manager state from when
5579 // we started sleeping. In either case, we need to apply the sleep tokens, which
5580 // will wake up stacks or put them to sleep as appropriate.
5581 if (wasSleeping) {
5582 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005583 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5584 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005585 startTimeTrackingFocusedActivityLocked();
5586 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005587 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005588 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5589 }
Louis Chang149d5c82019-12-30 09:47:39 +08005590 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005591 if (wasSleeping) {
5592 updateOomAdj = true;
5593 }
5594 } else if (!mSleeping && shouldSleep) {
5595 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005596 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5597 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005598 if (mCurAppTimeTracker != null) {
5599 mCurAppTimeTracker.stop();
5600 }
5601 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005602 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005603 mStackSupervisor.goingToSleepLocked();
5604 updateResumedAppTrace(null /* resumed */);
5605 updateOomAdj = true;
5606 }
5607 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005608 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005609 }
5610 }
5611
5612 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005613 mH.removeCallbacks(mUpdateOomAdjRunnable);
5614 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005615 }
5616
Wale Ogunwale53783742018-09-16 10:21:51 -07005617 void updateCpuStats() {
5618 mH.post(mAmInternal::updateCpuStats);
5619 }
5620
Hui Yu03d12402018-12-06 18:00:37 -08005621 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5622 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005623 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5624 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005625 mH.sendMessage(m);
5626 }
5627
Hui Yu03d12402018-12-06 18:00:37 -08005628 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005629 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005630 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005631 if (task != null) {
5632 final ActivityRecord rootActivity = task.getRootActivity();
5633 if (rootActivity != null) {
5634 taskRoot = rootActivity.mActivityComponent;
5635 }
5636 }
5637
Hui Yu03d12402018-12-06 18:00:37 -08005638 final Message m = PooledLambda.obtainMessage(
5639 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005640 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005641 mH.sendMessage(m);
5642 }
5643
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005644 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5645 String hostingType) {
5646 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005647 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5648 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005649 + activity.processName);
5650 }
5651 // Post message to start process to avoid possible deadlock of calling into AMS with the
5652 // ATMS lock held.
5653 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5654 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5655 isTop, hostingType, activity.intent.getComponent());
5656 mH.sendMessage(m);
5657 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005658 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005659 }
5660 }
5661
Wale Ogunwale53783742018-09-16 10:21:51 -07005662 void setBooting(boolean booting) {
5663 mAmInternal.setBooting(booting);
5664 }
5665
5666 boolean isBooting() {
5667 return mAmInternal.isBooting();
5668 }
5669
5670 void setBooted(boolean booted) {
5671 mAmInternal.setBooted(booted);
5672 }
5673
5674 boolean isBooted() {
5675 return mAmInternal.isBooted();
5676 }
5677
5678 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5679 mH.post(() -> {
5680 if (finishBooting) {
5681 mAmInternal.finishBooting();
5682 }
5683 if (enableScreen) {
5684 mInternal.enableScreenAfterBoot(isBooted());
5685 }
5686 });
5687 }
5688
5689 void setHeavyWeightProcess(ActivityRecord root) {
5690 mHeavyWeightProcess = root.app;
5691 final Message m = PooledLambda.obtainMessage(
5692 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005693 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005694 mH.sendMessage(m);
5695 }
5696
5697 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5698 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5699 return;
5700 }
5701
5702 mHeavyWeightProcess = null;
5703 final Message m = PooledLambda.obtainMessage(
5704 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5705 proc.mUserId);
5706 mH.sendMessage(m);
5707 }
5708
5709 private void cancelHeavyWeightProcessNotification(int userId) {
5710 final INotificationManager inm = NotificationManager.getService();
5711 if (inm == null) {
5712 return;
5713 }
5714 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005715 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005716 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5717 } catch (RuntimeException e) {
5718 Slog.w(TAG, "Error canceling notification for service", e);
5719 } catch (RemoteException e) {
5720 }
5721
5722 }
5723
5724 private void postHeavyWeightProcessNotification(
5725 WindowProcessController proc, Intent intent, int userId) {
5726 if (proc == null) {
5727 return;
5728 }
5729
5730 final INotificationManager inm = NotificationManager.getService();
5731 if (inm == null) {
5732 return;
5733 }
5734
5735 try {
5736 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5737 String text = mContext.getString(R.string.heavy_weight_notification,
5738 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5739 Notification notification =
5740 new Notification.Builder(context,
5741 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5742 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5743 .setWhen(0)
5744 .setOngoing(true)
5745 .setTicker(text)
5746 .setColor(mContext.getColor(
5747 com.android.internal.R.color.system_notification_accent_color))
5748 .setContentTitle(text)
5749 .setContentText(
5750 mContext.getText(R.string.heavy_weight_notification_detail))
5751 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5752 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5753 new UserHandle(userId)))
5754 .build();
5755 try {
5756 inm.enqueueNotificationWithTag("android", "android", null,
5757 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5758 } catch (RuntimeException e) {
5759 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5760 } catch (RemoteException e) {
5761 }
5762 } catch (PackageManager.NameNotFoundException e) {
5763 Slog.w(TAG, "Unable to create context for heavy notification", e);
5764 }
5765
5766 }
5767
Philip P. Moltmannee295092020-02-10 08:46:26 -08005768 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5769 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5770 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005771
5772 ActivityRecord activity = null;
5773 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5774 activity = ActivityRecord.isInStackLocked(token);
5775 if (activity == null) {
5776 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5777 return null;
5778 }
5779 if (activity.finishing) {
5780 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5781 return null;
5782 }
5783 }
5784
5785 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005786 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5787 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005788 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5789 if (noCreate) {
5790 return rec;
5791 }
5792 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5793 if (activity.pendingResults == null) {
5794 activity.pendingResults = new HashSet<>();
5795 }
5796 activity.pendingResults.add(rec.ref);
5797 }
5798 return rec;
5799 }
5800
Andrii Kulian52d255c2018-07-13 11:32:19 -07005801 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005802 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005803 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005804 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5805 mCurAppTimeTracker.start(resumedActivity.packageName);
5806 }
5807 }
5808
5809 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5810 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005811 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005812 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5813 }
5814 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005815 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005816 constructResumedTraceName(resumed.packageName), 0);
5817 }
5818 mTracedResumedActivity = resumed;
5819 }
5820
5821 private String constructResumedTraceName(String packageName) {
5822 return "focused app: " + packageName;
5823 }
5824
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005825 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005826 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005827 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005828 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005829 // mainStack is null during startup.
5830 if (mainStack != null) {
5831 if (changes != 0 && starting == null) {
5832 // If the configuration changed, and the caller is not already
5833 // in the process of starting an activity, then find the top
5834 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005835 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005836 }
5837
5838 if (starting != null) {
5839 kept = starting.ensureActivityConfiguration(changes,
5840 false /* preserveWindow */);
5841 // And we need to make sure at this point that all other activities
5842 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005843 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005844 !PRESERVE_WINDOWS);
5845 }
5846 }
5847
5848 return kept;
5849 }
5850
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005851 void scheduleAppGcsLocked() {
5852 mH.post(() -> mAmInternal.scheduleAppGcs());
5853 }
5854
Wale Ogunwale53783742018-09-16 10:21:51 -07005855 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5856 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5857 }
5858
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005859 /**
5860 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5861 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5862 * on demand.
5863 */
5864 IPackageManager getPackageManager() {
5865 return AppGlobals.getPackageManager();
5866 }
5867
5868 PackageManagerInternal getPackageManagerInternalLocked() {
5869 if (mPmInternal == null) {
5870 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5871 }
5872 return mPmInternal;
5873 }
5874
Darryl L Johnsona0982222020-02-18 18:21:51 -08005875 ComponentName getSysUiServiceComponentLocked() {
5876 if (mSysUiServiceComponent == null) {
5877 final PackageManagerInternal pm = getPackageManagerInternalLocked();
5878 mSysUiServiceComponent = pm.getSystemUiServiceComponent();
5879 }
5880 return mSysUiServiceComponent;
5881 }
5882
Hai Zhangf4da9be2019-05-01 13:46:06 +08005883 PermissionPolicyInternal getPermissionPolicyInternal() {
5884 if (mPermissionPolicyInternal == null) {
5885 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5886 }
5887 return mPermissionPolicyInternal;
5888 }
5889
Wale Ogunwale008163e2018-07-23 23:11:08 -07005890 AppWarnings getAppWarningsLocked() {
5891 return mAppWarnings;
5892 }
5893
Wale Ogunwale214f3482018-10-04 11:00:47 -07005894 Intent getHomeIntent() {
5895 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5896 intent.setComponent(mTopComponent);
5897 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5898 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5899 intent.addCategory(Intent.CATEGORY_HOME);
5900 }
5901 return intent;
5902 }
5903
Chilun2ef71f72018-11-16 17:57:15 +08005904 /**
5905 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5906 * activities.
5907 *
Chilun939b05c2020-02-19 14:50:59 +08005908 * @param preferredPackage Specify a preferred package name, otherwise use the package name
5909 * defined in config_secondaryHomePackage.
Chilun2ef71f72018-11-16 17:57:15 +08005910 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5911 */
5912 Intent getSecondaryHomeIntent(String preferredPackage) {
5913 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005914 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5915 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5916 if (preferredPackage == null || useSystemProvidedLauncher) {
Chilun939b05c2020-02-19 14:50:59 +08005917 // Using the package name stored in config if no preferred package name or forced.
5918 final String secondaryHomePackage = mContext.getResources().getString(
5919 com.android.internal.R.string.config_secondaryHomePackage);
5920 intent.setPackage(secondaryHomePackage);
Chilun2ef71f72018-11-16 17:57:15 +08005921 } else {
5922 intent.setPackage(preferredPackage);
5923 }
5924 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5925 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5926 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5927 }
5928 return intent;
5929 }
5930
Wale Ogunwale214f3482018-10-04 11:00:47 -07005931 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5932 if (info == null) return null;
5933 ApplicationInfo newInfo = new ApplicationInfo(info);
5934 newInfo.initForUser(userId);
5935 return newInfo;
5936 }
5937
Wale Ogunwale9c103022018-10-18 07:44:54 -07005938 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005939 if (uid == SYSTEM_UID) {
5940 // The system gets to run in any process. If there are multiple processes with the same
5941 // uid, just pick the first (this should never happen).
5942 final SparseArray<WindowProcessController> procs =
5943 mProcessNames.getMap().get(processName);
5944 if (procs == null) return null;
5945 final int procCount = procs.size();
5946 for (int i = 0; i < procCount; i++) {
5947 final int procUid = procs.keyAt(i);
5948 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5949 // Don't use an app process or different user process for system component.
5950 continue;
5951 }
5952 return procs.valueAt(i);
5953 }
5954 }
5955
5956 return mProcessNames.get(processName, uid);
5957 }
5958
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005959 WindowProcessController getProcessController(IApplicationThread thread) {
5960 if (thread == null) {
5961 return null;
5962 }
5963
5964 final IBinder threadBinder = thread.asBinder();
5965 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5966 for (int i = pmap.size()-1; i >= 0; i--) {
5967 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5968 for (int j = procs.size() - 1; j >= 0; j--) {
5969 final WindowProcessController proc = procs.valueAt(j);
5970 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5971 return proc;
5972 }
5973 }
5974 }
5975
5976 return null;
5977 }
5978
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005979 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005980 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005981 if (proc == null) return null;
5982 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5983 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005984 }
5985 return null;
5986 }
5987
Riddle Hsua0536432019-02-16 00:38:59 +08005988 int getUidState(int uid) {
5989 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005990 }
5991
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005992 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005993 // A uid is considered to be foreground if it has a visible non-toast window.
5994 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005995 }
5996
Ricky Wai96f5c352019-04-10 18:40:17 +01005997 boolean isDeviceOwner(int uid) {
5998 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005999 }
6000
Ricky Wai96f5c352019-04-10 18:40:17 +01006001 void setDeviceOwnerUid(int uid) {
6002 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006003 }
6004
Wale Ogunwale9de19442018-10-18 19:05:03 -07006005 /**
6006 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6007 * the whitelist
6008 */
6009 String getPendingTempWhitelistTagForUidLocked(int uid) {
6010 return mPendingTempWhitelist.get(uid);
6011 }
6012
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006013 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6014 if (true || Build.IS_USER) {
6015 return;
6016 }
6017
6018 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6019 StrictMode.allowThreadDiskWrites();
6020 try {
6021 File tracesDir = new File("/data/anr");
6022 File tracesFile = null;
6023 try {
6024 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6025
6026 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006027 String timeString =
6028 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6029 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006030 sb.append(": ");
6031 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6032 sb.append(" since ");
6033 sb.append(msg);
6034 FileOutputStream fos = new FileOutputStream(tracesFile);
6035 fos.write(sb.toString().getBytes());
6036 if (app == null) {
6037 fos.write("\n*** No application process!".getBytes());
6038 }
6039 fos.close();
6040 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6041 } catch (IOException e) {
6042 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6043 return;
6044 }
6045
6046 if (app != null && app.getPid() > 0) {
6047 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6048 firstPids.add(app.getPid());
6049 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6050 }
6051
6052 File lastTracesFile = null;
6053 File curTracesFile = null;
6054 for (int i=9; i>=0; i--) {
6055 String name = String.format(Locale.US, "slow%02d.txt", i);
6056 curTracesFile = new File(tracesDir, name);
6057 if (curTracesFile.exists()) {
6058 if (lastTracesFile != null) {
6059 curTracesFile.renameTo(lastTracesFile);
6060 } else {
6061 curTracesFile.delete();
6062 }
6063 }
6064 lastTracesFile = curTracesFile;
6065 }
6066 tracesFile.renameTo(curTracesFile);
6067 } finally {
6068 StrictMode.setThreadPolicy(oldPolicy);
6069 }
6070 }
6071
Michal Karpinskida34cd42019-04-02 19:46:52 +01006072 boolean isAssociatedCompanionApp(int userId, int uid) {
6073 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6074 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006075 return false;
6076 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006077 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006078 }
6079
Issei Suzuki734bc942019-06-05 13:59:52 +02006080 void notifySingleTaskDisplayEmpty(int displayId) {
6081 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6082 }
6083
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006084 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006085 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006086
6087
Wale Ogunwale98875612018-10-12 07:53:02 -07006088 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6089 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006090
Riddle Hsud93a6c42018-11-29 21:50:06 +08006091 H(Looper looper) {
6092 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006093 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006094
6095 @Override
6096 public void handleMessage(Message msg) {
6097 switch (msg.what) {
6098 case REPORT_TIME_TRACKER_MSG: {
6099 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6100 tracker.deliverResult(mContext);
6101 } break;
6102 }
6103 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006104 }
6105
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006106 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006107 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006108
6109 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006110 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006111 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006112
6113 @Override
6114 public void handleMessage(Message msg) {
6115 switch (msg.what) {
6116 case DISMISS_DIALOG_UI_MSG: {
6117 final Dialog d = (Dialog) msg.obj;
6118 d.dismiss();
6119 break;
6120 }
6121 }
6122 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006123 }
6124
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006125 final class LocalService extends ActivityTaskManagerInternal {
6126 @Override
6127 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006128 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006129 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006130 }
6131
6132 @Override
6133 public ComponentName getHomeActivityForUser(int userId) {
6134 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006135 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006136 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006137 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006138 }
6139 }
6140
6141 @Override
6142 public void onLocalVoiceInteractionStarted(IBinder activity,
6143 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6144 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006145 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006146 }
6147 }
6148
6149 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006150 public void notifySingleTaskDisplayDrawn(int displayId) {
6151 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6152 }
6153
6154 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006155 public void notifyAppTransitionFinished() {
6156 synchronized (mGlobalLock) {
6157 mStackSupervisor.notifyAppTransitionDone();
6158 }
6159 }
6160
6161 @Override
6162 public void notifyAppTransitionCancelled() {
6163 synchronized (mGlobalLock) {
6164 mStackSupervisor.notifyAppTransitionDone();
6165 }
6166 }
6167
6168 @Override
6169 public List<IBinder> getTopVisibleActivities() {
6170 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006171 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006172 }
6173 }
6174
6175 @Override
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00006176 public boolean hasResumedActivity(int uid) {
6177 synchronized (mGlobalLock) {
6178 final ArraySet<WindowProcessController> processes = mProcessMap.getProcesses(uid);
6179 for (int i = 0, n = processes.size(); i < n; i++) {
6180 final WindowProcessController process = processes.valueAt(i);
6181 if (process.hasResumedActivity()) {
6182 return true;
6183 }
6184 }
6185 }
6186 return false;
6187 }
6188
6189 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006190 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6191 int userId, Intent[] intents, Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006192 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006193 final String[] resolvedTypes = new String[intents.length];
6194
6195 // UID of the package on user userId.
6196 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6197 // packageUid may not be initialized.
6198 int packageUid = 0;
6199 final long ident = Binder.clearCallingIdentity();
6200
6201 try {
6202 for (int i = 0; i < intents.length; i++) {
6203 resolvedTypes[i] =
6204 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6205 }
6206
6207 packageUid = AppGlobals.getPackageManager().getPackageUid(
6208 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6209 } catch (RemoteException e) {
6210 // Shouldn't happen.
6211 } finally {
6212 Binder.restoreCallingIdentity(ident);
6213 }
6214
Riddle Hsu591bf612019-02-14 17:55:31 +08006215 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006216 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006217 intents, resolvedTypes, null /* resultTo */,
6218 SafeActivityOptions.fromBundle(bOptions), userId,
6219 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6220 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006221 }
6222
6223 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006224 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006225 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6226 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6227 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006228 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006229 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006230 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006231 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006232 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6233 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006234 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006235 }
6236 }
6237
6238 @Override
6239 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006240 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6241 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6242 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6243 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006244 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006245 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006246 synchronized (mGlobalLock) {
6247 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006248 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6249 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6250 reason, validateIncomingUser, originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006251 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006252 }
6253 }
6254
6255 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006256 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006257 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6258 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006259 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006260 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006261 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006262 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006263 false /*validateIncomingUser*/);
6264 }
6265
6266 @Override
lumark588a3e82018-07-20 18:53:54 +08006267 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006268 synchronized (mGlobalLock) {
6269
6270 // We might change the visibilities here, so prepare an empty app transition which
6271 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006272 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006273 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006274 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006275 return;
6276 }
Louis Chang677921f2019-12-06 16:44:24 +08006277 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006278 final boolean wasTransitionSet =
6279 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006280 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006281 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006282 }
Louis Chang149d5c82019-12-30 09:47:39 +08006283 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006284
6285 // If there was a transition set already we don't want to interfere with it as we
6286 // might be starting it too early.
6287 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006288 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006289 }
6290 }
6291 if (callback != null) {
6292 callback.run();
6293 }
6294 }
6295
6296 @Override
6297 public void notifyKeyguardTrustedChanged() {
6298 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006299 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006300 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006301 }
6302 }
6303 }
6304
6305 /**
6306 * Called after virtual display Id is updated by
6307 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6308 * {@param vrVr2dDisplayId}.
6309 */
6310 @Override
6311 public void setVr2dDisplayId(int vr2dDisplayId) {
6312 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6313 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006314 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006315 }
6316 }
6317
6318 @Override
6319 public void setFocusedActivity(IBinder token) {
6320 synchronized (mGlobalLock) {
6321 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6322 if (r == null) {
6323 throw new IllegalArgumentException(
6324 "setFocusedActivity: No activity record matching token=" + token);
6325 }
Louis Chang19443452018-10-09 12:10:21 +08006326 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006327 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006328 }
6329 }
6330 }
6331
6332 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006333 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006334 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006335 }
6336
6337 @Override
6338 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006339 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006340 }
6341
6342 @Override
6343 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006344 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006345 }
6346
6347 @Override
6348 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6349 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6350 }
6351
6352 @Override
6353 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006354 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006355 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006356
6357 @Override
6358 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6359 synchronized (mGlobalLock) {
6360 mActiveVoiceInteractionServiceComponent = component;
6361 }
6362 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006363
6364 @Override
6365 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6366 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6367 return;
6368 }
6369 synchronized (mGlobalLock) {
6370 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6371 if (types == null) {
6372 if (uid < 0) {
6373 return;
6374 }
6375 types = new ArrayMap<>();
6376 mAllowAppSwitchUids.put(userId, types);
6377 }
6378 if (uid < 0) {
6379 types.remove(type);
6380 } else {
6381 types.put(type, uid);
6382 }
6383 }
6384 }
6385
6386 @Override
6387 public void onUserStopped(int userId) {
6388 synchronized (mGlobalLock) {
6389 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6390 mAllowAppSwitchUids.remove(userId);
6391 }
6392 }
6393
6394 @Override
6395 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6396 synchronized (mGlobalLock) {
6397 return ActivityTaskManagerService.this.isGetTasksAllowed(
6398 caller, callingPid, callingUid);
6399 }
6400 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006401
Riddle Hsua0536432019-02-16 00:38:59 +08006402 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006403 @Override
6404 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006405 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006406 mProcessNames.put(proc.mName, proc.mUid, proc);
6407 }
6408 }
6409
Riddle Hsua0536432019-02-16 00:38:59 +08006410 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006411 @Override
6412 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006413 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006414 mProcessNames.remove(name, uid);
6415 }
6416 }
6417
Riddle Hsua0536432019-02-16 00:38:59 +08006418 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006419 @Override
6420 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006421 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006422 if (proc == mHomeProcess) {
6423 mHomeProcess = null;
6424 }
6425 if (proc == mPreviousProcess) {
6426 mPreviousProcess = null;
6427 }
6428 }
6429 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006430
Riddle Hsua0536432019-02-16 00:38:59 +08006431 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006432 @Override
6433 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006434 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006435 return mTopProcessState;
6436 }
6437 }
6438
Riddle Hsua0536432019-02-16 00:38:59 +08006439 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006440 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006441 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006442 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006443 return proc == mHeavyWeightProcess;
6444 }
6445 }
6446
Riddle Hsua0536432019-02-16 00:38:59 +08006447 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006448 @Override
6449 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006450 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006451 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6452 }
6453 }
6454
6455 @Override
6456 public void finishHeavyWeightApp() {
6457 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006458 if (mHeavyWeightProcess != null) {
6459 mHeavyWeightProcess.finishActivities();
6460 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006461 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6462 mHeavyWeightProcess);
6463 }
6464 }
6465
Riddle Hsua0536432019-02-16 00:38:59 +08006466 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006467 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006468 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006469 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006470 return isSleepingLocked();
6471 }
6472 }
6473
6474 @Override
6475 public boolean isShuttingDown() {
6476 synchronized (mGlobalLock) {
6477 return mShuttingDown;
6478 }
6479 }
6480
6481 @Override
6482 public boolean shuttingDown(boolean booted, int timeout) {
6483 synchronized (mGlobalLock) {
6484 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006485 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006486 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006487 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006488 return mStackSupervisor.shutdownLocked(timeout);
6489 }
6490 }
6491
6492 @Override
6493 public void enableScreenAfterBoot(boolean booted) {
6494 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006495 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006496 mWindowManager.enableScreenAfterBoot();
6497 updateEventDispatchingLocked(booted);
6498 }
6499 }
6500
6501 @Override
6502 public boolean showStrictModeViolationDialog() {
6503 synchronized (mGlobalLock) {
6504 return mShowDialogs && !mSleeping && !mShuttingDown;
6505 }
6506 }
6507
6508 @Override
6509 public void showSystemReadyErrorDialogsIfNeeded() {
6510 synchronized (mGlobalLock) {
6511 try {
6512 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6513 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6514 + " data partition or your device will be unstable.");
6515 mUiHandler.post(() -> {
6516 if (mShowDialogs) {
6517 AlertDialog d = new BaseErrorDialog(mUiContext);
6518 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6519 d.setCancelable(false);
6520 d.setTitle(mUiContext.getText(R.string.android_system_label));
6521 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6522 d.setButton(DialogInterface.BUTTON_POSITIVE,
6523 mUiContext.getText(R.string.ok),
6524 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6525 d.show();
6526 }
6527 });
6528 }
6529 } catch (RemoteException e) {
6530 }
6531
6532 if (!Build.isBuildConsistent()) {
6533 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6534 mUiHandler.post(() -> {
6535 if (mShowDialogs) {
6536 AlertDialog d = new BaseErrorDialog(mUiContext);
6537 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6538 d.setCancelable(false);
6539 d.setTitle(mUiContext.getText(R.string.android_system_label));
6540 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6541 d.setButton(DialogInterface.BUTTON_POSITIVE,
6542 mUiContext.getText(R.string.ok),
6543 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6544 d.show();
6545 }
6546 });
6547 }
6548 }
6549 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006550
6551 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006552 public void onProcessMapped(int pid, WindowProcessController proc) {
6553 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006554 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006555 }
6556 }
6557
6558 @Override
6559 public void onProcessUnMapped(int pid) {
6560 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006561 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006562 }
6563 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006564
6565 @Override
6566 public void onPackageDataCleared(String name) {
6567 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006568 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006569 mAppWarnings.onPackageDataCleared(name);
6570 }
6571 }
6572
6573 @Override
6574 public void onPackageUninstalled(String name) {
6575 synchronized (mGlobalLock) {
6576 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006577 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006578 }
6579 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006580
6581 @Override
6582 public void onPackageAdded(String name, boolean replacing) {
6583 synchronized (mGlobalLock) {
6584 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6585 }
6586 }
6587
6588 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006589 public void onPackageReplaced(ApplicationInfo aInfo) {
6590 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006591 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006592 }
6593 }
6594
6595 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006596 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6597 synchronized (mGlobalLock) {
6598 return compatibilityInfoForPackageLocked(ai);
6599 }
6600 }
6601
Yunfan Chen75157d72018-07-27 14:47:21 +09006602 /**
6603 * Set the corresponding display information for the process global configuration. To be
6604 * called when we need to show IME on a different display.
6605 *
6606 * @param pid The process id associated with the IME window.
6607 * @param displayId The ID of the display showing the IME.
6608 */
6609 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006610 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006611 // Don't update process-level configuration for Multi-Client IME process since other
6612 // IMEs on other displays will also receive this configuration change due to IME
6613 // services use the same application config/context.
6614 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006615
Yunfan Chen75157d72018-07-27 14:47:21 +09006616 if (pid == MY_PID || pid < 0) {
6617 if (DEBUG_CONFIGURATION) {
6618 Slog.w(TAG,
6619 "Trying to update display configuration for system/invalid process.");
6620 }
6621 return;
6622 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006623 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006624 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006625 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006626 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006627 // Call might come when display is not yet added or has been removed.
6628 if (DEBUG_CONFIGURATION) {
6629 Slog.w(TAG, "Trying to update display configuration for non-existing "
6630 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006631 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006632 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006633 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006634 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006635 if (process == null) {
6636 if (DEBUG_CONFIGURATION) {
6637 Slog.w(TAG, "Trying to update display configuration for invalid "
6638 + "process, pid=" + pid);
6639 }
6640 return;
6641 }
lumarkddc77fb2019-06-27 22:22:23 +08006642 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006643 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006644 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006645 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006646
6647 @Override
6648 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006649 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006650 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006651 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006652 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006653 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006654 }
6655 }
6656 }
6657
6658 @Override
6659 public void clearPendingResultForActivity(IBinder activityToken,
6660 WeakReference<PendingIntentRecord> pir) {
6661 synchronized (mGlobalLock) {
6662 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6663 if (r != null && r.pendingResults != null) {
6664 r.pendingResults.remove(pir);
6665 }
6666 }
6667 }
6668
6669 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006670 public ActivityTokens getTopActivityForTask(int taskId) {
6671 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006672 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006673 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006674 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6675 + " Requested task not found");
6676 return null;
6677 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006678 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006679 if (activity == null) {
6680 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6681 + " Requested activity not found");
6682 return null;
6683 }
6684 if (!activity.attachedToProcess()) {
6685 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6686 + activity);
6687 return null;
6688 }
6689 return new ActivityTokens(activity.appToken, activity.assistToken,
6690 activity.app.getThread());
6691 }
6692 }
6693
6694 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006695 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006696 @Nullable String featureId, int callingUid, int userId, IBinder token,
6697 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6698 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006699 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006700 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6701 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006702 }
6703 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006704
6705 @Override
6706 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6707 synchronized (mGlobalLock) {
6708 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6709 if (r == null) {
6710 return null;
6711 }
6712 if (r.mServiceConnectionsHolder == null) {
6713 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6714 ActivityTaskManagerService.this, r);
6715 }
6716
6717 return r.mServiceConnectionsHolder;
6718 }
6719 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006720
6721 @Override
6722 public Intent getHomeIntent() {
6723 synchronized (mGlobalLock) {
6724 return ActivityTaskManagerService.this.getHomeIntent();
6725 }
6726 }
6727
6728 @Override
6729 public boolean startHomeActivity(int userId, String reason) {
6730 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006731 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006732 }
6733 }
6734
6735 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006736 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006737 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006738 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006739 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006740 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006741 }
Chilun8b1f1be2019-03-13 17:14:36 +08006742 }
6743
6744 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006745 public boolean startHomeOnAllDisplays(int userId, String reason) {
6746 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006747 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006748 }
6749 }
6750
Riddle Hsua0536432019-02-16 00:38:59 +08006751 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006752 @Override
6753 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006754 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006755 if (mFactoryTest == FACTORY_TEST_OFF) {
6756 return false;
6757 }
6758 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6759 && wpc.mName.equals(mTopComponent.getPackageName())) {
6760 return true;
6761 }
6762 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6763 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6764 }
6765 }
6766
6767 @Override
6768 public void updateTopComponentForFactoryTest() {
6769 synchronized (mGlobalLock) {
6770 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6771 return;
6772 }
6773 final ResolveInfo ri = mContext.getPackageManager()
6774 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6775 final CharSequence errorMsg;
6776 if (ri != null) {
6777 final ActivityInfo ai = ri.activityInfo;
6778 final ApplicationInfo app = ai.applicationInfo;
6779 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6780 mTopAction = Intent.ACTION_FACTORY_TEST;
6781 mTopData = null;
6782 mTopComponent = new ComponentName(app.packageName, ai.name);
6783 errorMsg = null;
6784 } else {
6785 errorMsg = mContext.getResources().getText(
6786 com.android.internal.R.string.factorytest_not_system);
6787 }
6788 } else {
6789 errorMsg = mContext.getResources().getText(
6790 com.android.internal.R.string.factorytest_no_action);
6791 }
6792 if (errorMsg == null) {
6793 return;
6794 }
6795
6796 mTopAction = null;
6797 mTopData = null;
6798 mTopComponent = null;
6799 mUiHandler.post(() -> {
6800 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6801 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006802 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006803 });
6804 }
6805 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806
Riddle Hsua0536432019-02-16 00:38:59 +08006807 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006808 @Override
6809 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6810 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006811 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006812 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006813 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006814
6815 wpc.clearRecentTasks();
6816 wpc.clearActivities();
6817
6818 if (wpc.isInstrumenting()) {
6819 finishInstrumentationCallback.run();
6820 }
6821
Jorim Jaggid0752812018-10-16 16:07:20 +02006822 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006823 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006824 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006825 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006826 // If there was nothing to resume, and we are not already restarting
6827 // this process, but there is a visible activity that is hosted by the
6828 // process...then make sure all visible activities are running, taking
6829 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006830 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006831 !PRESERVE_WINDOWS);
6832 }
6833 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006834 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006835 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006836 }
6837 }
6838 }
6839
6840 @Override
6841 public void closeSystemDialogs(String reason) {
6842 enforceNotIsolatedCaller("closeSystemDialogs");
6843
6844 final int pid = Binder.getCallingPid();
6845 final int uid = Binder.getCallingUid();
6846 final long origId = Binder.clearCallingIdentity();
6847 try {
6848 synchronized (mGlobalLock) {
6849 // Only allow this from foreground processes, so that background
6850 // applications can't abuse it to prevent system UI from being shown.
6851 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006852 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006853 if (!proc.isPerceptible()) {
6854 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6855 + " from background process " + proc);
6856 return;
6857 }
6858 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006859 mWindowManager.closeSystemDialogs(reason);
6860
Louis Chang149d5c82019-12-30 09:47:39 +08006861 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006862 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006863 // Call into AM outside the synchronized block.
6864 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006865 } finally {
6866 Binder.restoreCallingIdentity(origId);
6867 }
6868 }
6869
6870 @Override
6871 public void cleanupDisabledPackageComponents(
6872 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6873 synchronized (mGlobalLock) {
6874 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006875 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006876 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006877 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006878 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 }
6880
6881 // Clean-up disabled tasks
6882 getRecentTasks().cleanupDisabledPackageTasksLocked(
6883 packageName, disabledClasses, userId);
6884 }
6885 }
6886
6887 @Override
6888 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6889 int userId) {
6890 synchronized (mGlobalLock) {
6891
6892 boolean didSomething =
6893 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006894 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006895 null, doit, evenPersistent, userId);
6896 return didSomething;
6897 }
6898 }
6899
6900 @Override
6901 public void resumeTopActivities(boolean scheduleIdle) {
6902 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006903 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006904 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006905 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006906 }
6907 }
6908 }
6909
Riddle Hsua0536432019-02-16 00:38:59 +08006910 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006911 @Override
6912 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006913 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006914 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6915 }
6916 }
6917
Riddle Hsua0536432019-02-16 00:38:59 +08006918 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006919 @Override
6920 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006921 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006922 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6923 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6924 }
6925 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006926 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006927 } finally {
6928 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6929 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006930 }
6931 }
6932
6933 @Override
6934 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6935 try {
6936 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6937 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6938 }
6939 } catch (RemoteException ex) {
6940 throw new SecurityException("Fail to check is caller a privileged app", ex);
6941 }
6942
6943 synchronized (mGlobalLock) {
6944 final long ident = Binder.clearCallingIdentity();
6945 try {
6946 if (mAmInternal.shouldConfirmCredentials(userId)) {
6947 if (mKeyguardController.isKeyguardLocked()) {
6948 // Showing launcher to avoid user entering credential twice.
6949 startHomeActivity(currentUserId, "notifyLockedProfile");
6950 }
Louis Chang149d5c82019-12-30 09:47:39 +08006951 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006952 }
6953 } finally {
6954 Binder.restoreCallingIdentity(ident);
6955 }
6956 }
6957 }
6958
6959 @Override
6960 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6961 mAmInternal.enforceCallingPermission(
6962 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6963
6964 synchronized (mGlobalLock) {
6965 final long ident = Binder.clearCallingIdentity();
6966 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006967 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6968 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006969 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006970 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6971 UserHandle.CURRENT);
6972 } finally {
6973 Binder.restoreCallingIdentity(ident);
6974 }
6975 }
6976 }
6977
6978 @Override
6979 public void writeActivitiesToProto(ProtoOutputStream proto) {
6980 synchronized (mGlobalLock) {
6981 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006982 mRootWindowContainer.dumpDebug(
6983 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006984 }
6985 }
6986
6987 @Override
6988 public void saveANRState(String reason) {
6989 synchronized (mGlobalLock) {
6990 final StringWriter sw = new StringWriter();
6991 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6992 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6993 if (reason != null) {
6994 pw.println(" Reason: " + reason);
6995 }
6996 pw.println();
6997 getActivityStartController().dump(pw, " ", null);
6998 pw.println();
6999 pw.println("-------------------------------------------------------------------------------");
7000 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7001 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7002 "" /* header */);
7003 pw.println();
7004 pw.close();
7005
7006 mLastANRState = sw.toString();
7007 }
7008 }
7009
7010 @Override
7011 public void clearSavedANRState() {
7012 synchronized (mGlobalLock) {
7013 mLastANRState = null;
7014 }
7015 }
7016
7017 @Override
7018 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7019 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7020 synchronized (mGlobalLock) {
7021 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7022 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7023 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7024 dumpLastANRLocked(pw);
7025 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7026 dumpLastANRTracesLocked(pw);
7027 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7028 dumpActivityStarterLocked(pw, dumpPackage);
7029 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7030 dumpActivityContainersLocked(pw);
7031 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7032 if (getRecentTasks() != null) {
7033 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7034 }
7035 }
7036 }
7037 }
7038
7039 @Override
7040 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7041 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7042 int wakefulness) {
7043 synchronized (mGlobalLock) {
7044 if (mHomeProcess != null && (dumpPackage == null
7045 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7046 if (needSep) {
7047 pw.println();
7048 needSep = false;
7049 }
7050 pw.println(" mHomeProcess: " + mHomeProcess);
7051 }
7052 if (mPreviousProcess != null && (dumpPackage == null
7053 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7054 if (needSep) {
7055 pw.println();
7056 needSep = false;
7057 }
7058 pw.println(" mPreviousProcess: " + mPreviousProcess);
7059 }
7060 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7061 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7062 StringBuilder sb = new StringBuilder(128);
7063 sb.append(" mPreviousProcessVisibleTime: ");
7064 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7065 pw.println(sb);
7066 }
7067 if (mHeavyWeightProcess != null && (dumpPackage == null
7068 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7069 if (needSep) {
7070 pw.println();
7071 needSep = false;
7072 }
7073 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7074 }
7075 if (dumpPackage == null) {
7076 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007077 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007078 }
7079 if (dumpAll) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007080 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7081 if (dumpPackage == null && topFocusedStack != null) {
7082 pw.println(" mConfigWillChange: " + topFocusedStack.mConfigWillChange);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007083 }
7084 if (mCompatModePackages.getPackages().size() > 0) {
7085 boolean printed = false;
7086 for (Map.Entry<String, Integer> entry
7087 : mCompatModePackages.getPackages().entrySet()) {
7088 String pkg = entry.getKey();
7089 int mode = entry.getValue();
7090 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7091 continue;
7092 }
7093 if (!printed) {
7094 pw.println(" mScreenCompatPackages:");
7095 printed = true;
7096 }
7097 pw.println(" " + pkg + ": " + mode);
7098 }
7099 }
7100 }
7101
7102 if (dumpPackage == null) {
7103 pw.println(" mWakefulness="
7104 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007105 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007106 if (mRunningVoice != null) {
7107 pw.println(" mRunningVoice=" + mRunningVoice);
7108 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7109 }
7110 pw.println(" mSleeping=" + mSleeping);
7111 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7112 pw.println(" mVrController=" + mVrController);
7113 }
7114 if (mCurAppTimeTracker != null) {
7115 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7116 }
7117 if (mAllowAppSwitchUids.size() > 0) {
7118 boolean printed = false;
7119 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7120 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7121 for (int j = 0; j < types.size(); j++) {
7122 if (dumpPackage == null ||
7123 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7124 if (needSep) {
7125 pw.println();
7126 needSep = false;
7127 }
7128 if (!printed) {
7129 pw.println(" mAllowAppSwitchUids:");
7130 printed = true;
7131 }
7132 pw.print(" User ");
7133 pw.print(mAllowAppSwitchUids.keyAt(i));
7134 pw.print(": Type ");
7135 pw.print(types.keyAt(j));
7136 pw.print(" = ");
7137 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7138 pw.println();
7139 }
7140 }
7141 }
7142 }
7143 if (dumpPackage == null) {
7144 if (mController != null) {
7145 pw.println(" mController=" + mController
7146 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7147 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007148 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7149 pw.println(" mLaunchingActivityWakeLock="
7150 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007151 }
7152
7153 return needSep;
7154 }
7155 }
7156
7157 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007158 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7159 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007160 synchronized (mGlobalLock) {
7161 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007162 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007163 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7164 if (topFocusedStack != null) {
7165 proto.write(CONFIG_WILL_CHANGE, topFocusedStack.mConfigWillChange);
7166 }
sanryhuang498e77e2018-12-06 14:57:01 +08007167 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7168 if (mRunningVoice != null) {
7169 final long vrToken = proto.start(
7170 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7171 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7172 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007173 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007174 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7175 proto.end(vrToken);
7176 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007177 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007178 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007179 if (mController != null) {
7180 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007181 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7182 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007183 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7184 proto.end(token);
7185 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007186 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7187 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007188 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007189 }
7190
7191 if (mHomeProcess != null && (dumpPackage == null
7192 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007193 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007194 }
7195
7196 if (mPreviousProcess != null && (dumpPackage == null
7197 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007198 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007199 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7200 }
7201
7202 if (mHeavyWeightProcess != null && (dumpPackage == null
7203 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007204 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007205 }
7206
7207 for (Map.Entry<String, Integer> entry
7208 : mCompatModePackages.getPackages().entrySet()) {
7209 String pkg = entry.getKey();
7210 int mode = entry.getValue();
7211 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7212 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7213 proto.write(PACKAGE, pkg);
7214 proto.write(MODE, mode);
7215 proto.end(compatToken);
7216 }
7217 }
7218
7219 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007220 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007221 }
7222
7223 }
7224 }
7225
7226 @Override
7227 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7228 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7229 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007230 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7231 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007232 }
7233
7234 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007235 public void dumpForOom(PrintWriter pw) {
7236 synchronized (mGlobalLock) {
7237 pw.println(" mHomeProcess: " + mHomeProcess);
7238 pw.println(" mPreviousProcess: " + mPreviousProcess);
7239 if (mHeavyWeightProcess != null) {
7240 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7241 }
7242 }
7243 }
7244
7245 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007246 public boolean canGcNow() {
7247 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007248 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007249 }
7250 }
7251
Riddle Hsua0536432019-02-16 00:38:59 +08007252 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007253 @Override
7254 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007255 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007256 if (mRootWindowContainer == null) {
7257 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007258 // oomadj after AMS created.
7259 return null;
7260 }
Louis Chang149d5c82019-12-30 09:47:39 +08007261 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007262 return top != null ? top.app : null;
7263 }
7264 }
7265
Riddle Hsua0536432019-02-16 00:38:59 +08007266 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007267 @Override
7268 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007269 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007270 if (mRootWindowContainer != null) {
7271 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007272 }
7273 }
7274 }
7275
7276 @Override
7277 public void scheduleDestroyAllActivities(String reason) {
7278 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007279 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007280 }
7281 }
7282
7283 @Override
7284 public void removeUser(int userId) {
7285 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007286 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007287 }
7288 }
7289
7290 @Override
7291 public boolean switchUser(int userId, UserState userState) {
7292 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007293 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007294 }
7295 }
7296
7297 @Override
7298 public void onHandleAppCrash(WindowProcessController wpc) {
7299 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007300 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007301 }
7302 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007303
7304 @Override
7305 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7306 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007307 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007308 }
7309 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007310
Riddle Hsua0536432019-02-16 00:38:59 +08007311 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007312 @Override
7313 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007314 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007315 }
7316
Riddle Hsua0536432019-02-16 00:38:59 +08007317 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007318 @Override
7319 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007320 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007321 }
7322
Riddle Hsua0536432019-02-16 00:38:59 +08007323 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007324 @Override
7325 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007326 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007327 }
7328
Riddle Hsua0536432019-02-16 00:38:59 +08007329 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007330 @Override
7331 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007332 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007333 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007334
7335 @Override
7336 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007337 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007338 mPendingTempWhitelist.put(uid, tag);
7339 }
7340 }
7341
7342 @Override
7343 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007344 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007345 mPendingTempWhitelist.remove(uid);
7346 }
7347 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007348
7349 @Override
7350 public boolean handleAppCrashInActivityController(String processName, int pid,
7351 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7352 Runnable killCrashingAppCallback) {
7353 synchronized (mGlobalLock) {
7354 if (mController == null) {
7355 return false;
7356 }
7357
7358 try {
7359 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7360 stackTrace)) {
7361 killCrashingAppCallback.run();
7362 return true;
7363 }
7364 } catch (RemoteException e) {
7365 mController = null;
7366 Watchdog.getInstance().setActivityController(null);
7367 }
7368 return false;
7369 }
7370 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007371
7372 @Override
7373 public void removeRecentTasksByPackageName(String packageName, int userId) {
7374 synchronized (mGlobalLock) {
7375 mRecentTasks.removeTasksByPackageName(packageName, userId);
7376 }
7377 }
7378
7379 @Override
7380 public void cleanupRecentTasksForUser(int userId) {
7381 synchronized (mGlobalLock) {
7382 mRecentTasks.cleanupLocked(userId);
7383 }
7384 }
7385
7386 @Override
7387 public void loadRecentTasksForUser(int userId) {
7388 synchronized (mGlobalLock) {
7389 mRecentTasks.loadUserRecentsLocked(userId);
7390 }
7391 }
7392
7393 @Override
7394 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7395 synchronized (mGlobalLock) {
7396 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7397 }
7398 }
7399
7400 @Override
7401 public void flushRecentTasks() {
7402 mRecentTasks.flush();
7403 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007404
7405 @Override
7406 public WindowProcessController getHomeProcess() {
7407 synchronized (mGlobalLock) {
7408 return mHomeProcess;
7409 }
7410 }
7411
7412 @Override
7413 public WindowProcessController getPreviousProcess() {
7414 synchronized (mGlobalLock) {
7415 return mPreviousProcess;
7416 }
7417 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007418
7419 @Override
7420 public void clearLockedTasks(String reason) {
7421 synchronized (mGlobalLock) {
7422 getLockTaskController().clearLockedTasks(reason);
7423 }
7424 }
7425
7426 @Override
7427 public void updateUserConfiguration() {
7428 synchronized (mGlobalLock) {
7429 final Configuration configuration = new Configuration(getGlobalConfiguration());
7430 final int currentUserId = mAmInternal.getCurrentUserId();
7431 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7432 configuration, currentUserId, Settings.System.canWrite(mContext));
7433 updateConfigurationLocked(configuration, null /* starting */,
7434 false /* initLocale */, false /* persistent */, currentUserId,
7435 false /* deferResume */);
7436 }
7437 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007438
7439 @Override
7440 public boolean canShowErrorDialogs() {
7441 synchronized (mGlobalLock) {
7442 return mShowDialogs && !mSleeping && !mShuttingDown
7443 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7444 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7445 mAmInternal.getCurrentUserId())
7446 && !(UserManager.isDeviceInDemoMode(mContext)
7447 && mAmInternal.getCurrentUser().isDemo());
7448 }
7449 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007450
7451 @Override
7452 public void setProfileApp(String profileApp) {
7453 synchronized (mGlobalLock) {
7454 mProfileApp = profileApp;
7455 }
7456 }
7457
7458 @Override
7459 public void setProfileProc(WindowProcessController wpc) {
7460 synchronized (mGlobalLock) {
7461 mProfileProc = wpc;
7462 }
7463 }
7464
7465 @Override
7466 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7467 synchronized (mGlobalLock) {
7468 mProfilerInfo = profilerInfo;
7469 }
7470 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007471
7472 @Override
7473 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7474 synchronized (mGlobalLock) {
7475 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7476 }
7477 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007478
7479 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007480 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
Peter Kalauskas4dc04602020-02-12 18:49:03 -08007481 boolean isLowResolution) {
7482 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007483 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007484 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007485
7486 @Override
7487 public boolean isUidForeground(int uid) {
7488 synchronized (mGlobalLock) {
7489 return ActivityTaskManagerService.this.isUidForeground(uid);
7490 }
7491 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007492
7493 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007494 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007495 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007496 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007497 }
7498 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007499
7500 @Override
7501 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007502 // Translate package names into UIDs
7503 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007504 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007505 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7506 if (uid >= 0) {
7507 result.add(uid);
7508 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007509 }
7510 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007511 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007512 }
7513 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007514 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007515}