blob: 21d300aba1b9ec6c13ff6bea72700178411a6c70 [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;
Evan Rosky0037e5f2019-11-05 10:26:24 -0800147import android.app.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;
Evan Roskyaf9f27c2020-02-18 18:58:35 +0000233import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700234import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700235
Evan Rosky4505b352018-09-06 11:20:40 -0700236import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700237import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.app.AssistUtils;
239import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700240import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700243import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
244import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700245import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700246import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700247import com.android.internal.policy.IKeyguardDismissCallback;
248import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700249import com.android.internal.util.ArrayUtils;
250import com.android.internal.util.FastPrintWriter;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800251import com.android.internal.util.FrameworkStatsLog;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800252import com.android.internal.util.function.pooled.PooledConsumer;
253import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700254import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700255import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700256import com.android.server.LocalServices;
257import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700258import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800259import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700260import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700261import com.android.server.am.ActivityManagerService;
Wale Ogunwale59507092018-10-29 09:00:30 -0700262import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
263import com.android.server.am.AppTimeTracker;
264import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700265import com.android.server.am.PendingIntentController;
266import com.android.server.am.PendingIntentRecord;
267import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700268import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700269import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700270import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800271import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700272import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700276import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700278import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700280import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700281import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700282import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800283import java.lang.annotation.ElementType;
284import java.lang.annotation.Retention;
285import java.lang.annotation.RetentionPolicy;
286import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700287import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700288import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700290import java.util.Arrays;
Jeff Sharkey8b0cff72020-03-09 15:49:01 -0600291import java.util.Collection;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700292import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400293import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700294import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700295import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700296import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700297import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000298import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700299import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700300
301/**
302 * System service for managing activities and their containers (task, stacks, displays,... ).
303 *
304 * {@hide}
305 */
306public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700307 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800308 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000309 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700310 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
311 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
312 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
313 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700314 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700315
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700316 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700317 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700318 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700319 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100320 // How long we permit background activity starts after an activity in the process
321 // started or finished.
322 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700323
Wale Ogunwale98875612018-10-12 07:53:02 -0700324 /** Used to indicate that an app transition should be animated. */
325 static final boolean ANIMATE = true;
326
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700327 /** Hardware-reported OpenGLES version. */
328 final int GL_ES_VERSION;
329
Wale Ogunwale31913b52018-10-13 08:29:31 -0700330 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
331 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
332 public static final String DUMP_LASTANR_CMD = "lastanr" ;
333 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
334 public static final String DUMP_STARTER_CMD = "starter" ;
335 public static final String DUMP_CONTAINERS_CMD = "containers" ;
336 public static final String DUMP_RECENTS_CMD = "recents" ;
337 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
338
Wale Ogunwale64258362018-10-16 15:13:37 -0700339 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
340 public static final int RELAUNCH_REASON_NONE = 0;
341 /** This activity is being relaunched due to windowing mode change. */
342 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
343 /** This activity is being relaunched due to a free-resize operation. */
344 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
345
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700346 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700347
Wale Ogunwalef6733932018-06-27 05:14:34 -0700348 /**
349 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
350 * change at runtime. Use mContext for non-UI purposes.
351 */
352 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700353 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700354 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700355 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700356 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700357 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700358 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800359 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800360 @VisibleForTesting
361 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700362 PowerManagerInternal mPowerManagerInternal;
363 private UsageStatsManagerInternal mUsageStatsInternal;
364
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700365 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700366 IntentFirewall mIntentFirewall;
367
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700368 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800369 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800370 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700371 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800372 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
373 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
374 *
375 * @see WindowManagerThreadPriorityBooster
376 */
377 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700378 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800379 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700380 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700381 private UserManagerService mUserManager;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800382 private AppOpsManager mAppOpsManager;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700383 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800384 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700385 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700386 /** All processes currently running that might have a window organized by name. */
387 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100388 /** All processes we currently have running mapped by pid and uid */
389 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700390 /** This is the process holding what we currently consider to be the "home" activity. */
391 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700392 /** The currently running heavy-weight process, if any. */
393 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700394 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700395 /**
396 * This is the process holding the activity the user last visited that is in a different process
397 * from the one they are currently in.
398 */
399 WindowProcessController mPreviousProcess;
400 /** The time at which the previous process was last visible. */
401 long mPreviousProcessVisibleTime;
402
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700403 /** List of intents that were used to start the most recent tasks. */
404 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700405 /** State of external calls telling us if the device is awake or asleep. */
406 private boolean mKeyguardShown = false;
407
408 // Wrapper around VoiceInteractionServiceManager
409 private AssistUtils mAssistUtils;
410
411 // VoiceInteraction session ID that changes for each new request except when
412 // being called for multi-window assist in a single session.
413 private int mViSessionId = 1000;
414
415 // How long to wait in getAssistContextExtras for the activity and foreground services
416 // to respond with the result.
417 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
418
419 // How long top wait when going through the modern assist (which doesn't need to block
420 // on getting this result before starting to launch its UI).
421 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
422
423 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
424 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
425
Alison Cichowlas3e340502018-08-07 17:15:01 -0400426 // Permission tokens are used to temporarily granted a trusted app the ability to call
427 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
428 // showing any appropriate error messages to the user.
429 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
430 10 * MINUTE_IN_MILLIS;
431
432 // How long before the service actually expires a token. This is slightly longer than
433 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
434 // expiration exception.
435 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
436 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
437
438 // How long the service will remember expired tokens, for the purpose of providing error
439 // messaging when a client uses an expired token.
440 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
441 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
442
443 // Activity tokens of system activities that are delegating their call to
444 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
445 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
446
447 // Permission tokens that have expired, but we remember for error reporting.
448 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
449
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700450 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
451
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700452 // Keeps track of the active voice interaction service component, notified from
453 // VoiceInteractionManagerService
454 ComponentName mActiveVoiceInteractionServiceComponent;
455
Michal Karpinskida34cd42019-04-02 19:46:52 +0100456 // A map userId and all its companion app uids
457 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000458
Wale Ogunwalee2172292018-10-25 10:11:10 -0700459 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700460 KeyguardController mKeyguardController;
461 private final ClientLifecycleManager mLifecycleManager;
462 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700463 /** The controller for all operations related to locktask. */
464 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700465 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700466
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700467 boolean mSuppressResizeConfigChanges;
468
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700469 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700470 new UpdateConfigurationResult();
471
472 static final class UpdateConfigurationResult {
473 // Configuration changes that were updated.
474 int changes;
475 // If the activity was relaunched to match the new configuration.
476 boolean activityRelaunched;
477
478 void reset() {
479 changes = 0;
480 activityRelaunched = false;
481 }
482 }
483
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700484 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700485 private int mConfigurationSeq;
486 // To cache the list of supported system locales
487 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700488
489 /**
490 * Temp object used when global and/or display override configuration is updated. It is also
491 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
492 * anyone...
493 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700494 private Configuration mTempConfig = new Configuration();
495
Wale Ogunwalef6733932018-06-27 05:14:34 -0700496 /** Temporary to avoid allocations. */
497 final StringBuilder mStringBuilder = new StringBuilder(256);
498
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700499 // Amount of time after a call to stopAppSwitches() during which we will
500 // prevent further untrusted switches from happening.
501 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
502
503 /**
504 * The time at which we will allow normal application switches again,
505 * after a call to {@link #stopAppSwitches()}.
506 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700507 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700508 /**
509 * This is set to true after the first switch after mAppSwitchesAllowedTime
510 * is set; any switches after that will clear the time.
511 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700512 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700513
Ricky Wai906af482019-06-03 17:25:28 +0100514 /**
515 * Last stop app switches time, apps finished before this time cannot start background activity
516 * even if they are in grace period.
517 */
518 private long mLastStopAppSwitchesTime;
519
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700520 IActivityController mController = null;
521 boolean mControllerIsAMonkey = false;
522
Wale Ogunwale214f3482018-10-04 11:00:47 -0700523 final int mFactoryTest;
524
525 /** Used to control how we initialize the service. */
526 ComponentName mTopComponent;
527 String mTopAction = Intent.ACTION_MAIN;
528 String mTopData;
529
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800530 /** Profiling app information. */
531 String mProfileApp = null;
532 WindowProcessController mProfileProc = null;
533 ProfilerInfo mProfilerInfo = null;
534
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700535 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700536 * Dump of the activity state at the time of the last ANR. Cleared after
537 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
538 */
539 String mLastANRState;
540
541 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700542 * Used to retain an update lock when the foreground activity is in
543 * immersive mode.
544 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700545 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700546
547 /**
548 * Packages that are being allowed to perform unrestricted app switches. Mapping is
549 * User -> Type -> uid.
550 */
551 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
552
553 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700554 private int mThumbnailWidth;
555 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700556
557 /**
558 * Flag that indicates if multi-window is enabled.
559 *
560 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
561 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
562 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
563 * At least one of the forms of multi-window must be enabled in order for this flag to be
564 * initialized to 'true'.
565 *
566 * @see #mSupportsSplitScreenMultiWindow
567 * @see #mSupportsFreeformWindowManagement
568 * @see #mSupportsPictureInPicture
569 * @see #mSupportsMultiDisplay
570 */
571 boolean mSupportsMultiWindow;
572 boolean mSupportsSplitScreenMultiWindow;
573 boolean mSupportsFreeformWindowManagement;
574 boolean mSupportsPictureInPicture;
575 boolean mSupportsMultiDisplay;
576 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700577 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700578
579 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
580
581 // VR Vr2d Display Id.
582 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700583
Wale Ogunwalef6733932018-06-27 05:14:34 -0700584 /**
585 * Set while we are wanting to sleep, to prevent any
586 * activities from being started/resumed.
587 *
588 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
589 *
590 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
591 * while in the sleep state until there is a pending transition out of sleep, in which case
592 * mSleeping is set to false, and remains false while awake.
593 *
594 * Whether mSleeping can quickly toggled between true/false without the device actually
595 * display changing states is undefined.
596 */
597 private boolean mSleeping = false;
598
599 /**
600 * The process state used for processes that are running the top activities.
601 * This changes between TOP and TOP_SLEEPING to following mSleeping.
602 */
603 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
604
Riddle Hsua0022cd2019-09-09 21:12:41 +0800605 @Retention(RetentionPolicy.SOURCE)
606 @IntDef({
607 LAYOUT_REASON_CONFIG_CHANGED,
608 LAYOUT_REASON_VISIBILITY_CHANGED,
609 })
610 @interface LayoutReason {}
611 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
612 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
613
614 /** The reasons to perform surface placement. */
615 @LayoutReason
616 private int mLayoutReasons;
617
Wale Ogunwalef6733932018-06-27 05:14:34 -0700618 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
619 // automatically. Important for devices without direct input devices.
620 private boolean mShowDialogs = true;
621
622 /** Set if we are shutting down the system, similar to sleeping. */
623 boolean mShuttingDown = false;
624
625 /**
626 * We want to hold a wake lock while running a voice interaction session, since
627 * this may happen with the screen off and we need to keep the CPU running to
628 * be able to continue to interact with the user.
629 */
630 PowerManager.WakeLock mVoiceWakeLock;
631
632 /**
633 * Set while we are running a voice interaction. This overrides sleeping while it is active.
634 */
635 IVoiceInteractionSession mRunningVoice;
636
637 /**
638 * The last resumed activity. This is identical to the current resumed activity most
639 * of the time but could be different when we're pausing one activity before we resume
640 * another activity.
641 */
642 ActivityRecord mLastResumedActivity;
643
644 /**
645 * The activity that is currently being traced as the active resumed activity.
646 *
647 * @see #updateResumedAppTrace
648 */
649 private @Nullable ActivityRecord mTracedResumedActivity;
650
651 /** If non-null, we are tracking the time the user spends in the currently focused app. */
652 AppTimeTracker mCurAppTimeTracker;
653
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700654 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700655
Wale Ogunwale53783742018-09-16 10:21:51 -0700656 /**
657 * Packages that the user has asked to have run in screen size
658 * compatibility mode instead of filling the screen.
659 */
660 CompatModePackages mCompatModePackages;
661
Wale Ogunwalef6733932018-06-27 05:14:34 -0700662 private FontScaleSettingObserver mFontScaleSettingObserver;
663
Robert Carr8a2f9132019-11-11 15:03:15 -0800664 /**
665 * Stores the registration and state of TaskOrganizers in use.
666 */
Evan Rosky0037e5f2019-11-05 10:26:24 -0800667 TaskOrganizerController mTaskOrganizerController = new TaskOrganizerController(this);
Robert Carr8a2f9132019-11-11 15:03:15 -0800668
Ricky Wai96f5c352019-04-10 18:40:17 +0100669 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000670
Wale Ogunwalef6733932018-06-27 05:14:34 -0700671 private final class FontScaleSettingObserver extends ContentObserver {
672 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
673 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
674
675 public FontScaleSettingObserver() {
676 super(mH);
677 final ContentResolver resolver = mContext.getContentResolver();
678 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
679 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
680 UserHandle.USER_ALL);
681 }
682
683 @Override
Jeff Sharkey8b0cff72020-03-09 15:49:01 -0600684 public void onChange(boolean selfChange, Collection<Uri> uris, int flags,
Riddle Hsu9c024d12020-03-09 16:10:07 +0800685 @UserIdInt int userId) {
686 for (Uri uri : uris) {
687 if (mFontScaleUri.equals(uri)) {
688 updateFontScaleIfNeeded(userId);
689 } else if (mHideErrorDialogsUri.equals(uri)) {
690 synchronized (mGlobalLock) {
691 updateShouldShowDialogsLocked(getGlobalConfiguration());
692 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700693 }
694 }
695 }
696 }
697
Riddle Hsua0536432019-02-16 00:38:59 +0800698 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
699 @Target(ElementType.METHOD)
700 @Retention(RetentionPolicy.SOURCE)
701 @interface HotPath {
702 int NONE = 0;
703 int OOM_ADJUSTMENT = 1;
704 int LRU_UPDATE = 2;
705 int PROCESS_CHANGE = 3;
706 int caller() default NONE;
707 }
708
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800709 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
710 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900711 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800712 mAmInternal.updateOomAdj();
713 }
714 };
715
Charles Chen8d98dd22018-12-26 17:36:54 +0800716 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
717 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700718 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700719 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700720 mSystemThread = ActivityThread.currentActivityThread();
721 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700722 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800723 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700724 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700725 }
726
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700727 public void onSystemReady() {
728 synchronized (mGlobalLock) {
729 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
730 PackageManager.FEATURE_CANT_SAVE_STATE);
731 mAssistUtils = new AssistUtils(mContext);
732 mVrController.onSystemReady();
733 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700734 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700735 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700736 }
737
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700738 public void onInitPowerManagement() {
739 synchronized (mGlobalLock) {
740 mStackSupervisor.initPowerManagement();
741 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
742 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
743 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
744 mVoiceWakeLock.setReferenceCounted(false);
745 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700746 }
747
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700748 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700749 mFontScaleSettingObserver = new FontScaleSettingObserver();
750 }
751
Wale Ogunwale59507092018-10-29 09:00:30 -0700752 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700753 final boolean freeformWindowManagement =
754 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
755 || Settings.Global.getInt(
756 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
757
758 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
759 final boolean supportsPictureInPicture = supportsMultiWindow &&
760 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
761 final boolean supportsSplitScreenMultiWindow =
762 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
763 final boolean supportsMultiDisplay = mContext.getPackageManager()
764 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700765 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
766 final boolean forceResizable = Settings.Global.getInt(
767 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700768 final boolean sizeCompatFreeform = Settings.Global.getInt(
769 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700770
771 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900772 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700773
774 final Configuration configuration = new Configuration();
775 Settings.System.getConfiguration(resolver, configuration);
776 if (forceRtl) {
777 // This will take care of setting the correct layout direction flags
778 configuration.setLayoutDirection(configuration.locale);
779 }
780
781 synchronized (mGlobalLock) {
782 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700783 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700784 final boolean multiWindowFormEnabled = freeformWindowManagement
785 || supportsSplitScreenMultiWindow
786 || supportsPictureInPicture
787 || supportsMultiDisplay;
788 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
789 mSupportsMultiWindow = true;
790 mSupportsFreeformWindowManagement = freeformWindowManagement;
791 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
792 mSupportsPictureInPicture = supportsPictureInPicture;
793 mSupportsMultiDisplay = supportsMultiDisplay;
794 } else {
795 mSupportsMultiWindow = false;
796 mSupportsFreeformWindowManagement = false;
797 mSupportsSplitScreenMultiWindow = false;
798 mSupportsPictureInPicture = false;
799 mSupportsMultiDisplay = false;
800 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700801 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700802 // This happens before any activities are started, so we can change global configuration
803 // in-place.
804 updateConfigurationLocked(configuration, null, true);
805 final Configuration globalConfig = getGlobalConfiguration();
806 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
807
808 // Load resources only after the current configuration has been set.
809 final Resources res = mContext.getResources();
810 mThumbnailWidth = res.getDimensionPixelSize(
811 com.android.internal.R.dimen.thumbnail_width);
812 mThumbnailHeight = res.getDimensionPixelSize(
813 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700814 }
815 }
816
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800817 public WindowManagerGlobalLock getGlobalLock() {
818 return mGlobalLock;
819 }
820
Yunfan Chen585f2932019-01-29 16:04:45 +0900821 /** For test purpose only. */
822 @VisibleForTesting
823 public ActivityTaskManagerInternal getAtmInternal() {
824 return mInternal;
825 }
826
Riddle Hsud93a6c42018-11-29 21:50:06 +0800827 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
828 Looper looper) {
829 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700830 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700831 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700832 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800833 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700834 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700835 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700836 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700837
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700838 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700839 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700840 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700841 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700842 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700843 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700844 mKeyguardController = mStackSupervisor.getKeyguardController();
845 }
846
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700847 public void onActivityManagerInternalAdded() {
848 synchronized (mGlobalLock) {
849 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
850 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
851 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700852 }
853
Yunfan Chen75157d72018-07-27 14:47:21 +0900854 int increaseConfigurationSeqLocked() {
855 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
856 return mConfigurationSeq;
857 }
858
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700859 protected ActivityStackSupervisor createStackSupervisor() {
860 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
861 supervisor.initialize();
862 return supervisor;
863 }
864
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800865 protected AppWarnings createAppWarnings(
866 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
867 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
868 }
869
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700870 public void setWindowManager(WindowManagerService wm) {
871 synchronized (mGlobalLock) {
872 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800873 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800874 mTempConfig.setToDefaults();
875 mTempConfig.setLocales(LocaleList.getDefault());
876 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800877 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700878 mLockTaskController.setWindowManager(wm);
879 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800880 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700881 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700882 }
883
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700884 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
885 synchronized (mGlobalLock) {
886 mUsageStatsInternal = usageStatsManager;
887 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700888 }
889
Wale Ogunwalef6733932018-06-27 05:14:34 -0700890 UserManagerService getUserManager() {
891 if (mUserManager == null) {
892 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
893 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
894 }
895 return mUserManager;
896 }
897
Philip P. Moltmannee295092020-02-10 08:46:26 -0800898 AppOpsManager getAppOpsManager() {
899 if (mAppOpsManager == null) {
900 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Wale Ogunwalef6733932018-06-27 05:14:34 -0700901 }
Philip P. Moltmannee295092020-02-10 08:46:26 -0800902 return mAppOpsManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700903 }
904
905 boolean hasUserRestriction(String restriction, int userId) {
906 return getUserManager().hasUserRestriction(restriction, userId);
907 }
908
Michal Karpinski15486842019-04-25 17:33:42 +0100909 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
Philip P. Moltmannee295092020-02-10 08:46:26 -0800910 final int mode = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
911 callingUid, callingPackage, /* featureId */ null, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100912 if (mode == AppOpsManager.MODE_DEFAULT) {
913 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
914 == PERMISSION_GRANTED;
915 }
916 return mode == AppOpsManager.MODE_ALLOWED;
917 }
918
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700919 @VisibleForTesting
920 protected void setRecentTasks(RecentTasks recentTasks) {
921 mRecentTasks = recentTasks;
922 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700923 }
924
925 RecentTasks getRecentTasks() {
926 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700927 }
928
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700929 ClientLifecycleManager getLifecycleManager() {
930 return mLifecycleManager;
931 }
932
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700933 ActivityStartController getActivityStartController() {
934 return mActivityStartController;
935 }
936
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700937 TaskChangeNotificationController getTaskChangeNotificationController() {
938 return mTaskChangeNotificationController;
939 }
940
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700941 LockTaskController getLockTaskController() {
942 return mLockTaskController;
943 }
944
Yunfan Chen75157d72018-07-27 14:47:21 +0900945 /**
946 * Return the global configuration used by the process corresponding to the input pid. This is
947 * usually the global configuration with some overrides specific to that process.
948 */
949 Configuration getGlobalConfigurationForCallingPid() {
950 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800951 return getGlobalConfigurationForPid(pid);
952 }
953
954 /**
955 * Return the global configuration used by the process corresponding to the given pid.
956 */
957 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900958 if (pid == MY_PID || pid < 0) {
959 return getGlobalConfiguration();
960 }
961 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100962 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900963 return app != null ? app.getConfiguration() : getGlobalConfiguration();
964 }
965 }
966
967 /**
968 * Return the device configuration info used by the process corresponding to the input pid.
969 * The value is consistent with the global configuration for the process.
970 */
971 @Override
972 public ConfigurationInfo getDeviceConfigurationInfo() {
973 ConfigurationInfo config = new ConfigurationInfo();
974 synchronized (mGlobalLock) {
975 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
976 config.reqTouchScreen = globalConfig.touchscreen;
977 config.reqKeyboardType = globalConfig.keyboard;
978 config.reqNavigation = globalConfig.navigation;
979 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
980 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
981 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
982 }
983 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
984 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
985 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
986 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700987 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900988 }
989 return config;
990 }
991
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700992 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700993 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700994 }
995
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700996 public static final class Lifecycle extends SystemService {
997 private final ActivityTaskManagerService mService;
998
999 public Lifecycle(Context context) {
1000 super(context);
1001 mService = new ActivityTaskManagerService(context);
1002 }
1003
1004 @Override
1005 public void onStart() {
1006 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001007 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001008 }
1009
Garfield Tan891146c2018-10-09 12:14:00 -07001010 @Override
1011 public void onUnlockUser(int userId) {
1012 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001013 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001014 }
1015 }
1016
1017 @Override
1018 public void onCleanupUser(int userId) {
1019 synchronized (mService.getGlobalLock()) {
1020 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1021 }
1022 }
1023
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001024 public ActivityTaskManagerService getService() {
1025 return mService;
1026 }
1027 }
1028
1029 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001030 public final int startActivity(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001031 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1032 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1033 Bundle bOptions) {
1034 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1035 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001036 UserHandle.getCallingUserId());
1037 }
1038
1039 @Override
1040 public final int startActivities(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001041 String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
1042 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001043 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001045 enforceNotIsolatedCaller(reason);
1046 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001047 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001048 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001049 callingFeatureId, intents, resolvedTypes, resultTo,
1050 SafeActivityOptions.fromBundle(bOptions), userId, reason,
1051 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001052 }
1053
1054 @Override
1055 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001056 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1057 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1058 Bundle bOptions, int userId) {
1059 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1060 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001061 true /*validateIncomingUser*/);
1062 }
1063
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001064 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001065 @Nullable String callingFeatureId, Intent intent, String resolvedType,
1066 IBinder resultTo, String resultWho, int requestCode, int startFlags,
1067 ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001068 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001069 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001070
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001071 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001072 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1073
1074 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001075 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001076 .setCaller(caller)
1077 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001078 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001079 .setResolvedType(resolvedType)
1080 .setResultTo(resultTo)
1081 .setResultWho(resultWho)
1082 .setRequestCode(requestCode)
1083 .setStartFlags(startFlags)
1084 .setProfilerInfo(profilerInfo)
1085 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001086 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001087 .execute();
1088
1089 }
1090
1091 @Override
1092 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1093 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001094 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1095 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001096 // Refuse possible leaked file descriptors
1097 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1098 throw new IllegalArgumentException("File descriptors passed in Intent");
1099 }
1100
1101 if (!(target instanceof PendingIntentRecord)) {
1102 throw new IllegalArgumentException("Bad PendingIntent object");
1103 }
1104
1105 PendingIntentRecord pir = (PendingIntentRecord)target;
1106
1107 synchronized (mGlobalLock) {
1108 // If this is coming from the currently resumed activity, it is
1109 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001110 final ActivityStack stack = getTopDisplayFocusedStack();
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001111 if (stack != null && stack.mResumedActivity != null
1112 && stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001113 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001114 }
1115 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001116 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001117 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001118 }
1119
1120 @Override
1121 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1122 Bundle bOptions) {
1123 // Refuse possible leaked file descriptors
1124 if (intent != null && intent.hasFileDescriptors()) {
1125 throw new IllegalArgumentException("File descriptors passed in Intent");
1126 }
1127 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1128
1129 synchronized (mGlobalLock) {
1130 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1131 if (r == null) {
1132 SafeActivityOptions.abort(options);
1133 return false;
1134 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001135 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001136 // The caller is not running... d'oh!
1137 SafeActivityOptions.abort(options);
1138 return false;
1139 }
1140 intent = new Intent(intent);
1141 // The caller is not allowed to change the data.
1142 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1143 // And we are resetting to find the next component...
1144 intent.setComponent(null);
1145
1146 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1147
1148 ActivityInfo aInfo = null;
1149 try {
1150 List<ResolveInfo> resolves =
1151 AppGlobals.getPackageManager().queryIntentActivities(
1152 intent, r.resolvedType,
1153 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1154 UserHandle.getCallingUserId()).getList();
1155
1156 // Look for the original activity in the list...
1157 final int N = resolves != null ? resolves.size() : 0;
1158 for (int i=0; i<N; i++) {
1159 ResolveInfo rInfo = resolves.get(i);
1160 if (rInfo.activityInfo.packageName.equals(r.packageName)
1161 && rInfo.activityInfo.name.equals(r.info.name)) {
1162 // We found the current one... the next matching is
1163 // after it.
1164 i++;
1165 if (i<N) {
1166 aInfo = resolves.get(i).activityInfo;
1167 }
1168 if (debug) {
1169 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1170 + "/" + r.info.name);
1171 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1172 ? "null" : aInfo.packageName + "/" + aInfo.name));
1173 }
1174 break;
1175 }
1176 }
1177 } catch (RemoteException e) {
1178 }
1179
1180 if (aInfo == null) {
1181 // Nobody who is next!
1182 SafeActivityOptions.abort(options);
1183 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1184 return false;
1185 }
1186
1187 intent.setComponent(new ComponentName(
1188 aInfo.applicationInfo.packageName, aInfo.name));
1189 intent.setFlags(intent.getFlags()&~(
1190 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1191 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1192 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1193 FLAG_ACTIVITY_NEW_TASK));
1194
1195 // Okay now we need to start the new activity, replacing the currently running activity.
1196 // This is a little tricky because we want to start the new one as if the current one is
1197 // finished, but not finish the current one first so that there is no flicker.
1198 // And thus...
1199 final boolean wasFinishing = r.finishing;
1200 r.finishing = true;
1201
1202 // Propagate reply information over to the new activity.
1203 final ActivityRecord resultTo = r.resultTo;
1204 final String resultWho = r.resultWho;
1205 final int requestCode = r.requestCode;
1206 r.resultTo = null;
1207 if (resultTo != null) {
1208 resultTo.removeResultsLocked(r, resultWho, requestCode);
1209 }
1210
1211 final long origId = Binder.clearCallingIdentity();
1212 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001213 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001214 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001215 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001216 .setResolvedType(r.resolvedType)
1217 .setActivityInfo(aInfo)
1218 .setResultTo(resultTo != null ? resultTo.appToken : null)
1219 .setResultWho(resultWho)
1220 .setRequestCode(requestCode)
1221 .setCallingPid(-1)
1222 .setCallingUid(r.launchedFromUid)
1223 .setCallingPackage(r.launchedFromPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001224 .setCallingFeatureId(r.launchedFromFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001225 .setRealCallingPid(-1)
1226 .setRealCallingUid(r.launchedFromUid)
1227 .setActivityOptions(options)
1228 .execute();
1229 Binder.restoreCallingIdentity(origId);
1230
1231 r.finishing = wasFinishing;
1232 if (res != ActivityManager.START_SUCCESS) {
1233 return false;
1234 }
1235 return true;
1236 }
1237 }
1238
1239 @Override
Galia Peycheva6861e912019-08-21 10:20:23 +02001240 public boolean startDreamActivity(Intent intent) {
Galia Peycheva52e89222020-02-18 23:41:43 +01001241 final WindowProcessController process = mProcessMap.getProcess(Binder.getCallingPid());
1242 final long origId = Binder.clearCallingIdentity();
1243
1244 // The dream activity is only called for non-doze dreams.
1245 final ComponentName currentDream = LocalServices.getService(DreamManagerInternal.class)
1246 .getActiveDreamComponent(/* doze= */ false);
1247
1248 if (currentDream == null || currentDream.getPackageName() == null
1249 || !currentDream.getPackageName().equals(process.mInfo.packageName)) {
1250 Slog.e(TAG, "Calling package is not the current dream package. "
1251 + "Aborting startDreamActivity...");
1252 return false;
1253 }
1254
Galia Peycheva6861e912019-08-21 10:20:23 +02001255 final ActivityInfo a = new ActivityInfo();
1256 a.theme = com.android.internal.R.style.Theme_Dream;
1257 a.exported = true;
1258 a.name = DreamActivity.class.getName();
1259
Galia Peycheva6861e912019-08-21 10:20:23 +02001260
1261 a.packageName = process.mInfo.packageName;
1262 a.applicationInfo = process.mInfo;
1263 a.processName = process.mInfo.processName;
1264 a.uiOptions = process.mInfo.uiOptions;
1265 a.taskAffinity = "android:" + a.packageName + "/dream";
1266 a.enabled = true;
1267 a.launchMode = ActivityInfo.LAUNCH_SINGLE_INSTANCE;
1268
1269 a.persistableMode = ActivityInfo.PERSIST_NEVER;
1270 a.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1271 a.colorMode = ActivityInfo.COLOR_MODE_DEFAULT;
1272 a.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1273
Galia Peycheva6861e912019-08-21 10:20:23 +02001274 try {
1275 getActivityStartController().obtainStarter(intent, "dream")
1276 .setActivityInfo(a)
1277 .setIsDream(true)
1278 .execute();
1279 return true;
1280 } finally {
1281 Binder.restoreCallingIdentity(origId);
1282 }
1283 }
1284
1285 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001286 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001287 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1288 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1289 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001290 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001291 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001292 enforceNotIsolatedCaller("startActivityAndWait");
1293 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1294 userId, "startActivityAndWait");
1295 // TODO: Switch to user app stacks here.
1296 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1297 .setCaller(caller)
1298 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001299 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001300 .setResolvedType(resolvedType)
1301 .setResultTo(resultTo)
1302 .setResultWho(resultWho)
1303 .setRequestCode(requestCode)
1304 .setStartFlags(startFlags)
1305 .setActivityOptions(bOptions)
1306 .setUserId(userId)
1307 .setProfilerInfo(profilerInfo)
1308 .setWaitResult(res)
1309 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001310 return res;
1311 }
1312
1313 @Override
1314 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001315 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1316 String resultWho, int requestCode, int startFlags, Configuration config,
1317 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001318 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001319 enforceNotIsolatedCaller("startActivityWithConfig");
1320 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1321 "startActivityWithConfig");
1322 // TODO: Switch to user app stacks here.
1323 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1324 .setCaller(caller)
1325 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001326 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001327 .setResolvedType(resolvedType)
1328 .setResultTo(resultTo)
1329 .setResultWho(resultWho)
1330 .setRequestCode(requestCode)
1331 .setStartFlags(startFlags)
1332 .setGlobalConfiguration(config)
1333 .setActivityOptions(bOptions)
1334 .setUserId(userId)
1335 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001336 }
1337
Robert Carr8a2f9132019-11-11 15:03:15 -08001338 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001339 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1340 int callingUid = Binder.getCallingUid();
1341 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1342 throw new SecurityException("Only the system process can request a permission token, "
1343 + "received request from uid: " + callingUid);
1344 }
1345 IBinder permissionToken = new Binder();
1346 synchronized (mGlobalLock) {
1347 mStartActivitySources.put(permissionToken, delegatorToken);
1348 }
1349
1350 Message expireMsg = PooledLambda.obtainMessage(
1351 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1352 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1353
1354 Message forgetMsg = PooledLambda.obtainMessage(
1355 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1356 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1357
1358 return permissionToken;
1359 }
1360
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001361 @Override
1362 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1363 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001364 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1365 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001366 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001367 // permission grants) as any app that may launch one of your own activities. So we only
1368 // allow this in two cases:
1369 // 1) The caller is an activity that is part of the core framework, and then only when it
1370 // is running as the system.
1371 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1372 // can only be requested by a system activity, which may then delegate this call to
1373 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001374 final ActivityRecord sourceRecord;
1375 final int targetUid;
1376 final String targetPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001377 final String targetFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001378 final boolean isResolver;
1379 synchronized (mGlobalLock) {
1380 if (resultTo == null) {
1381 throw new SecurityException("Must be called from an activity");
1382 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001383 final IBinder sourceToken;
1384 if (permissionToken != null) {
1385 // To even attempt to use a permissionToken, an app must also have this signature
1386 // permission.
1387 mAmInternal.enforceCallingPermission(
1388 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1389 "startActivityAsCaller");
1390 // If called with a permissionToken, we want the sourceRecord from the delegator
1391 // activity that requested this token.
1392 sourceToken = mStartActivitySources.remove(permissionToken);
1393 if (sourceToken == null) {
1394 // Invalid permissionToken, check if it recently expired.
1395 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1396 throw new SecurityException("Called with expired permission token: "
1397 + permissionToken);
1398 } else {
1399 throw new SecurityException("Called with invalid permission token: "
1400 + permissionToken);
1401 }
1402 }
1403 } else {
1404 // This method was called directly by the source.
1405 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001406 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001407
Louis Chang149d5c82019-12-30 09:47:39 +08001408 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001409 if (sourceRecord == null) {
1410 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001411 }
1412 if (sourceRecord.app == null) {
1413 throw new SecurityException("Called without a process attached to activity");
1414 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001415
1416 // Whether called directly or from a delegate, the source activity must be from the
1417 // android package.
1418 if (!sourceRecord.info.packageName.equals("android")) {
1419 throw new SecurityException("Must be called from an activity that is "
1420 + "declared in the android package");
1421 }
1422
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001423 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001424 // This is still okay, as long as this activity is running under the
1425 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001426 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001427 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001428 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001429 + " must be system uid or original calling uid "
1430 + sourceRecord.launchedFromUid);
1431 }
1432 }
1433 if (ignoreTargetSecurity) {
1434 if (intent.getComponent() == null) {
1435 throw new SecurityException(
1436 "Component must be specified with ignoreTargetSecurity");
1437 }
1438 if (intent.getSelector() != null) {
1439 throw new SecurityException(
1440 "Selector not allowed with ignoreTargetSecurity");
1441 }
1442 }
1443 targetUid = sourceRecord.launchedFromUid;
1444 targetPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001445 targetFeatureId = sourceRecord.launchedFromFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001446 isResolver = sourceRecord.isResolverOrChildActivity();
1447 }
1448
1449 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001450 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001451 }
1452
1453 // TODO: Switch to user app stacks here.
1454 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001455 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456 .setCallingUid(targetUid)
1457 .setCallingPackage(targetPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001458 .setCallingFeatureId(targetFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 .setResolvedType(resolvedType)
1460 .setResultTo(resultTo)
1461 .setResultWho(resultWho)
1462 .setRequestCode(requestCode)
1463 .setStartFlags(startFlags)
1464 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001465 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001466 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1467 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001468 // The target may well be in the background, which would normally prevent it
1469 // from starting an activity. Here we definitely want the start to succeed.
1470 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001471 .execute();
1472 } catch (SecurityException e) {
1473 // XXX need to figure out how to propagate to original app.
1474 // A SecurityException here is generally actually a fault of the original
1475 // calling activity (such as a fairly granting permissions), so propagate it
1476 // back to them.
1477 /*
1478 StringBuilder msg = new StringBuilder();
1479 msg.append("While launching");
1480 msg.append(intent.toString());
1481 msg.append(": ");
1482 msg.append(e.getMessage());
1483 */
1484 throw e;
1485 }
1486 }
1487
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001488 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1489 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001490 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001491 }
1492
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001493 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001494 public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1495 int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001496 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1497 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001498 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001499 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001500 if (session == null || interactor == null) {
1501 throw new NullPointerException("null session or interactor");
1502 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001503 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001504 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001505 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001506 .setCallingUid(callingUid)
1507 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001508 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001509 .setResolvedType(resolvedType)
1510 .setVoiceSession(session)
1511 .setVoiceInteractor(interactor)
1512 .setStartFlags(startFlags)
1513 .setProfilerInfo(profilerInfo)
1514 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001515 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001516 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001517 .execute();
1518 }
1519
1520 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001521 public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1522 int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1523 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001524 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001525 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1526 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001527
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001528 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001529 .setCallingUid(callingUid)
1530 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001531 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001532 .setResolvedType(resolvedType)
1533 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001534 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001535 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001536 .execute();
1537 }
1538
Riddle Hsu609a8e22019-06-27 16:46:29 -06001539 /**
1540 * Start the recents activity to perform the recents animation.
1541 *
1542 * @param intent The intent to start the recents activity.
1543 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1544 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001545 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001546 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1547 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001548 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001549 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001550 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 final long origId = Binder.clearCallingIdentity();
1552 try {
1553 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001554 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
Philip P. Moltmannee295092020-02-10 08:46:26 -08001555 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001556 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001557 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001558
1559 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001560 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001561 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001562 recentsFeatureId, recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001563 if (recentsAnimationRunner == null) {
1564 anim.preloadRecentsActivity();
1565 } else {
1566 anim.startRecentsActivity(recentsAnimationRunner);
1567 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001568 }
1569 } finally {
1570 Binder.restoreCallingIdentity(origId);
1571 }
1572 }
1573
1574 @Override
1575 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001576 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001577 "startActivityFromRecents()");
1578
1579 final int callingPid = Binder.getCallingPid();
1580 final int callingUid = Binder.getCallingUid();
1581 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1582 final long origId = Binder.clearCallingIdentity();
1583 try {
1584 synchronized (mGlobalLock) {
1585 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1586 safeOptions);
1587 }
1588 } finally {
1589 Binder.restoreCallingIdentity(origId);
1590 }
1591 }
1592
1593 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001594 * Public API to check if the client is allowed to start an activity on specified display.
1595 *
1596 * If the target display is private or virtual, some restrictions will apply.
1597 *
1598 * @param displayId Target display id.
1599 * @param intent Intent used to launch the activity.
1600 * @param resolvedType The MIME type of the intent.
1601 * @param userId The id of the user for whom the call is made.
1602 * @return {@code true} if a call to start an activity on the target display should succeed and
1603 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1604 */
1605 @Override
1606 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1607 String resolvedType, int userId) {
1608 final int callingUid = Binder.getCallingUid();
1609 final int callingPid = Binder.getCallingPid();
1610 final long origId = Binder.clearCallingIdentity();
1611
1612 try {
1613 // Collect information about the target of the Intent.
1614 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1615 0 /* startFlags */, null /* profilerInfo */, userId,
1616 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1617 UserHandle.USER_NULL));
1618 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1619
1620 synchronized (mGlobalLock) {
1621 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1622 aInfo);
1623 }
1624 } finally {
1625 Binder.restoreCallingIdentity(origId);
1626 }
1627 }
1628
1629 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001630 * This is the internal entry point for handling Activity.finish().
1631 *
1632 * @param token The Binder token referencing the Activity we want to finish.
1633 * @param resultCode Result code, if any, from this Activity.
1634 * @param resultData Result data (Intent), if any, from this Activity.
1635 * @param finishTask Whether to finish the task associated with this Activity.
1636 *
1637 * @return Returns true if the activity successfully finished, or false if it is still running.
1638 */
1639 @Override
1640 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1641 int finishTask) {
1642 // Refuse possible leaked file descriptors
1643 if (resultData != null && resultData.hasFileDescriptors()) {
1644 throw new IllegalArgumentException("File descriptors passed in Intent");
1645 }
1646
1647 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001648 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001649 if (r == null) {
1650 return true;
1651 }
1652 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001653 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001654 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001655 if (rootR == null) {
1656 Slog.w(TAG, "Finishing task with all activities already finished");
1657 }
1658 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1659 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001660 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001661 return false;
1662 }
1663
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001664 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1665 // We should consolidate.
1666 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001667 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001668 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001669 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001670 if (next != null) {
1671 // ask watcher if this is allowed
1672 boolean resumeOK = true;
1673 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001674 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001675 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001676 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001677 Watchdog.getInstance().setActivityController(null);
1678 }
1679
1680 if (!resumeOK) {
1681 Slog.i(TAG, "Not finishing activity because controller resumed");
1682 return false;
1683 }
1684 }
1685 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001686
1687 // note down that the process has finished an activity and is in background activity
1688 // starts grace period
1689 if (r.app != null) {
1690 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1691 }
1692
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001693 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001694 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001695 try {
1696 boolean res;
1697 final boolean finishWithRootActivity =
1698 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1699 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1700 || (finishWithRootActivity && r == rootR)) {
1701 // If requested, remove the task that is associated to this activity only if it
1702 // was the root activity in the task. The result code and data is ignored
1703 // because we don't support returning them across task boundaries. Also, to
1704 // keep backwards compatibility we remove the task from recents when finishing
1705 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001706 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001707 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001708 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001709 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001710 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001711 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001712 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001713 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001714 if (!res) {
1715 Slog.i(TAG, "Failed to finish by app-request");
1716 }
1717 }
1718 return res;
1719 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001720 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001721 Binder.restoreCallingIdentity(origId);
1722 }
1723 }
1724 }
1725
1726 @Override
1727 public boolean finishActivityAffinity(IBinder token) {
1728 synchronized (mGlobalLock) {
1729 final long origId = Binder.clearCallingIdentity();
1730 try {
1731 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1732 if (r == null) {
1733 return false;
1734 }
1735
1736 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1737 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001738 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001739 return false;
1740 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001741
1742 final PooledFunction p = PooledLambda.obtainFunction(
1743 ActivityRecord::finishIfSameAffinity, r,
1744 PooledLambda.__(ActivityRecord.class));
1745 r.getTask().forAllActivities(
1746 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1747 p.recycle();
1748
Andrii Kuliande93eff2019-07-12 12:21:27 -07001749 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001750 } finally {
1751 Binder.restoreCallingIdentity(origId);
1752 }
1753 }
1754 }
1755
1756 @Override
1757 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1758 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001759 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001760 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001761 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001762 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1763 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001764 return;
1765 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001766 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1767 false /* processPausingActivities */, config);
1768 if (stopProfiling && r.hasProcess()) {
1769 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001770 }
1771 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001772 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001773 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001774 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001775 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001776 }
1777
1778 @Override
1779 public final void activityResumed(IBinder token) {
1780 final long origId = Binder.clearCallingIdentity();
1781 synchronized (mGlobalLock) {
1782 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001783 }
1784 Binder.restoreCallingIdentity(origId);
1785 }
1786
1787 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001788 public final void activityTopResumedStateLost() {
1789 final long origId = Binder.clearCallingIdentity();
1790 synchronized (mGlobalLock) {
1791 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1792 }
1793 Binder.restoreCallingIdentity(origId);
1794 }
1795
1796 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001797 public final void activityPaused(IBinder token) {
1798 final long origId = Binder.clearCallingIdentity();
1799 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001800 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001801 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1802 if (r != null) {
1803 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001804 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001805 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001806 }
1807 Binder.restoreCallingIdentity(origId);
1808 }
1809
1810 @Override
1811 public final void activityStopped(IBinder token, Bundle icicle,
1812 PersistableBundle persistentState, CharSequence description) {
1813 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1814
1815 // Refuse possible leaked file descriptors
1816 if (icicle != null && icicle.hasFileDescriptors()) {
1817 throw new IllegalArgumentException("File descriptors passed in Bundle");
1818 }
1819
1820 final long origId = Binder.clearCallingIdentity();
1821
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001822 String restartingName = null;
1823 int restartingUid = 0;
1824 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001825 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001826 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001827 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001828 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001829 if (r.attachedToProcess()
1830 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1831 // The activity was requested to restart from
1832 // {@link #restartActivityProcessIfVisible}.
1833 restartingName = r.app.mName;
1834 restartingUid = r.app.mUid;
1835 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001836 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001837 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001838 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001839 }
1840
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001841 if (restartingName != null) {
1842 // In order to let the foreground activity can be restarted with its saved state from
1843 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1844 // until the activity reports stopped with the state. And the activity record will be
1845 // kept because the record state is restarting, then the activity will be restarted
1846 // immediately if it is still the top one.
1847 mStackSupervisor.removeRestartTimeouts(r);
1848 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1849 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001850 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001851
1852 Binder.restoreCallingIdentity(origId);
1853 }
1854
1855 @Override
1856 public final void activityDestroyed(IBinder token) {
1857 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1858 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001859 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001860 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001861 try {
1862 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1863 if (activity != null) {
1864 activity.destroyed("activityDestroyed");
1865 }
1866 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001867 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001868 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001869 }
1870 }
1871 }
1872
1873 @Override
1874 public final void activityRelaunched(IBinder token) {
1875 final long origId = Binder.clearCallingIdentity();
1876 synchronized (mGlobalLock) {
1877 mStackSupervisor.activityRelaunchedLocked(token);
1878 }
1879 Binder.restoreCallingIdentity(origId);
1880 }
1881
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001882 @Override
1883 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1884 synchronized (mGlobalLock) {
1885 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1886 if (r == null) {
1887 return;
1888 }
1889 final long origId = Binder.clearCallingIdentity();
1890 try {
1891 r.setRequestedOrientation(requestedOrientation);
1892 } finally {
1893 Binder.restoreCallingIdentity(origId);
1894 }
1895 }
1896 }
1897
1898 @Override
1899 public int getRequestedOrientation(IBinder token) {
1900 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001901 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1902 return (r != null)
1903 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001904 }
1905 }
1906
1907 @Override
1908 public void setImmersive(IBinder token, boolean immersive) {
1909 synchronized (mGlobalLock) {
1910 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1911 if (r == null) {
1912 throw new IllegalArgumentException();
1913 }
1914 r.immersive = immersive;
1915
1916 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001917 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001918 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001919 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001920 }
1921 }
1922 }
1923
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001924 void applyUpdateLockStateLocked(ActivityRecord r) {
1925 // Modifications to the UpdateLock state are done on our handler, outside
1926 // the activity manager's locks. The new state is determined based on the
1927 // state *now* of the relevant activity record. The object is passed to
1928 // the handler solely for logging detail, not to be consulted/modified.
1929 final boolean nextState = r != null && r.immersive;
1930 mH.post(() -> {
1931 if (mUpdateLock.isHeld() != nextState) {
1932 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1933 "Applying new update lock state '" + nextState + "' for " + r);
1934 if (nextState) {
1935 mUpdateLock.acquire();
1936 } else {
1937 mUpdateLock.release();
1938 }
1939 }
1940 });
1941 }
1942
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001943 @Override
1944 public boolean isImmersive(IBinder token) {
1945 synchronized (mGlobalLock) {
1946 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1947 if (r == null) {
1948 throw new IllegalArgumentException();
1949 }
1950 return r.immersive;
1951 }
1952 }
1953
1954 @Override
1955 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001956 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001957 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001958 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
1959 if (topFocusedStack == null) {
1960 return false;
1961 }
1962
1963 final ActivityRecord r = topFocusedStack.topRunningActivity();
1964 return r != null && r.immersive;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001965 }
1966 }
1967
1968 @Override
1969 public void overridePendingTransition(IBinder token, String packageName,
1970 int enterAnim, int exitAnim) {
1971 synchronized (mGlobalLock) {
1972 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1973 if (self == null) {
1974 return;
1975 }
1976
1977 final long origId = Binder.clearCallingIdentity();
1978
1979 if (self.isState(
1980 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001981 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001982 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001983 }
1984
1985 Binder.restoreCallingIdentity(origId);
1986 }
1987 }
1988
1989 @Override
1990 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001991 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001992 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001993 final ActivityStack stack = getTopDisplayFocusedStack();
1994 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001995 if (r == null) {
1996 return ActivityManager.COMPAT_MODE_UNKNOWN;
1997 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001998 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 }
2000 }
2001
2002 @Override
2003 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002004 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002005 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002006 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002007 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002008 final ActivityStack stack = getTopDisplayFocusedStack();
2009 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002010 if (r == null) {
2011 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
2012 return;
2013 }
2014 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07002015 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002016 }
2017 }
2018
2019 @Override
2020 public int getLaunchedFromUid(IBinder activityToken) {
2021 ActivityRecord srec;
2022 synchronized (mGlobalLock) {
2023 srec = ActivityRecord.forTokenLocked(activityToken);
2024 }
2025 if (srec == null) {
2026 return -1;
2027 }
2028 return srec.launchedFromUid;
2029 }
2030
2031 @Override
2032 public String getLaunchedFromPackage(IBinder activityToken) {
2033 ActivityRecord srec;
2034 synchronized (mGlobalLock) {
2035 srec = ActivityRecord.forTokenLocked(activityToken);
2036 }
2037 if (srec == null) {
2038 return null;
2039 }
2040 return srec.launchedFromPackage;
2041 }
2042
2043 @Override
2044 public boolean convertFromTranslucent(IBinder token) {
2045 final long origId = Binder.clearCallingIdentity();
2046 try {
2047 synchronized (mGlobalLock) {
2048 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2049 if (r == null) {
2050 return false;
2051 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002052 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002053 }
2054 } finally {
2055 Binder.restoreCallingIdentity(origId);
2056 }
2057 }
2058
2059 @Override
2060 public boolean convertToTranslucent(IBinder token, Bundle options) {
2061 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2062 final long origId = Binder.clearCallingIdentity();
2063 try {
2064 synchronized (mGlobalLock) {
2065 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2066 if (r == null) {
2067 return false;
2068 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002069 final ActivityRecord under = r.getTask().getActivityBelow(r);
2070 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002071 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2072 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002073 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002074 }
2075 } finally {
2076 Binder.restoreCallingIdentity(origId);
2077 }
2078 }
2079
2080 @Override
2081 public void notifyActivityDrawn(IBinder token) {
2082 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2083 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002084 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002086 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002087 }
2088 }
2089 }
2090
2091 @Override
2092 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2093 synchronized (mGlobalLock) {
2094 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2095 if (r == null) {
2096 return;
2097 }
2098 r.reportFullyDrawnLocked(restoredFromBundle);
2099 }
2100 }
2101
2102 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002103 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002104 synchronized (mGlobalLock) {
2105 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002106 if (stack != null) {
2107 final int displayId = stack.getDisplayId();
2108 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002109 }
2110 return DEFAULT_DISPLAY;
2111 }
2112 }
2113
2114 @Override
2115 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002116 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002117 long ident = Binder.clearCallingIdentity();
2118 try {
2119 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002120 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002121 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002122 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002123 }
2124 return null;
2125 }
2126 } finally {
2127 Binder.restoreCallingIdentity(ident);
2128 }
2129 }
2130
2131 @Override
2132 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002133 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002134 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2135 final long callingId = Binder.clearCallingIdentity();
2136 try {
2137 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002138 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002139 if (stack == null) {
2140 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2141 return;
2142 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002143 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002144 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002145 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002146 }
2147 }
2148 } finally {
2149 Binder.restoreCallingIdentity(callingId);
2150 }
2151 }
2152
2153 @Override
2154 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002155 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002156 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2157 final long callingId = Binder.clearCallingIdentity();
2158 try {
2159 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002160 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002161 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002162 if (task == null) {
2163 return;
2164 }
2165 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002166 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002167 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002168 }
2169 }
2170 } finally {
2171 Binder.restoreCallingIdentity(callingId);
2172 }
2173 }
2174
2175 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002176 public void restartActivityProcessIfVisible(IBinder activityToken) {
2177 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2178 final long callingId = Binder.clearCallingIdentity();
2179 try {
2180 synchronized (mGlobalLock) {
2181 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2182 if (r == null) {
2183 return;
2184 }
2185 r.restartProcessIfVisible();
2186 }
2187 } finally {
2188 Binder.restoreCallingIdentity(callingId);
2189 }
2190 }
2191
2192 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002193 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002194 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002195 synchronized (mGlobalLock) {
2196 final long ident = Binder.clearCallingIdentity();
2197 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002198 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002199 "remove-task");
2200 } finally {
2201 Binder.restoreCallingIdentity(ident);
2202 }
2203 }
2204 }
2205
2206 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002207 public void removeAllVisibleRecentTasks() {
2208 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2209 synchronized (mGlobalLock) {
2210 final long ident = Binder.clearCallingIdentity();
2211 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002212 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002213 } finally {
2214 Binder.restoreCallingIdentity(ident);
2215 }
2216 }
2217 }
2218
2219 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002220 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2221 synchronized (mGlobalLock) {
2222 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2223 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002224 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002225 }
2226 }
2227 return false;
2228 }
2229
2230 @Override
2231 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2232 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002233
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002234 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002235 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2236 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002237 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002238 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002239 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002240 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002241 }
2242 }
2243
2244 /**
2245 * Attempts to move a task backwards in z-order (the order of activities within the task is
2246 * unchanged).
2247 *
2248 * There are several possible results of this call:
2249 * - if the task is locked, then we will show the lock toast
2250 * - if there is a task behind the provided task, then that task is made visible and resumed as
2251 * this task is moved to the back
2252 * - otherwise, if there are no other tasks in the stack:
2253 * - if this task is in the pinned stack, then we remove the stack completely, which will
2254 * have the effect of moving the task to the top or bottom of the fullscreen stack
2255 * (depending on whether it is visible)
2256 * - otherwise, we simply return home and hide this task
2257 *
2258 * @param token A reference to the activity we wish to move
2259 * @param nonRoot If false then this only works if the activity is the root
2260 * of a task; if true it will work for any activity in a task.
2261 * @return Returns true if the move completed, false if not.
2262 */
2263 @Override
2264 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002265 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002266 synchronized (mGlobalLock) {
2267 final long origId = Binder.clearCallingIdentity();
2268 try {
2269 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002270 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002271 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002272 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002273 }
2274 } finally {
2275 Binder.restoreCallingIdentity(origId);
2276 }
2277 }
2278 return false;
2279 }
2280
2281 @Override
2282 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002283 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002284 long ident = Binder.clearCallingIdentity();
2285 Rect rect = new Rect();
2286 try {
2287 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002288 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002289 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2290 if (task == null) {
2291 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2292 return rect;
2293 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002294 if (task.getParent() != null) {
2295 rect.set(task.getBounds());
2296 } else if (task.mLastNonFullscreenBounds != null) {
2297 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002298 }
2299 }
2300 } finally {
2301 Binder.restoreCallingIdentity(ident);
2302 }
2303 return rect;
2304 }
2305
2306 @Override
2307 public ActivityManager.TaskDescription getTaskDescription(int id) {
2308 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002309 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002310 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002311 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002312 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2313 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002314 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002315 }
2316 }
2317 return null;
2318 }
2319
2320 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002321 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002322 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08002323 return setTaskWindowingModeSplitScreenPrimary(taskId, toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002324 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002325 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002326 synchronized (mGlobalLock) {
2327 final long ident = Binder.clearCallingIdentity();
2328 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002329 if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2330 return setTaskWindowingModeSplitScreen(taskId, windowingMode, toTop);
2331 }
Louis Chang149d5c82019-12-30 09:47:39 +08002332 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002333 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002334 if (task == null) {
2335 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002336 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002337 }
2338
2339 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2340 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2341
2342 if (!task.isActivityTypeStandardOrUndefined()) {
2343 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2344 + " non-standard task " + taskId + " to windowing mode="
2345 + windowingMode);
2346 }
2347
2348 final ActivityStack stack = task.getStack();
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002349 // Convert some windowing-mode changes into root-task reparents for split-screen.
2350 if (stack.getTile() != null) {
2351 stack.getDisplay().onSplitScreenModeDismissed();
2352 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002353 if (toTop) {
2354 stack.moveToFront("setTaskWindowingMode", task);
2355 }
2356 stack.setWindowingMode(windowingMode);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002357 stack.getDisplay().ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2358 true /* notifyClients */);
Winson Chung7ccc6812020-01-23 16:15:10 -08002359 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002360 } finally {
2361 Binder.restoreCallingIdentity(ident);
2362 }
2363 }
2364 }
2365
2366 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002367 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002368 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002369 ActivityRecord r = getCallingRecordLocked(token);
2370 return r != null ? r.info.packageName : null;
2371 }
2372 }
2373
2374 @Override
2375 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002376 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002377 ActivityRecord r = getCallingRecordLocked(token);
2378 return r != null ? r.intent.getComponent() : null;
2379 }
2380 }
2381
2382 private ActivityRecord getCallingRecordLocked(IBinder token) {
2383 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2384 if (r == null) {
2385 return null;
2386 }
2387 return r.resultTo;
2388 }
2389
2390 @Override
2391 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002392 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002393
2394 synchronized (mGlobalLock) {
2395 final long origId = Binder.clearCallingIdentity();
2396 try {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002397 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
2398 if (topFocusedStack != null) {
2399 topFocusedStack.unhandledBackLocked();
2400 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002401 } finally {
2402 Binder.restoreCallingIdentity(origId);
2403 }
2404 }
2405 }
2406
Mark Renouf446251d2019-04-26 10:22:41 -04002407 @Override
2408 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2409 synchronized (mGlobalLock) {
2410 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2411 if (r == null) {
2412 return;
2413 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002414 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002415 if (stack != null && stack.isSingleTaskInstance()) {
2416 // Single-task stacks are used for activities which are presented in floating
2417 // windows above full screen activities. Instead of directly finishing the
2418 // task, a task change listener is used to notify SystemUI so the action can be
2419 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002420 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002421 mTaskChangeNotificationController
2422 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2423 } else {
2424 try {
2425 callback.requestFinish();
2426 } catch (RemoteException e) {
2427 Slog.e(TAG, "Failed to invoke request finish callback", e);
2428 }
2429 }
2430 }
2431 }
2432
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002433 /**
2434 * TODO: Add mController hook
2435 */
2436 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002437 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2438 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002439 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002440
2441 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2442 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002443 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2444 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002445 }
2446 }
2447
Ricky Waiaca8a772019-04-04 16:01:06 +01002448 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2449 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002450 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002451 final int callingPid = Binder.getCallingPid();
2452 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002453 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002454 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002455 SafeActivityOptions.abort(options);
2456 return;
2457 }
2458 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002459 WindowProcessController callerApp = null;
2460 if (appThread != null) {
2461 callerApp = getProcessController(appThread);
2462 }
2463 final ActivityStarter starter = getActivityStartController().obtainStarter(
2464 null /* intent */, "moveTaskToFront");
2465 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
Galia Peycheva6861e912019-08-21 10:20:23 +02002466 -1, callerApp, null, false, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002467 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002468 return;
2469 }
2470 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002471 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002472 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002473 if (task == null) {
2474 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002475 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002476 return;
2477 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002478 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002479 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002480 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002481 return;
2482 }
2483 ActivityOptions realOptions = options != null
2484 ? options.getOptions(mStackSupervisor)
2485 : null;
2486 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2487 false /* forceNonResizable */);
2488
Wale Ogunwale21e06482019-11-18 05:14:15 -08002489 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002490 if (topActivity != null) {
2491
2492 // We are reshowing a task, use a starting window to hide the initial draw delay
2493 // so the transition can start earlier.
2494 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2495 true /* taskSwitch */, fromRecents);
2496 }
2497 } finally {
2498 Binder.restoreCallingIdentity(origId);
2499 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002500 }
2501
Ricky Waiaca8a772019-04-04 16:01:06 +01002502 /**
2503 * Return true if callingUid is system, or packageName belongs to that callingUid.
2504 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002505 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002506 try {
2507 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2508 if (packageName == null) {
2509 return false;
2510 }
2511 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2512 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2513 UserHandle.getUserId(callingUid));
2514 return UserHandle.isSameApp(callingUid, uid);
2515 }
2516 } catch (RemoteException e) {
2517 // Should not happen
2518 }
2519 return true;
2520 }
2521
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002522 /**
2523 * Checks that the provided package name matches the current calling UID, throws a security
2524 * exception if it doesn't.
2525 */
2526 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2527 final int callingUid = Binder.getCallingUid();
2528 if (isSameApp(callingUid, packageName)) {
2529 return;
2530 }
2531 final String msg = "Permission Denial: package=" + packageName
2532 + " does not belong to uid=" + callingUid;
2533 Slog.w(TAG, msg);
2534 throw new SecurityException(msg);
2535 }
2536
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002537 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2538 int callingPid, int callingUid, String name) {
2539 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2540 return true;
2541 }
2542
2543 if (getRecentTasks().isCallerRecents(sourceUid)) {
2544 return true;
2545 }
2546
2547 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2548 if (perm == PackageManager.PERMISSION_GRANTED) {
2549 return true;
2550 }
2551 if (checkAllowAppSwitchUid(sourceUid)) {
2552 return true;
2553 }
2554
2555 // If the actual IPC caller is different from the logical source, then
2556 // also see if they are allowed to control app switches.
2557 if (callingUid != -1 && callingUid != sourceUid) {
2558 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2559 if (perm == PackageManager.PERMISSION_GRANTED) {
2560 return true;
2561 }
2562 if (checkAllowAppSwitchUid(callingUid)) {
2563 return true;
2564 }
2565 }
2566
2567 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2568 return false;
2569 }
2570
2571 private boolean checkAllowAppSwitchUid(int uid) {
2572 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2573 if (types != null) {
2574 for (int i = types.size() - 1; i >= 0; i--) {
2575 if (types.valueAt(i).intValue() == uid) {
2576 return true;
2577 }
2578 }
2579 }
2580 return false;
2581 }
2582
2583 @Override
2584 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2585 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2586 "setActivityController()");
2587 synchronized (mGlobalLock) {
2588 mController = controller;
2589 mControllerIsAMonkey = imAMonkey;
2590 Watchdog.getInstance().setActivityController(controller);
2591 }
2592 }
2593
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002594 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002595 synchronized (mGlobalLock) {
2596 return mController != null && mControllerIsAMonkey;
2597 }
2598 }
2599
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002600 @Override
2601 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2602 synchronized (mGlobalLock) {
2603 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2604 }
2605 }
2606
2607 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002608 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2609 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2610 }
2611
2612 @Override
2613 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2614 @WindowConfiguration.ActivityType int ignoreActivityType,
2615 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2616 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002617 final int callingPid = Binder.getCallingPid();
2618 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002619 final int[] profileIds = getUserManager().getProfileIds(
2620 UserHandle.getUserId(callingUid), true);
2621 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2622 for (int i = 0; i < profileIds.length; i++) {
2623 callingProfileIds.add(profileIds[i]);
2624 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002625 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2626
2627 synchronized (mGlobalLock) {
2628 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2629
Nicholas Sauer0259e532019-08-30 08:24:55 -07002630 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002631 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002632 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002633 }
2634
2635 return list;
2636 }
2637
2638 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002639 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2640 synchronized (mGlobalLock) {
2641 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002642 try {
2643 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2644 if (r == null) return;
2645
2646 final PooledConsumer c = PooledLambda.obtainConsumer(
2647 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2648 r, resultWho, requestCode);
2649 // TODO: This should probably only loop over the task since you need to be in the
2650 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002651 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002652 c.recycle();
2653
2654 updateOomAdj();
2655 } finally {
2656 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002657 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002658 }
2659 }
2660
2661 @Override
2662 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002663 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002664 ActivityStack stack = ActivityRecord.getStackLocked(token);
2665 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002666 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002667 }
2668 return false;
2669 }
2670 }
2671
2672 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002673 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002674 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002675 synchronized (mGlobalLock) {
2676 final long ident = Binder.clearCallingIdentity();
2677 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002678 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002679 if (task == null) {
2680 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2681 return;
2682 }
2683
2684 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2685 + " to stackId=" + stackId + " toTop=" + toTop);
2686
Louis Chang149d5c82019-12-30 09:47:39 +08002687 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002688 if (stack == null) {
2689 throw new IllegalStateException(
2690 "moveTaskToStack: No stack for stackId=" + stackId);
2691 }
2692 if (!stack.isActivityTypeStandardOrUndefined()) {
2693 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2694 + taskId + " to stack " + stackId);
2695 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002696 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2697 "moveTaskToStack");
2698 } finally {
2699 Binder.restoreCallingIdentity(ident);
2700 }
2701 }
2702 }
2703
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002704 /**
2705 * Moves the specified task to the primary-split-screen stack.
2706 *
2707 * @param taskId Id of task to move.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002708 * @param toTop If the task and stack should be moved to the top.
Winson Chung7ccc6812020-01-23 16:15:10 -08002709 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002710 */
2711 @Override
Evan Rosky73a7fe92019-11-18 18:28:01 -08002712 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002713 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002714 "setTaskWindowingModeSplitScreenPrimary()");
2715 synchronized (mGlobalLock) {
2716 final long ident = Binder.clearCallingIdentity();
2717 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002718 return setTaskWindowingModeSplitScreen(taskId, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY,
2719 toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002720 } finally {
2721 Binder.restoreCallingIdentity(ident);
2722 }
2723 }
2724 }
2725
2726 /**
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002727 * Moves the specified task into a split-screen tile.
2728 */
2729 private boolean setTaskWindowingModeSplitScreen(int taskId, int windowingMode, boolean toTop) {
2730 if (!WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2731 throw new IllegalArgumentException("Calling setTaskWindowingModeSplitScreen with non"
2732 + "split-screen mode: " + windowingMode);
2733 }
2734 if (isInLockTaskMode()) {
2735 Slog.w(TAG, "setTaskWindowingModeSplitScreen: Is in lock task mode="
2736 + getLockTaskModeState());
2737 return false;
2738 }
2739
2740 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2741 MATCH_TASK_IN_STACKS_ONLY);
2742 if (task == null) {
2743 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2744 return false;
2745 }
2746 if (!task.isActivityTypeStandardOrUndefined()) {
2747 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2748 + " non-standard task " + taskId + " to split-screen windowing mode");
2749 }
Wale Ogunwale0d465192020-01-23 19:14:44 -08002750 if (!task.supportsSplitScreenWindowingMode()) {
2751 return false;
2752 }
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002753
2754 final int prevMode = task.getWindowingMode();
Wale Ogunwale0d465192020-01-23 19:14:44 -08002755 moveTaskToSplitScreenPrimaryTile(task, toTop);
2756 return prevMode != task.getWindowingMode();
2757 }
2758
2759 void moveTaskToSplitScreenPrimaryTile(Task task, boolean toTop) {
2760 ActivityStack stack = task.getStack();
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002761 TaskTile tile = null;
2762 for (int i = stack.getDisplay().getStackCount() - 1; i >= 0; --i) {
2763 tile = stack.getDisplay().getStackAt(i).asTile();
2764 if (tile != null && tile.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2765 break;
2766 }
2767 }
2768 if (tile == null) {
2769 throw new IllegalStateException("Can't enter split without associated tile");
2770 }
2771 WindowContainerTransaction wct = new WindowContainerTransaction();
2772 wct.reparent(stack.mRemoteToken, tile.mRemoteToken, toTop);
2773 mTaskOrganizerController.applyContainerTransaction(wct, null);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002774 }
2775
2776 /**
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002777 * Removes stacks in the input windowing modes from the system if they are of activity type
2778 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2779 */
2780 @Override
2781 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002782 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002783 "removeStacksInWindowingModes()");
2784
2785 synchronized (mGlobalLock) {
2786 final long ident = Binder.clearCallingIdentity();
2787 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002788 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002789 } finally {
2790 Binder.restoreCallingIdentity(ident);
2791 }
2792 }
2793 }
2794
2795 @Override
2796 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002797 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002798 "removeStacksWithActivityTypes()");
2799
2800 synchronized (mGlobalLock) {
2801 final long ident = Binder.clearCallingIdentity();
2802 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002803 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002804 } finally {
2805 Binder.restoreCallingIdentity(ident);
2806 }
2807 }
2808 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809
2810 @Override
2811 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2812 int userId) {
2813 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002814 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2815 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002816 callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002817 synchronized (mGlobalLock) {
Winson Chung66b08f02020-03-03 14:32:35 -08002818 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, userId, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002819 }
2820 }
2821
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002822 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002823 @Override
2824 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002825 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 long ident = Binder.clearCallingIdentity();
2827 try {
2828 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002829 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002830 }
2831 } finally {
2832 Binder.restoreCallingIdentity(ident);
2833 }
2834 }
2835
2836 @Override
2837 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002838 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002839 long ident = Binder.clearCallingIdentity();
2840 try {
2841 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002842 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002843 }
2844 } finally {
2845 Binder.restoreCallingIdentity(ident);
2846 }
2847 }
2848
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002849 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002850 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002851 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2852 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2853 long ident = Binder.clearCallingIdentity();
2854 try {
2855 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002856 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002857 }
2858 } finally {
2859 Binder.restoreCallingIdentity(ident);
2860 }
2861 }
2862
2863 @Override
2864 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2865 int displayId) {
2866 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2867 long ident = Binder.clearCallingIdentity();
2868 try {
2869 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002870 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002871 }
2872 } finally {
2873 Binder.restoreCallingIdentity(ident);
2874 }
2875 }
2876
2877 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002878 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002879 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880 final long callingUid = Binder.getCallingUid();
2881 final long origId = Binder.clearCallingIdentity();
2882 try {
2883 synchronized (mGlobalLock) {
2884 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002885 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002886 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2887 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2888 }
2889 } finally {
2890 Binder.restoreCallingIdentity(origId);
2891 }
2892 }
2893
2894 @Override
2895 public void startLockTaskModeByToken(IBinder token) {
2896 synchronized (mGlobalLock) {
2897 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2898 if (r == null) {
2899 return;
2900 }
Louis Changcdec0802019-11-11 11:45:07 +08002901 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002902 }
2903 }
2904
2905 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002906 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002907 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002908 // This makes inner call to look as if it was initiated by system.
2909 long ident = Binder.clearCallingIdentity();
2910 try {
2911 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002912 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002913 MATCH_TASK_IN_STACKS_ONLY);
2914 if (task == null) {
2915 return;
2916 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002917
2918 // When starting lock task mode the stack must be in front and focused
2919 task.getStack().moveToFront("startSystemLockTaskMode");
2920 startLockTaskModeLocked(task, true /* isSystemCaller */);
2921 }
2922 } finally {
2923 Binder.restoreCallingIdentity(ident);
2924 }
2925 }
2926
2927 @Override
2928 public void stopLockTaskModeByToken(IBinder token) {
2929 synchronized (mGlobalLock) {
2930 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2931 if (r == null) {
2932 return;
2933 }
Louis Changcdec0802019-11-11 11:45:07 +08002934 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002935 }
2936 }
2937
2938 /**
2939 * This API should be called by SystemUI only when user perform certain action to dismiss
2940 * lock task mode. We should only dismiss pinned lock task mode in this case.
2941 */
2942 @Override
2943 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002944 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002945 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2946 }
2947
Louis Changcdec0802019-11-11 11:45:07 +08002948 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002949 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2950 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2951 return;
2952 }
2953
Louis Chang149d5c82019-12-30 09:47:39 +08002954 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002955 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002956 throw new IllegalArgumentException("Invalid task, not in foreground");
2957 }
2958
2959 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2960 // system or a specific app.
2961 // * System-initiated requests will only start the pinned mode (screen pinning)
2962 // * App-initiated requests
2963 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2964 // - will start the pinned mode, otherwise
2965 final int callingUid = Binder.getCallingUid();
2966 long ident = Binder.clearCallingIdentity();
2967 try {
2968 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002969 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002970
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002971 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002972 } finally {
2973 Binder.restoreCallingIdentity(ident);
2974 }
2975 }
2976
Louis Changcdec0802019-11-11 11:45:07 +08002977 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002978 final int callingUid = Binder.getCallingUid();
2979 long ident = Binder.clearCallingIdentity();
2980 try {
2981 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002982 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002983 }
2984 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2985 // task and jumping straight into a call in the case of emergency call back.
2986 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2987 if (tm != null) {
2988 tm.showInCallScreen(false);
2989 }
2990 } finally {
2991 Binder.restoreCallingIdentity(ident);
2992 }
2993 }
2994
2995 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002996 public void updateLockTaskPackages(int userId, String[] packages) {
2997 final int callingUid = Binder.getCallingUid();
2998 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2999 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
3000 "updateLockTaskPackages()");
3001 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08003002 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003003 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
3004 + Arrays.toString(packages));
3005 getLockTaskController().updateLockTaskPackages(userId, packages);
3006 }
3007 }
3008
3009 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003010 public boolean isInLockTaskMode() {
3011 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3012 }
3013
3014 @Override
3015 public int getLockTaskModeState() {
3016 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003017 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003018 }
3019 }
3020
3021 @Override
3022 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3023 synchronized (mGlobalLock) {
3024 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3025 if (r != null) {
3026 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003027 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003028 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003029 }
3030 }
3031 }
3032
3033 @Override
3034 public Bundle getActivityOptions(IBinder token) {
3035 final long origId = Binder.clearCallingIdentity();
3036 try {
3037 synchronized (mGlobalLock) {
3038 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3039 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003040 final ActivityOptions activityOptions = r.takeOptionsLocked(
3041 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003042 return activityOptions == null ? null : activityOptions.toBundle();
3043 }
3044 return null;
3045 }
3046 } finally {
3047 Binder.restoreCallingIdentity(origId);
3048 }
3049 }
3050
3051 @Override
3052 public List<IBinder> getAppTasks(String callingPackage) {
3053 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003054 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003055 long ident = Binder.clearCallingIdentity();
3056 try {
3057 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003058 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003059 }
3060 } finally {
3061 Binder.restoreCallingIdentity(ident);
3062 }
3063 }
3064
3065 @Override
3066 public void finishVoiceTask(IVoiceInteractionSession session) {
3067 synchronized (mGlobalLock) {
3068 final long origId = Binder.clearCallingIdentity();
3069 try {
3070 // TODO: VI Consider treating local voice interactions and voice tasks
3071 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003072 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003073 } finally {
3074 Binder.restoreCallingIdentity(origId);
3075 }
3076 }
3077
3078 }
3079
3080 @Override
3081 public boolean isTopOfTask(IBinder token) {
3082 synchronized (mGlobalLock) {
3083 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003084 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003085 }
3086 }
3087
3088 @Override
3089 public void notifyLaunchTaskBehindComplete(IBinder token) {
3090 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3091 }
3092
3093 @Override
3094 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003095 mH.post(() -> {
3096 synchronized (mGlobalLock) {
3097 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003098 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003099 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003100 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003101 } catch (RemoteException e) {
3102 }
3103 }
3104 }
3105
3106 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003107 }
3108
3109 /** Called from an app when assist data is ready. */
3110 @Override
3111 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3112 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003113 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003114 synchronized (pae) {
3115 pae.result = extras;
3116 pae.structure = structure;
3117 pae.content = content;
3118 if (referrer != null) {
3119 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3120 }
3121 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003122 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003123 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003124 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003125 structure.setHomeActivity(pae.isHome);
3126 }
3127 pae.haveResult = true;
3128 pae.notifyAll();
3129 if (pae.intent == null && pae.receiver == null) {
3130 // Caller is just waiting for the result.
3131 return;
3132 }
3133 }
3134 // We are now ready to launch the assist activity.
3135 IAssistDataReceiver sendReceiver = null;
3136 Bundle sendBundle = null;
3137 synchronized (mGlobalLock) {
3138 buildAssistBundleLocked(pae, extras);
3139 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003140 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003141 if (!exists) {
3142 // Timed out.
3143 return;
3144 }
3145
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003146 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003147 // Caller wants result sent back to them.
3148 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003149 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003150 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003151 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3152 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003153 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3154 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3155 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3156 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3157 }
3158 }
3159 if (sendReceiver != null) {
3160 try {
3161 sendReceiver.onHandleAssistData(sendBundle);
3162 } catch (RemoteException e) {
3163 }
3164 return;
3165 }
3166
3167 final long ident = Binder.clearCallingIdentity();
3168 try {
3169 if (TextUtils.equals(pae.intent.getAction(),
3170 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003171 // Start voice interaction through VoiceInteractionManagerService.
3172 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3173 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003174 } else {
3175 pae.intent.replaceExtras(pae.extras);
3176 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3177 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3178 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003179 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003180
3181 try {
3182 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3183 } catch (ActivityNotFoundException e) {
3184 Slog.w(TAG, "No activity to handle assist action.", e);
3185 }
3186 }
3187 } finally {
3188 Binder.restoreCallingIdentity(ident);
3189 }
3190 }
3191
3192 @Override
3193 public int addAppTask(IBinder activityToken, Intent intent,
3194 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3195 final int callingUid = Binder.getCallingUid();
3196 final long callingIdent = Binder.clearCallingIdentity();
3197
3198 try {
3199 synchronized (mGlobalLock) {
3200 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3201 if (r == null) {
3202 throw new IllegalArgumentException("Activity does not exist; token="
3203 + activityToken);
3204 }
3205 ComponentName comp = intent.getComponent();
3206 if (comp == null) {
3207 throw new IllegalArgumentException("Intent " + intent
3208 + " must specify explicit component");
3209 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003210 if (thumbnail.getWidth() != mThumbnailWidth
3211 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003212 throw new IllegalArgumentException("Bad thumbnail size: got "
3213 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003214 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003215 }
3216 if (intent.getSelector() != null) {
3217 intent.setSelector(null);
3218 }
3219 if (intent.getSourceBounds() != null) {
3220 intent.setSourceBounds(null);
3221 }
3222 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3223 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3224 // The caller has added this as an auto-remove task... that makes no
3225 // sense, so turn off auto-remove.
3226 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3227 }
3228 }
3229 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3230 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3231 if (ainfo.applicationInfo.uid != callingUid) {
3232 throw new SecurityException(
3233 "Can't add task for another application: target uid="
3234 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3235 }
3236
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003237 final ActivityStack stack = r.getRootTask();
Wale Ogunwale0d465192020-01-23 19:14:44 -08003238 final Task task = stack.getDisplay().createStack(stack.getWindowingMode(),
3239 stack.getActivityType(), !ON_TOP, ainfo, intent);
3240
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003241 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003242 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003243 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003244 return INVALID_TASK_ID;
3245 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003246 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003247
3248 // TODO: Send the thumbnail to WM to store it.
3249
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003250 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003251 }
3252 } finally {
3253 Binder.restoreCallingIdentity(callingIdent);
3254 }
3255 }
3256
3257 @Override
3258 public Point getAppTaskThumbnailSize() {
3259 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003260 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003261 }
3262 }
3263
3264 @Override
3265 public void setTaskResizeable(int taskId, int resizeableMode) {
3266 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003267 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003268 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3269 if (task == null) {
3270 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3271 return;
3272 }
3273 task.setResizeMode(resizeableMode);
3274 }
3275 }
3276
3277 @Override
3278 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003279 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003280 long ident = Binder.clearCallingIdentity();
3281 try {
3282 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003283 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003284 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003285 if (task == null) {
3286 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3287 return;
3288 }
3289 // Place the task in the right stack if it isn't there already based on
3290 // the requested bounds.
3291 // The stack transition logic is:
3292 // - a null bounds on a freeform task moves that task to fullscreen
3293 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3294 // that task to freeform
3295 // - otherwise the task is not moved
3296 ActivityStack stack = task.getStack();
3297 if (!task.getWindowConfiguration().canResizeTask()) {
3298 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3299 }
3300 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3301 stack = stack.getDisplay().getOrCreateStack(
3302 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3303 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3304 stack = stack.getDisplay().getOrCreateStack(
3305 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3306 }
3307
3308 // Reparent the task to the right stack if necessary
3309 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3310 if (stack != task.getStack()) {
3311 // Defer resume until the task is resized below
3312 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3313 DEFER_RESUME, "resizeTask");
3314 preserveWindow = false;
3315 }
3316
3317 // After reparenting (which only resizes the task to the stack bounds), resize the
3318 // task to the actual bounds provided
3319 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3320 }
3321 } finally {
3322 Binder.restoreCallingIdentity(ident);
3323 }
3324 }
3325
3326 @Override
3327 public boolean releaseActivityInstance(IBinder token) {
3328 synchronized (mGlobalLock) {
3329 final long origId = Binder.clearCallingIdentity();
3330 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003331 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3332 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003333 return false;
3334 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003335 r.destroyImmediately(true /* removeFromApp */, "app-req");
3336 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003337 } finally {
3338 Binder.restoreCallingIdentity(origId);
3339 }
3340 }
3341 }
3342
3343 @Override
3344 public void releaseSomeActivities(IApplicationThread appInt) {
3345 synchronized (mGlobalLock) {
3346 final long origId = Binder.clearCallingIdentity();
3347 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003348 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003349 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003350 } finally {
3351 Binder.restoreCallingIdentity(origId);
3352 }
3353 }
3354 }
3355
3356 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003357 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003358 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003359 != PackageManager.PERMISSION_GRANTED) {
3360 throw new SecurityException("Requires permission "
3361 + android.Manifest.permission.DEVICE_POWER);
3362 }
3363
3364 synchronized (mGlobalLock) {
3365 long ident = Binder.clearCallingIdentity();
3366 if (mKeyguardShown != keyguardShowing) {
3367 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003368 final Message msg = PooledLambda.obtainMessage(
3369 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3370 keyguardShowing);
3371 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003372 }
3373 try {
wilsonshih177261f2019-02-22 12:02:18 +08003374 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003375 } finally {
3376 Binder.restoreCallingIdentity(ident);
3377 }
3378 }
3379
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003380 mH.post(() -> {
3381 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3382 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3383 }
3384 });
3385 }
3386
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003387 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003388 mH.post(() -> {
3389 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3390 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3391 }
3392 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003393 }
3394
3395 @Override
3396 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003397 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3398 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003399
3400 final File passedIconFile = new File(filePath);
3401 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3402 passedIconFile.getName());
3403 if (!legitIconFile.getPath().equals(filePath)
3404 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3405 throw new IllegalArgumentException("Bad file path: " + filePath
3406 + " passed for userId " + userId);
3407 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003408 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003409 }
3410
3411 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003413 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003414 synchronized (mGlobalLock) {
3415 final long ident = Binder.clearCallingIdentity();
3416 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003417 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003418 if (stack == null) {
3419 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3420 return;
3421 }
3422 if (!stack.isActivityTypeStandardOrUndefined()) {
3423 throw new IllegalArgumentException(
3424 "Removing non-standard stack is not allowed.");
3425 }
3426 mStackSupervisor.removeStack(stack);
3427 } finally {
3428 Binder.restoreCallingIdentity(ident);
3429 }
3430 }
3431 }
3432
3433 @Override
3434 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003435 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003436
3437 synchronized (mGlobalLock) {
3438 final long ident = Binder.clearCallingIdentity();
3439 try {
3440 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3441 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003442 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003443 } finally {
3444 Binder.restoreCallingIdentity(ident);
3445 }
3446 }
3447 }
3448
3449 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003450 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003451 synchronized (mGlobalLock) {
3452 long ident = Binder.clearCallingIdentity();
3453 try {
3454 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3455 if (r == null) {
3456 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003457 "toggleFreeformWindowingMode: No activity record matching token="
3458 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003459 }
3460
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003461 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003462 if (stack == null) {
3463 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3464 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003465 }
3466
Yunfan Chend967af82019-01-17 18:30:18 +09003467 if (!stack.inFreeformWindowingMode()
3468 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3469 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3470 + "toggle between fullscreen and freeform.");
3471 }
3472
3473 if (stack.inFreeformWindowingMode()) {
3474 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003475 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003476 throw new IllegalStateException("Size-compat windows are currently not"
3477 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003478 } else if (stack.getParent().inFreeformWindowingMode()) {
3479 // If the window is on a freeform display, set it to undefined. It will be
3480 // resolved to freeform and it can adjust windowing mode when the display mode
3481 // changes in runtime.
3482 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003483 } else {
3484 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3485 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003486 } finally {
3487 Binder.restoreCallingIdentity(ident);
3488 }
3489 }
3490 }
3491
3492 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3493 @Override
3494 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003495 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003496 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003497 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003498 }
3499
3500 /** Unregister a task stack listener so that it stops receiving callbacks. */
3501 @Override
3502 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003503 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003504 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003505 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003506 }
3507
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003508 @Override
3509 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3510 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3511 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3512 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3513 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3514 }
3515
3516 @Override
3517 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3518 IBinder activityToken, int flags) {
3519 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3520 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3521 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3522 }
3523
3524 @Override
3525 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3526 Bundle args) {
3527 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3528 true /* focused */, true /* newSessionId */, userHandle, args,
3529 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3530 }
3531
3532 @Override
3533 public Bundle getAssistContextExtras(int requestType) {
3534 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3535 null, null, true /* focused */, true /* newSessionId */,
3536 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3537 if (pae == null) {
3538 return null;
3539 }
3540 synchronized (pae) {
3541 while (!pae.haveResult) {
3542 try {
3543 pae.wait();
3544 } catch (InterruptedException e) {
3545 }
3546 }
3547 }
3548 synchronized (mGlobalLock) {
3549 buildAssistBundleLocked(pae, pae.result);
3550 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003551 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003552 }
3553 return pae.extras;
3554 }
3555
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003556 /**
3557 * Binder IPC calls go through the public entry point.
3558 * This can be called with or without the global lock held.
3559 */
3560 private static int checkCallingPermission(String permission) {
3561 return checkPermission(
3562 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3563 }
3564
3565 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003566 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003567 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3568 mAmInternal.enforceCallingPermission(permission, func);
3569 }
3570 }
3571
3572 @VisibleForTesting
3573 int checkGetTasksPermission(String permission, int pid, int uid) {
3574 return checkPermission(permission, pid, uid);
3575 }
3576
3577 static int checkPermission(String permission, int pid, int uid) {
3578 if (permission == null) {
3579 return PackageManager.PERMISSION_DENIED;
3580 }
3581 return checkComponentPermission(permission, pid, uid, -1, true);
3582 }
3583
Wale Ogunwale214f3482018-10-04 11:00:47 -07003584 public static int checkComponentPermission(String permission, int pid, int uid,
3585 int owningUid, boolean exported) {
3586 return ActivityManagerService.checkComponentPermission(
3587 permission, pid, uid, owningUid, exported);
3588 }
3589
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003590 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3591 if (getRecentTasks().isCallerRecents(callingUid)) {
3592 // Always allow the recents component to get tasks
3593 return true;
3594 }
3595
3596 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3597 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3598 if (!allowed) {
3599 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3600 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3601 // Temporary compatibility: some existing apps on the system image may
3602 // still be requesting the old permission and not switched to the new
3603 // one; if so, we'll still allow them full access. This means we need
3604 // to see if they are holding the old permission and are a system app.
3605 try {
3606 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3607 allowed = true;
3608 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3609 + " is using old GET_TASKS but privileged; allowing");
3610 }
3611 } catch (RemoteException e) {
3612 }
3613 }
3614 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3615 + " does not hold REAL_GET_TASKS; limiting output");
3616 }
3617 return allowed;
3618 }
3619
Nicholas Sauer0259e532019-08-30 08:24:55 -07003620 boolean isCrossUserAllowed(int pid, int uid) {
3621 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3622 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3623 }
3624
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003625 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3626 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3627 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3628 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003629 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003630 "enqueueAssistContext()");
3631
3632 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08003633 final ActivityStack stack = getTopDisplayFocusedStack();
3634 ActivityRecord activity = stack != null ? stack.getTopNonFinishingActivity() : null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003635 if (activity == null) {
3636 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3637 return null;
3638 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003639 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003640 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3641 return null;
3642 }
3643 if (focused) {
3644 if (activityToken != null) {
3645 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3646 if (activity != caller) {
3647 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3648 + " is not current top " + activity);
3649 return null;
3650 }
3651 }
3652 } else {
3653 activity = ActivityRecord.forTokenLocked(activityToken);
3654 if (activity == null) {
3655 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3656 + " couldn't be found");
3657 return null;
3658 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003659 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003660 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3661 return null;
3662 }
3663 }
3664
3665 PendingAssistExtras pae;
3666 Bundle extras = new Bundle();
3667 if (args != null) {
3668 extras.putAll(args);
3669 }
3670 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003671 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003672
3673 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3674 userHandle);
3675 pae.isHome = activity.isActivityTypeHome();
3676
3677 // Increment the sessionId if necessary
3678 if (newSessionId) {
3679 mViSessionId++;
3680 }
3681 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003682 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3683 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003684 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003685 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003686 } catch (RemoteException e) {
3687 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3688 return null;
3689 }
3690 return pae;
3691 }
3692 }
3693
3694 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3695 if (result != null) {
3696 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3697 }
3698 if (pae.hint != null) {
3699 pae.extras.putBoolean(pae.hint, true);
3700 }
3701 }
3702
3703 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3704 IAssistDataReceiver receiver;
3705 synchronized (mGlobalLock) {
3706 mPendingAssistExtras.remove(pae);
3707 receiver = pae.receiver;
3708 }
3709 if (receiver != null) {
3710 // Caller wants result sent back to them.
3711 Bundle sendBundle = new Bundle();
3712 // At least return the receiver extras
3713 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3714 try {
3715 pae.receiver.onHandleAssistData(sendBundle);
3716 } catch (RemoteException e) {
3717 }
3718 }
3719 }
3720
3721 public class PendingAssistExtras extends Binder implements Runnable {
3722 public final ActivityRecord activity;
3723 public boolean isHome;
3724 public final Bundle extras;
3725 public final Intent intent;
3726 public final String hint;
3727 public final IAssistDataReceiver receiver;
3728 public final int userHandle;
3729 public boolean haveResult = false;
3730 public Bundle result = null;
3731 public AssistStructure structure = null;
3732 public AssistContent content = null;
3733 public Bundle receiverExtras;
3734
3735 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3736 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3737 int _userHandle) {
3738 activity = _activity;
3739 extras = _extras;
3740 intent = _intent;
3741 hint = _hint;
3742 receiver = _receiver;
3743 receiverExtras = _receiverExtras;
3744 userHandle = _userHandle;
3745 }
3746
3747 @Override
3748 public void run() {
3749 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3750 synchronized (this) {
3751 haveResult = true;
3752 notifyAll();
3753 }
3754 pendingAssistExtrasTimedOut(this);
3755 }
3756 }
3757
3758 @Override
3759 public boolean isAssistDataAllowedOnCurrentActivity() {
3760 int userId;
3761 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003762 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003763 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3764 return false;
3765 }
3766
Wale Ogunwale21e06482019-11-18 05:14:15 -08003767 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003768 if (activity == null) {
3769 return false;
3770 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003771 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003772 }
3773 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3774 }
3775
3776 @Override
3777 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3778 long ident = Binder.clearCallingIdentity();
3779 try {
3780 synchronized (mGlobalLock) {
3781 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003782 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003783 if (top != caller) {
3784 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3785 + " is not current top " + top);
3786 return false;
3787 }
3788 if (!top.nowVisible) {
3789 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3790 + " is not visible");
3791 return false;
3792 }
3793 }
3794 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3795 token);
3796 } finally {
3797 Binder.restoreCallingIdentity(ident);
3798 }
3799 }
3800
3801 @Override
3802 public boolean isRootVoiceInteraction(IBinder token) {
3803 synchronized (mGlobalLock) {
3804 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3805 if (r == null) {
3806 return false;
3807 }
3808 return r.rootVoiceInteraction;
3809 }
3810 }
3811
Wale Ogunwalef6733932018-06-27 05:14:34 -07003812 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3813 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3814 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3815 if (activityToCallback == null) return;
3816 activityToCallback.setVoiceSessionLocked(voiceSession);
3817
3818 // Inform the activity
3819 try {
3820 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3821 voiceInteractor);
3822 long token = Binder.clearCallingIdentity();
3823 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003824 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003825 } finally {
3826 Binder.restoreCallingIdentity(token);
3827 }
3828 // TODO: VI Should we cache the activity so that it's easier to find later
3829 // rather than scan through all the stacks and activities?
3830 } catch (RemoteException re) {
3831 activityToCallback.clearVoiceSessionLocked();
3832 // TODO: VI Should this terminate the voice session?
3833 }
3834 }
3835
3836 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3837 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3838 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3839 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3840 boolean wasRunningVoice = mRunningVoice != null;
3841 mRunningVoice = session;
3842 if (!wasRunningVoice) {
3843 mVoiceWakeLock.acquire();
3844 updateSleepIfNeededLocked();
3845 }
3846 }
3847 }
3848
3849 void finishRunningVoiceLocked() {
3850 if (mRunningVoice != null) {
3851 mRunningVoice = null;
3852 mVoiceWakeLock.release();
3853 updateSleepIfNeededLocked();
3854 }
3855 }
3856
3857 @Override
3858 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3859 synchronized (mGlobalLock) {
3860 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3861 if (keepAwake) {
3862 mVoiceWakeLock.acquire();
3863 } else {
3864 mVoiceWakeLock.release();
3865 }
3866 }
3867 }
3868 }
3869
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003870 @Override
3871 public ComponentName getActivityClassForToken(IBinder token) {
3872 synchronized (mGlobalLock) {
3873 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3874 if (r == null) {
3875 return null;
3876 }
3877 return r.intent.getComponent();
3878 }
3879 }
3880
3881 @Override
3882 public String getPackageForToken(IBinder token) {
3883 synchronized (mGlobalLock) {
3884 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3885 if (r == null) {
3886 return null;
3887 }
3888 return r.packageName;
3889 }
3890 }
3891
3892 @Override
3893 public void showLockTaskEscapeMessage(IBinder token) {
3894 synchronized (mGlobalLock) {
3895 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3896 if (r == null) {
3897 return;
3898 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003899 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003900 }
3901 }
3902
3903 @Override
3904 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003905 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003906 final long token = Binder.clearCallingIdentity();
3907 try {
3908 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003909 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003910 }
3911 } finally {
3912 Binder.restoreCallingIdentity(token);
3913 }
3914 }
3915
3916 /**
3917 * Try to place task to provided position. The final position might be different depending on
3918 * current user and stacks state. The task will be moved to target stack if it's currently in
3919 * different stack.
3920 */
3921 @Override
3922 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003923 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003924 synchronized (mGlobalLock) {
3925 long ident = Binder.clearCallingIdentity();
3926 try {
3927 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3928 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003929 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003930 if (task == null) {
3931 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3932 + taskId);
3933 }
3934
Louis Chang149d5c82019-12-30 09:47:39 +08003935 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003936
3937 if (stack == null) {
3938 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3939 + stackId);
3940 }
3941 if (!stack.isActivityTypeStandardOrUndefined()) {
3942 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3943 + " the position of task " + taskId + " in/to non-standard stack");
3944 }
3945
3946 // TODO: Have the callers of this API call a separate reparent method if that is
3947 // what they intended to do vs. having this method also do reparenting.
3948 if (task.getStack() == stack) {
3949 // Change position in current stack.
3950 stack.positionChildAt(task, position);
3951 } else {
3952 // Reparent to new stack.
3953 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3954 !DEFER_RESUME, "positionTaskInStack");
3955 }
3956 } finally {
3957 Binder.restoreCallingIdentity(ident);
3958 }
3959 }
3960 }
3961
3962 @Override
3963 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3964 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3965 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003966 + Arrays.toString(horizontalSizeConfiguration) + " "
3967 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003968 synchronized (mGlobalLock) {
3969 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3970 if (record == null) {
3971 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3972 + "found for: " + token);
3973 }
3974 record.setSizeConfigurations(horizontalSizeConfiguration,
3975 verticalSizeConfigurations, smallestSizeConfigurations);
3976 }
3977 }
3978
3979 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003980 * Dismisses Pip
3981 * @param animate True if the dismissal should be animated.
3982 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3983 * default animation duration should be used.
3984 */
3985 @Override
3986 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003987 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003988 final long ident = Binder.clearCallingIdentity();
3989 try {
3990 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003991 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08003992 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003993 if (stack == null) {
3994 Slog.w(TAG, "dismissPip: pinned stack not found.");
3995 return;
3996 }
3997 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3998 throw new IllegalArgumentException("Stack: " + stack
3999 + " doesn't support animated resize.");
4000 }
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004001 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004002 }
4003 } finally {
4004 Binder.restoreCallingIdentity(ident);
4005 }
4006 }
4007
4008 @Override
4009 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004010 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004011 synchronized (mGlobalLock) {
4012 mSuppressResizeConfigChanges = suppress;
4013 }
4014 }
4015
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004016 @Override
4017 // TODO: API should just be about changing windowing modes...
4018 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004019 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004020 "moveTasksToFullscreenStack()");
4021 synchronized (mGlobalLock) {
4022 final long origId = Binder.clearCallingIdentity();
4023 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004024 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004025 if (stack != null){
4026 if (!stack.isActivityTypeStandardOrUndefined()) {
4027 throw new IllegalArgumentException(
4028 "You can't move tasks from non-standard stacks.");
4029 }
4030 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4031 }
4032 } finally {
4033 Binder.restoreCallingIdentity(origId);
4034 }
4035 }
4036 }
4037
4038 /**
4039 * Moves the top activity in the input stackId to the pinned stack.
4040 *
4041 * @param stackId Id of stack to move the top activity to pinned stack.
4042 * @param bounds Bounds to use for pinned stack.
4043 *
4044 * @return True if the top activity of the input stack was successfully moved to the pinned
4045 * stack.
4046 */
4047 @Override
4048 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004049 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004050 "moveTopActivityToPinnedStack()");
4051 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004052 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004053 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4054 + "Device doesn't support picture-in-picture mode");
4055 }
4056
4057 long ident = Binder.clearCallingIdentity();
4058 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004059 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004060 } finally {
4061 Binder.restoreCallingIdentity(ident);
4062 }
4063 }
4064 }
4065
4066 @Override
4067 public boolean isInMultiWindowMode(IBinder token) {
4068 final long origId = Binder.clearCallingIdentity();
4069 try {
4070 synchronized (mGlobalLock) {
4071 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4072 if (r == null) {
4073 return false;
4074 }
4075 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4076 return r.inMultiWindowMode();
4077 }
4078 } finally {
4079 Binder.restoreCallingIdentity(origId);
4080 }
4081 }
4082
4083 @Override
4084 public boolean isInPictureInPictureMode(IBinder token) {
4085 final long origId = Binder.clearCallingIdentity();
4086 try {
4087 synchronized (mGlobalLock) {
4088 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4089 }
4090 } finally {
4091 Binder.restoreCallingIdentity(origId);
4092 }
4093 }
4094
4095 private boolean isInPictureInPictureMode(ActivityRecord r) {
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004096 return r != null
4097 && r.getRootTask() != null
4098 && r.inPinnedWindowingMode()
4099 && r.getRootTask().isInStackLocked(r) != null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004100 }
4101
4102 @Override
4103 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4104 final long origId = Binder.clearCallingIdentity();
4105 try {
4106 synchronized (mGlobalLock) {
4107 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4108 "enterPictureInPictureMode", token, params);
4109
4110 // If the activity is already in picture in picture mode, then just return early
4111 if (isInPictureInPictureMode(r)) {
4112 return true;
4113 }
4114
4115 // Activity supports picture-in-picture, now check that we can enter PiP at this
4116 // point, if it is
4117 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4118 false /* beforeStopping */)) {
4119 return false;
4120 }
4121
4122 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004123 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004124 if (r.getParent() == null) {
4125 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4126 return;
4127 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004128 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004129 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004130 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4131 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4132 // Adjust the source bounds by the insets for the transition down
4133 final Rect sourceBounds = new Rect(
4134 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004135 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004136 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004137 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004138 stack.setPictureInPictureAspectRatio(aspectRatio);
4139 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004140 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4141 r.info.applicationInfo.uid, r.shortComponentName,
4142 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004143 logPictureInPictureArgs(params);
4144 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004145 };
4146
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004147 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004148 // If the keyguard is showing or occluded, then try and dismiss it before
4149 // entering picture-in-picture (this will prompt the user to authenticate if the
4150 // device is currently locked).
4151 dismissKeyguard(token, new KeyguardDismissCallback() {
4152 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004153 public void onDismissSucceeded() {
4154 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004155 }
4156 }, null /* message */);
4157 } else {
4158 // Enter picture in picture immediately otherwise
4159 enterPipRunnable.run();
4160 }
4161 return true;
4162 }
4163 } finally {
4164 Binder.restoreCallingIdentity(origId);
4165 }
4166 }
4167
4168 @Override
4169 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4170 final long origId = Binder.clearCallingIdentity();
4171 try {
4172 synchronized (mGlobalLock) {
4173 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4174 "setPictureInPictureParams", token, params);
4175
4176 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004177 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004178 if (r.inPinnedWindowingMode()) {
4179 // If the activity is already in picture-in-picture, update the pinned stack now
4180 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4181 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004182 final ActivityStack stack = r.getRootTask();
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004183 stack.setPictureInPictureAspectRatio(
4184 r.pictureInPictureArgs.getAspectRatio());
4185 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004186 }
4187 logPictureInPictureArgs(params);
4188 }
4189 } finally {
4190 Binder.restoreCallingIdentity(origId);
4191 }
4192 }
4193
4194 @Override
4195 public int getMaxNumPictureInPictureActions(IBinder token) {
4196 // Currently, this is a static constant, but later, we may change this to be dependent on
4197 // the context of the activity
4198 return 3;
4199 }
4200
4201 private void logPictureInPictureArgs(PictureInPictureParams params) {
4202 if (params.hasSetActions()) {
4203 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4204 params.getActions().size());
4205 }
4206 if (params.hasSetAspectRatio()) {
4207 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4208 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4209 MetricsLogger.action(lm);
4210 }
4211 }
4212
4213 /**
4214 * Checks the state of the system and the activity associated with the given {@param token} to
4215 * verify that picture-in-picture is supported for that activity.
4216 *
4217 * @return the activity record for the given {@param token} if all the checks pass.
4218 */
4219 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4220 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004221 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004222 throw new IllegalStateException(caller
4223 + ": Device doesn't support picture-in-picture mode.");
4224 }
4225
4226 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4227 if (r == null) {
4228 throw new IllegalStateException(caller
4229 + ": Can't find activity for token=" + token);
4230 }
4231
4232 if (!r.supportsPictureInPicture()) {
4233 throw new IllegalStateException(caller
4234 + ": Current activity does not support picture-in-picture.");
4235 }
4236
4237 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004238 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004239 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004240 final float minAspectRatio = mContext.getResources().getFloat(
4241 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4242 final float maxAspectRatio = mContext.getResources().getFloat(
4243 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4244 throw new IllegalArgumentException(String.format(caller
4245 + ": Aspect ratio is too extreme (must be between %f and %f).",
4246 minAspectRatio, maxAspectRatio));
4247 }
4248
4249 // Truncate the number of actions if necessary
4250 params.truncateActions(getMaxNumPictureInPictureActions(token));
4251
4252 return r;
4253 }
4254
4255 @Override
4256 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004257 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004258 synchronized (mGlobalLock) {
4259 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4260 if (r == null) {
4261 throw new IllegalArgumentException("Activity does not exist; token="
4262 + activityToken);
4263 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004264 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004265 }
4266 }
4267
Evan Rosky73a7fe92019-11-18 18:28:01 -08004268 // TODO(b/149338177): remove when CTS no-longer requires it
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004269 @Override
4270 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4271 Rect tempDockedTaskInsetBounds,
4272 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004273 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004274 long ident = Binder.clearCallingIdentity();
4275 try {
4276 synchronized (mGlobalLock) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08004277 final DisplayContent dc = mRootWindowContainer.getDefaultDisplay();
4278 TaskTile primary = null;
4279 TaskTile secondary = null;
4280 for (int i = dc.getStackCount() - 1; i >= 0; --i) {
4281 final TaskTile t = dc.getStackAt(i).asTile();
4282 if (t == null) {
4283 continue;
4284 }
4285 if (t.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
4286 primary = t;
4287 } else if (t.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY) {
4288 secondary = t;
4289 }
4290 }
4291 if (primary == null || secondary == null) {
4292 return;
4293 }
4294 final WindowContainerTransaction wct = new WindowContainerTransaction();
4295 final Rect primaryRect =
4296 tempDockedTaskInsetBounds != null ? tempDockedTaskInsetBounds
4297 : (tempDockedTaskBounds != null ? tempDockedTaskBounds
4298 : dockedBounds);
4299 wct.setBounds(primary.mRemoteToken, primaryRect);
4300 Rect otherRect = tempOtherTaskInsetBounds != null ? tempOtherTaskInsetBounds
4301 : tempOtherTaskBounds;
4302 if (otherRect == null) {
4303 // Temporary estimation... again this is just for tests.
4304 otherRect = new Rect(secondary.getBounds());
4305 if (dc.getBounds().width() > dc.getBounds().height()) {
4306 otherRect.left = primaryRect.right + 6;
4307 } else {
4308 otherRect.top = primaryRect.bottom + 6;
4309 }
4310 }
4311 wct.setBounds(secondary.mRemoteToken, otherRect);
4312 mTaskOrganizerController.applyContainerTransaction(wct, null /* organizer */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004313 }
4314 } finally {
4315 Binder.restoreCallingIdentity(ident);
4316 }
4317 }
4318
4319 @Override
4320 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004321 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004322 final long ident = Binder.clearCallingIdentity();
4323 try {
4324 synchronized (mGlobalLock) {
4325 mStackSupervisor.setSplitScreenResizing(resizing);
4326 }
4327 } finally {
4328 Binder.restoreCallingIdentity(ident);
4329 }
4330 }
4331
Evan Rosky0037e5f2019-11-05 10:26:24 -08004332 @Override
4333 public ITaskOrganizerController getTaskOrganizerController() {
4334 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
4335 "getTaskOrganizerController()");
4336 return mTaskOrganizerController;
4337 }
4338
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004339 /**
4340 * Check that we have the features required for VR-related API calls, and throw an exception if
4341 * not.
4342 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004343 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004344 if (!mContext.getPackageManager().hasSystemFeature(
4345 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4346 throw new UnsupportedOperationException("VR mode not supported on this device!");
4347 }
4348 }
4349
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004350 @Override
4351 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004352 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004353
4354 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4355
4356 ActivityRecord r;
4357 synchronized (mGlobalLock) {
4358 r = ActivityRecord.isInStackLocked(token);
4359 }
4360
4361 if (r == null) {
4362 throw new IllegalArgumentException();
4363 }
4364
4365 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004366 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367 VrManagerInternal.NO_ERROR) {
4368 return err;
4369 }
4370
4371 // Clear the binder calling uid since this path may call moveToTask().
4372 final long callingId = Binder.clearCallingIdentity();
4373 try {
4374 synchronized (mGlobalLock) {
4375 r.requestedVrComponent = (enabled) ? packageName : null;
4376
4377 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004378 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004379 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004380 }
4381 return 0;
4382 }
4383 } finally {
4384 Binder.restoreCallingIdentity(callingId);
4385 }
4386 }
4387
4388 @Override
4389 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4390 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4391 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004392 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004393 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4394 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4395 }
Louis Changcdec0802019-11-11 11:45:07 +08004396 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004397 || activity.voiceSession != null) {
4398 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4399 return;
4400 }
4401 if (activity.pendingVoiceInteractionStart) {
4402 Slog.w(TAG, "Pending start of voice interaction already.");
4403 return;
4404 }
4405 activity.pendingVoiceInteractionStart = true;
4406 }
4407 LocalServices.getService(VoiceInteractionManagerInternal.class)
4408 .startLocalVoiceInteraction(callingActivity, options);
4409 }
4410
4411 @Override
4412 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4413 LocalServices.getService(VoiceInteractionManagerInternal.class)
4414 .stopLocalVoiceInteraction(callingActivity);
4415 }
4416
4417 @Override
4418 public boolean supportsLocalVoiceInteraction() {
4419 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4420 .supportsLocalVoiceInteraction();
4421 }
4422
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004423 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004424 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004425 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004426
4427 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004428 if (mWindowManager == null) {
4429 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4430 return false;
4431 }
4432
4433 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004434 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004435 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004436 }
4437
Riddle Hsua0022cd2019-09-09 21:12:41 +08004438 mH.sendMessage(PooledLambda.obtainMessage(
4439 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4440 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004441
4442 final long origId = Binder.clearCallingIdentity();
4443 try {
4444 if (values != null) {
4445 Settings.System.clearConfiguration(values);
4446 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004447 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004448 UserHandle.USER_NULL, false /* deferResume */,
4449 mTmpUpdateConfigurationResult);
4450 return mTmpUpdateConfigurationResult.changes != 0;
4451 } finally {
4452 Binder.restoreCallingIdentity(origId);
4453 }
4454 }
4455 }
4456
4457 @Override
4458 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4459 CharSequence message) {
4460 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004461 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004462 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4463 }
4464 final long callingId = Binder.clearCallingIdentity();
4465 try {
4466 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004467 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004468 }
4469 } finally {
4470 Binder.restoreCallingIdentity(callingId);
4471 }
4472 }
4473
4474 @Override
4475 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004476 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004477 "cancelTaskWindowTransition()");
4478 final long ident = Binder.clearCallingIdentity();
4479 try {
4480 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004481 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004482 MATCH_TASK_IN_STACKS_ONLY);
4483 if (task == null) {
4484 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4485 return;
4486 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004487 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004488 }
4489 } finally {
4490 Binder.restoreCallingIdentity(ident);
4491 }
4492 }
4493
4494 @Override
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004495 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004496 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004497 final long ident = Binder.clearCallingIdentity();
4498 try {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004499 return getTaskSnapshot(taskId, isLowResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004500 } finally {
4501 Binder.restoreCallingIdentity(ident);
4502 }
4503 }
4504
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004505 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004506 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004507 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004508 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004509 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004510 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4511 if (task == null) {
4512 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4513 return null;
4514 }
4515 }
4516 // Don't call this while holding the lock as this operation might hit the disk.
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004517 return task.getSnapshot(isLowResolution, restoreFromDisk);
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004518 }
4519
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004520 @Override
4521 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4522 synchronized (mGlobalLock) {
4523 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4524 if (r == null) {
4525 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4526 + token);
4527 return;
4528 }
4529 final long origId = Binder.clearCallingIdentity();
4530 try {
4531 r.setDisablePreviewScreenshots(disable);
4532 } finally {
4533 Binder.restoreCallingIdentity(origId);
4534 }
4535 }
4536 }
4537
Riddle Hsu440f88b2019-11-06 22:17:35 +08004538 @Override
4539 public void invalidateHomeTaskSnapshot(IBinder token) {
4540 synchronized (mGlobalLock) {
4541 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4542 if (r == null || !r.isActivityTypeHome()) {
4543 return;
4544 }
4545 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4546 }
4547 }
4548
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004549 /** Return the user id of the last resumed activity. */
4550 @Override
4551 public @UserIdInt
4552 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004553 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004554 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4555 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004556 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004557 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004558 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004559 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004560 }
4561 }
4562
4563 @Override
4564 public void updateLockTaskFeatures(int userId, int flags) {
4565 final int callingUid = Binder.getCallingUid();
4566 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004567 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004568 "updateLockTaskFeatures()");
4569 }
4570 synchronized (mGlobalLock) {
4571 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4572 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004573 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004574 }
4575 }
4576
4577 @Override
4578 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4579 synchronized (mGlobalLock) {
4580 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4581 if (r == null) {
4582 return;
4583 }
4584 final long origId = Binder.clearCallingIdentity();
4585 try {
4586 r.setShowWhenLocked(showWhenLocked);
4587 } finally {
4588 Binder.restoreCallingIdentity(origId);
4589 }
4590 }
4591 }
4592
4593 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004594 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4595 synchronized (mGlobalLock) {
4596 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4597 if (r == null) {
4598 return;
4599 }
4600 final long origId = Binder.clearCallingIdentity();
4601 try {
4602 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4603 } finally {
4604 Binder.restoreCallingIdentity(origId);
4605 }
4606 }
4607 }
4608
4609 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004610 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4611 synchronized (mGlobalLock) {
4612 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4613 if (r == null) {
4614 return;
4615 }
4616 final long origId = Binder.clearCallingIdentity();
4617 try {
4618 r.setTurnScreenOn(turnScreenOn);
4619 } finally {
4620 Binder.restoreCallingIdentity(origId);
4621 }
4622 }
4623 }
4624
4625 @Override
4626 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004627 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004628 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004629 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004630 synchronized (mGlobalLock) {
4631 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4632 if (r == null) {
4633 return;
4634 }
4635 final long origId = Binder.clearCallingIdentity();
4636 try {
4637 r.registerRemoteAnimations(definition);
4638 } finally {
4639 Binder.restoreCallingIdentity(origId);
4640 }
4641 }
4642 }
4643
4644 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004645 public void unregisterRemoteAnimations(IBinder token) {
4646 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4647 "unregisterRemoteAnimations");
4648 synchronized (mGlobalLock) {
4649 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4650 if (r == null) {
4651 return;
4652 }
4653 final long origId = Binder.clearCallingIdentity();
4654 try {
4655 r.unregisterRemoteAnimations();
4656 } finally {
4657 Binder.restoreCallingIdentity(origId);
4658 }
4659 }
4660 }
4661
4662 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004663 public void registerRemoteAnimationForNextActivityStart(String packageName,
4664 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004665 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004666 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004667 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004668 synchronized (mGlobalLock) {
4669 final long origId = Binder.clearCallingIdentity();
4670 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004671 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004672 packageName, adapter);
4673 } finally {
4674 Binder.restoreCallingIdentity(origId);
4675 }
4676 }
4677 }
4678
Evan Rosky966759f2019-01-15 10:33:58 -08004679 @Override
4680 public void registerRemoteAnimationsForDisplay(int displayId,
4681 RemoteAnimationDefinition definition) {
4682 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4683 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004684 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004685 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004686 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004687 if (display == null) {
4688 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4689 return;
4690 }
4691 final long origId = Binder.clearCallingIdentity();
4692 try {
4693 display.mDisplayContent.registerRemoteAnimations(definition);
4694 } finally {
4695 Binder.restoreCallingIdentity(origId);
4696 }
4697 }
4698 }
4699
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004700 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4701 @Override
4702 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4703 synchronized (mGlobalLock) {
4704 final long origId = Binder.clearCallingIdentity();
4705 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004706 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004707 } finally {
4708 Binder.restoreCallingIdentity(origId);
4709 }
4710 }
4711 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004712
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004713 @Override
4714 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004715 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004716 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004717 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004718 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004719 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004720 }
4721 }
4722
4723 @Override
4724 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004725 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004726 != PERMISSION_GRANTED) {
4727 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4728 + Binder.getCallingPid()
4729 + ", uid=" + Binder.getCallingUid()
4730 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4731 Slog.w(TAG, msg);
4732 throw new SecurityException(msg);
4733 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004734 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004735 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004736 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004737 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004738 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004739 }
4740 }
4741
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004742 @Override
4743 public void stopAppSwitches() {
4744 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4745 synchronized (mGlobalLock) {
4746 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004747 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004748 mDidAppSwitch = false;
4749 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4750 }
4751 }
4752
4753 @Override
4754 public void resumeAppSwitches() {
4755 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4756 synchronized (mGlobalLock) {
4757 // Note that we don't execute any pending app switches... we will
4758 // let those wait until either the timeout, or the next start
4759 // activity request.
4760 mAppSwitchesAllowedTime = 0;
4761 }
4762 }
4763
Ricky Wai906af482019-06-03 17:25:28 +01004764 long getLastStopAppSwitchesTime() {
4765 return mLastStopAppSwitchesTime;
4766 }
4767
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004768 void onStartActivitySetDidAppSwitch() {
4769 if (mDidAppSwitch) {
4770 // This is the second allowed switch since we stopped switches, so now just generally
4771 // allow switches. Use case:
4772 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4773 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4774 // anyone to switch again).
4775 mAppSwitchesAllowedTime = 0;
4776 } else {
4777 mDidAppSwitch = true;
4778 }
4779 }
4780
4781 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004782 boolean shouldDisableNonVrUiLocked() {
4783 return mVrController.shouldDisableNonVrUiLocked();
4784 }
4785
Wale Ogunwale53783742018-09-16 10:21:51 -07004786 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004787 // 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 +00004788 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004789 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004790 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4791 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004792 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004793 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004794 }
4795 mH.post(() -> {
4796 if (!mVrController.onVrModeChanged(r)) {
4797 return;
4798 }
4799 synchronized (mGlobalLock) {
4800 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4801 mWindowManager.disableNonVrUi(disableNonVrUi);
4802 if (disableNonVrUi) {
4803 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4804 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004805 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004806 }
4807 }
4808 });
4809 }
4810
Wale Ogunwale53783742018-09-16 10:21:51 -07004811 @Override
4812 public int getPackageScreenCompatMode(String packageName) {
4813 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4814 synchronized (mGlobalLock) {
4815 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4816 }
4817 }
4818
4819 @Override
4820 public void setPackageScreenCompatMode(String packageName, int mode) {
4821 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4822 "setPackageScreenCompatMode");
4823 synchronized (mGlobalLock) {
4824 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4825 }
4826 }
4827
4828 @Override
4829 public boolean getPackageAskScreenCompat(String packageName) {
4830 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4831 synchronized (mGlobalLock) {
4832 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4833 }
4834 }
4835
4836 @Override
4837 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4838 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4839 "setPackageAskScreenCompat");
4840 synchronized (mGlobalLock) {
4841 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4842 }
4843 }
4844
Wale Ogunwale64258362018-10-16 15:13:37 -07004845 public static String relaunchReasonToString(int relaunchReason) {
4846 switch (relaunchReason) {
4847 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4848 return "window_resize";
4849 case RELAUNCH_REASON_FREE_RESIZE:
4850 return "free_resize";
4851 default:
4852 return null;
4853 }
4854 }
4855
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004856 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004857 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004858 }
4859
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004860 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004861 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004862 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4863 }
4864
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004865 boolean isKeyguardLocked() {
4866 return mKeyguardController.isKeyguardLocked();
4867 }
4868
Garfield Tan01548632018-11-27 10:15:48 -08004869 /**
4870 * Clears launch params for the given package.
4871 * @param packageNames the names of the packages of which the launch params are to be cleared
4872 */
4873 @Override
4874 public void clearLaunchParamsForPackages(List<String> packageNames) {
4875 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4876 "clearLaunchParamsForPackages");
4877 synchronized (mGlobalLock) {
4878 for (int i = 0; i < packageNames.size(); ++i) {
4879 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4880 }
4881 }
4882 }
4883
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004884 /**
4885 * Makes the display with the given id a single task instance display. I.e the display can only
4886 * contain one task.
4887 */
4888 @Override
4889 public void setDisplayToSingleTaskInstance(int displayId) {
4890 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4891 "setDisplayToSingleTaskInstance");
4892 final long origId = Binder.clearCallingIdentity();
4893 try {
Louis Chang677921f2019-12-06 16:44:24 +08004894 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004895 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004896 if (display != null) {
4897 display.setDisplayToSingleTaskInstance();
4898 }
4899 } finally {
4900 Binder.restoreCallingIdentity(origId);
4901 }
4902 }
4903
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004904 /**
4905 * Requests that an activity should enter picture-in-picture mode if possible.
4906 */
4907 @Override
4908 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4909 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4910 "requestPictureInPictureMode");
4911 final long origId = Binder.clearCallingIdentity();
4912 try {
4913 synchronized (mGlobalLock) {
4914 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4915 if (activity == null) {
4916 return;
4917 }
4918
4919 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4920 "requestPictureInPictureMode", /* beforeStopping */ false);
4921 if (!canEnterPictureInPicture) {
4922 throw new IllegalStateException(
4923 "Requested PIP on an activity that doesn't support it");
4924 }
4925
4926 try {
4927 final ClientTransaction transaction = ClientTransaction.obtain(
4928 activity.app.getThread(),
4929 activity.token);
4930 transaction.addCallback(EnterPipRequestedItem.obtain());
4931 getLifecycleManager().scheduleTransaction(transaction);
4932 } catch (Exception e) {
4933 Slog.w(TAG, "Failed to send enter pip requested item: "
4934 + activity.intent.getComponent(), e);
4935 }
4936 }
4937 } finally {
4938 Binder.restoreCallingIdentity(origId);
4939 }
4940 }
4941
Wale Ogunwale31913b52018-10-13 08:29:31 -07004942 void dumpLastANRLocked(PrintWriter pw) {
4943 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4944 if (mLastANRState == null) {
4945 pw.println(" <no ANR has occurred since boot>");
4946 } else {
4947 pw.println(mLastANRState);
4948 }
4949 }
4950
4951 void dumpLastANRTracesLocked(PrintWriter pw) {
4952 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4953
4954 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4955 if (ArrayUtils.isEmpty(files)) {
4956 pw.println(" <no ANR has occurred since boot>");
4957 return;
4958 }
4959 // Find the latest file.
4960 File latest = null;
4961 for (File f : files) {
4962 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4963 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004964 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004965 }
4966 pw.print("File: ");
4967 pw.print(latest.getName());
4968 pw.println();
4969 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4970 String line;
4971 while ((line = in.readLine()) != null) {
4972 pw.println(line);
4973 }
4974 } catch (IOException e) {
4975 pw.print("Unable to read: ");
4976 pw.print(e);
4977 pw.println();
4978 }
4979 }
4980
4981 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4982 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4983 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4984 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4985 }
4986
4987 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4988 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4989 pw.println(header);
4990
Louis Chang149d5c82019-12-30 09:47:39 +08004991 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004992 dumpPackage);
4993 boolean needSep = printedAnything;
4994
4995 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08004996 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004997 " ResumedActivity: ");
4998 if (printed) {
4999 printedAnything = true;
5000 needSep = false;
5001 }
5002
5003 if (dumpPackage == null) {
5004 if (needSep) {
5005 pw.println();
5006 }
5007 printedAnything = true;
5008 mStackSupervisor.dump(pw, " ");
5009 }
5010
5011 if (!printedAnything) {
5012 pw.println(" (nothing)");
5013 }
5014 }
5015
5016 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005017 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005018 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005019 pw.println(" ");
5020 }
5021
5022 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5023 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5024 getActivityStartController().dump(pw, "", dumpPackage);
5025 }
5026
5027 /**
5028 * There are three things that cmd can be:
5029 * - a flattened component name that matches an existing activity
5030 * - the cmd arg isn't the flattened component name of an existing activity:
5031 * dump all activity whose component contains the cmd as a substring
5032 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005033 * <p>
5034 * The caller should not hold lock when calling this method because it will wait for the
5035 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005036 *
5037 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5038 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5039 */
5040 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5041 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5042 ArrayList<ActivityRecord> activities;
5043
5044 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005045 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005046 dumpFocusedStackOnly);
5047 }
5048
5049 if (activities.size() <= 0) {
5050 return false;
5051 }
5052
5053 String[] newArgs = new String[args.length - opti];
5054 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5055
Louis Changcdec0802019-11-11 11:45:07 +08005056 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005057 boolean needSep = false;
5058 for (int i = activities.size() - 1; i >= 0; i--) {
5059 ActivityRecord r = activities.get(i);
5060 if (needSep) {
5061 pw.println();
5062 }
5063 needSep = true;
5064 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005065 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005066 if (lastTask != task) {
5067 lastTask = task;
5068 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005069 pw.print(" id="); pw.print(lastTask.mTaskId);
5070 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005071 if (dumpAll) {
5072 lastTask.dump(pw, " ");
5073 }
5074 }
5075 }
5076 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5077 }
5078 return true;
5079 }
5080
5081 /**
5082 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5083 * there is a thread associated with the activity.
5084 */
5085 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5086 final ActivityRecord r, String[] args, boolean dumpAll) {
5087 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005088 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005089 synchronized (mGlobalLock) {
5090 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5091 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5092 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005093 if (r.hasProcess()) {
5094 pw.println(r.app.getPid());
5095 appThread = r.app.getThread();
5096 } else {
5097 pw.println("(not running)");
5098 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005099 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005100 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005101 }
5102 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005103 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005104 // flush anything that is already in the PrintWriter since the thread is going
5105 // to write to the file descriptor directly
5106 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005107 try (TransferPipe tp = new TransferPipe()) {
5108 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5109 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005110 } catch (IOException e) {
5111 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5112 } catch (RemoteException e) {
5113 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5114 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005115 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005116 }
5117
sanryhuang498e77e2018-12-06 14:57:01 +08005118 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5119 boolean testPssMode) {
5120 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5121 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5122 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005123 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005124 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5125 st.toString());
5126 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005127 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5128 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5129 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005130 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5131 testPssMode);
5132 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005133 }
5134
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005135 int getCurrentUserId() {
5136 return mAmInternal.getCurrentUserId();
5137 }
5138
5139 private void enforceNotIsolatedCaller(String caller) {
5140 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5141 throw new SecurityException("Isolated process not allowed to call " + caller);
5142 }
5143 }
5144
Wale Ogunwalef6733932018-06-27 05:14:34 -07005145 public Configuration getConfiguration() {
5146 Configuration ci;
5147 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005148 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005149 ci.userSetLocale = false;
5150 }
5151 return ci;
5152 }
5153
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005154 /**
5155 * Current global configuration information. Contains general settings for the entire system,
5156 * also corresponds to the merged configuration of the default display.
5157 */
5158 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005159 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005160 // while initializing process record for system, see {@link
5161 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005162 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005163 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005164 }
5165
5166 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5167 boolean initLocale) {
5168 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5169 }
5170
5171 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5172 boolean initLocale, boolean deferResume) {
5173 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5174 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5175 UserHandle.USER_NULL, deferResume);
5176 }
5177
Wale Ogunwale59507092018-10-29 09:00:30 -07005178 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005179 final long origId = Binder.clearCallingIdentity();
5180 try {
5181 synchronized (mGlobalLock) {
5182 updateConfigurationLocked(values, null, false, true, userId,
5183 false /* deferResume */);
5184 }
5185 } finally {
5186 Binder.restoreCallingIdentity(origId);
5187 }
5188 }
5189
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005190 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5191 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5192 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5193 deferResume, null /* result */);
5194 }
5195
5196 /**
5197 * Do either or both things: (1) change the current configuration, and (2)
5198 * make sure the given activity is running with the (now) current
5199 * configuration. Returns true if the activity has been left running, or
5200 * false if <var>starting</var> is being destroyed to match the new
5201 * configuration.
5202 *
5203 * @param userId is only used when persistent parameter is set to true to persist configuration
5204 * for that particular user
5205 */
5206 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5207 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5208 ActivityTaskManagerService.UpdateConfigurationResult result) {
5209 int changes = 0;
5210 boolean kept = true;
5211
Riddle Hsua0022cd2019-09-09 21:12:41 +08005212 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005213 try {
5214 if (values != null) {
5215 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5216 deferResume);
5217 }
5218
5219 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5220 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005221 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005222 }
5223
5224 if (result != null) {
5225 result.changes = changes;
5226 result.activityRelaunched = !kept;
5227 }
5228 return kept;
5229 }
5230
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005231 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005232 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005233 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005234
Louis Chang677921f2019-12-06 16:44:24 +08005235 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005236 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005237
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005238 mTempConfig.setTo(getGlobalConfiguration());
5239 final int changes = mTempConfig.updateFrom(values);
5240 if (changes == 0) {
5241 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5242 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5243 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5244 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005245 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005246 return 0;
5247 }
5248
5249 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5250 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005251 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005252 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005253 values.colorMode,
5254 values.densityDpi,
5255 values.fontScale,
5256 values.hardKeyboardHidden,
5257 values.keyboard,
5258 values.keyboardHidden,
5259 values.mcc,
5260 values.mnc,
5261 values.navigation,
5262 values.navigationHidden,
5263 values.orientation,
5264 values.screenHeightDp,
5265 values.screenLayout,
5266 values.screenWidthDp,
5267 values.smallestScreenWidthDp,
5268 values.touchscreen,
5269 values.uiMode);
5270
5271
5272 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5273 final LocaleList locales = values.getLocales();
5274 int bestLocaleIndex = 0;
5275 if (locales.size() > 1) {
5276 if (mSupportedSystemLocales == null) {
5277 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5278 }
5279 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5280 }
5281 SystemProperties.set("persist.sys.locale",
5282 locales.get(bestLocaleIndex).toLanguageTag());
5283 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005284
5285 final Message m = PooledLambda.obtainMessage(
5286 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5287 locales.get(bestLocaleIndex));
5288 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005289 }
5290
Yunfan Chen75157d72018-07-27 14:47:21 +09005291 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005292
5293 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005294 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005295
5296 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5297 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005298 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005299
5300 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005301 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005302
5303 AttributeCache ac = AttributeCache.instance();
5304 if (ac != null) {
5305 ac.updateConfiguration(mTempConfig);
5306 }
5307
5308 // Make sure all resources in our process are updated right now, so that anyone who is going
5309 // to retrieve resource values after we return will be sure to get the new ones. This is
5310 // especially important during boot, where the first config change needs to guarantee all
5311 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005312 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005313
5314 // We need another copy of global config because we're scheduling some calls instead of
5315 // running them in place. We need to be sure that object we send will be handled unchanged.
5316 final Configuration configCopy = new Configuration(mTempConfig);
5317 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005318 final Message msg = PooledLambda.obtainMessage(
5319 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5320 this, userId, configCopy);
5321 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005322 }
5323
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005324 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5325 for (int i = pidMap.size() - 1; i >= 0; i--) {
5326 final int pid = pidMap.keyAt(i);
5327 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005328 if (DEBUG_CONFIGURATION) {
5329 Slog.v(TAG_CONFIGURATION, "Update process config of "
5330 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005331 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005332 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005333 }
5334
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005335 final Message msg = PooledLambda.obtainMessage(
5336 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5337 mAmInternal, changes, initLocale);
5338 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005339
5340 // Override configuration of the default display duplicates global config, so we need to
5341 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005342 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005343 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005344
5345 return changes;
5346 }
5347
Riddle Hsua0022cd2019-09-09 21:12:41 +08005348 /** @see WindowSurfacePlacer#deferLayout */
5349 void deferWindowLayout() {
5350 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5351 // Reset the reasons at the first entrance because we only care about the changes in the
5352 // deferred scope.
5353 mLayoutReasons = 0;
5354 }
5355
5356 mWindowManager.mWindowPlacerLocked.deferLayout();
5357 }
5358
5359 /** @see WindowSurfacePlacer#continueLayout */
5360 void continueWindowLayout() {
5361 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5362 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5363 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5364 }
5365 }
5366
5367 /**
5368 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5369 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5370 * defer count is gone.
5371 */
5372 void addWindowLayoutReasons(@LayoutReason int reasons) {
5373 mLayoutReasons |= reasons;
5374 }
5375
Wale Ogunwalef6733932018-06-27 05:14:34 -07005376 private void updateEventDispatchingLocked(boolean booted) {
5377 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5378 }
5379
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005380 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5381 final ContentResolver resolver = mContext.getContentResolver();
5382 Settings.System.putConfigurationForUser(resolver, config, userId);
5383 }
5384
5385 private void sendLocaleToMountDaemonMsg(Locale l) {
5386 try {
5387 IBinder service = ServiceManager.getService("mount");
5388 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5389 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5390 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5391 } catch (RemoteException e) {
5392 Log.e(TAG, "Error storing locale for decryption UI", e);
5393 }
5394 }
5395
Alison Cichowlas3e340502018-08-07 17:15:01 -04005396 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5397 mStartActivitySources.remove(permissionToken);
5398 mExpiredStartAsCallerTokens.add(permissionToken);
5399 }
5400
5401 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5402 mExpiredStartAsCallerTokens.remove(permissionToken);
5403 }
5404
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005405 boolean isActivityStartsLoggingEnabled() {
5406 return mAmInternal.isActivityStartsLoggingEnabled();
5407 }
5408
Michal Karpinski8596ded2018-11-14 14:43:48 +00005409 boolean isBackgroundActivityStartsEnabled() {
5410 return mAmInternal.isBackgroundActivityStartsEnabled();
5411 }
5412
Wale Ogunwalef6733932018-06-27 05:14:34 -07005413 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005414 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005415 mWindowManager.enableScreenAfterBoot();
5416
5417 synchronized (mGlobalLock) {
5418 updateEventDispatchingLocked(booted);
5419 }
5420 }
5421
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005422 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5423 if (r == null || !r.hasProcess()) {
5424 return KEY_DISPATCHING_TIMEOUT_MS;
5425 }
5426 return getInputDispatchingTimeoutLocked(r.app);
5427 }
5428
5429 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005430 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005431 }
5432
Wale Ogunwalef6733932018-06-27 05:14:34 -07005433 /**
5434 * Decide based on the configuration whether we should show the ANR,
5435 * crash, etc dialogs. The idea is that if there is no affordance to
5436 * press the on-screen buttons, or the user experience would be more
5437 * greatly impacted than the crash itself, we shouldn't show the dialog.
5438 *
5439 * A thought: SystemUI might also want to get told about this, the Power
5440 * dialog / global actions also might want different behaviors.
5441 */
5442 private void updateShouldShowDialogsLocked(Configuration config) {
5443 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5444 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5445 && config.navigation == Configuration.NAVIGATION_NONAV);
5446 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5447 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5448 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5449 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5450 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5451 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5452 HIDE_ERROR_DIALOGS, 0) != 0;
5453 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5454 }
5455
5456 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5457 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5458 FONT_SCALE, 1.0f, userId);
5459
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005460 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005461 if (getGlobalConfiguration().fontScale == scaleFactor) {
5462 return;
5463 }
5464
5465 final Configuration configuration
5466 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5467 configuration.fontScale = scaleFactor;
5468 updatePersistentConfiguration(configuration, userId);
5469 }
5470 }
5471
5472 // Actually is sleeping or shutting down or whatever else in the future
5473 // is an inactive state.
5474 boolean isSleepingOrShuttingDownLocked() {
5475 return isSleepingLocked() || mShuttingDown;
5476 }
5477
5478 boolean isSleepingLocked() {
5479 return mSleeping;
5480 }
5481
Riddle Hsu16567132018-08-16 21:37:47 +08005482 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005483 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005484 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005485 if (task.isActivityTypeStandard()) {
5486 if (mCurAppTimeTracker != r.appTimeTracker) {
5487 // We are switching app tracking. Complete the current one.
5488 if (mCurAppTimeTracker != null) {
5489 mCurAppTimeTracker.stop();
5490 mH.obtainMessage(
5491 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005492 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005493 mCurAppTimeTracker = null;
5494 }
5495 if (r.appTimeTracker != null) {
5496 mCurAppTimeTracker = r.appTimeTracker;
5497 startTimeTrackingFocusedActivityLocked();
5498 }
5499 } else {
5500 startTimeTrackingFocusedActivityLocked();
5501 }
5502 } else {
5503 r.appTimeTracker = null;
5504 }
5505 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5506 // TODO: Probably not, because we don't want to resume voice on switching
5507 // back to this activity
5508 if (task.voiceInteractor != null) {
5509 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5510 } else {
5511 finishRunningVoiceLocked();
5512
5513 if (mLastResumedActivity != null) {
5514 final IVoiceInteractionSession session;
5515
Louis Changcdec0802019-11-11 11:45:07 +08005516 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005517 if (lastResumedActivityTask != null
5518 && lastResumedActivityTask.voiceSession != null) {
5519 session = lastResumedActivityTask.voiceSession;
5520 } else {
5521 session = mLastResumedActivity.voiceSession;
5522 }
5523
5524 if (session != null) {
5525 // We had been in a voice interaction session, but now focused has
5526 // move to something different. Just finish the session, we can't
5527 // return to it and retain the proper state and synchronization with
5528 // the voice interaction service.
5529 finishVoiceTask(session);
5530 }
5531 }
5532 }
5533
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005534 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5535 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005536 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005537 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5538
Wale Ogunwalef6733932018-06-27 05:14:34 -07005539 updateResumedAppTrace(r);
5540 mLastResumedActivity = r;
5541
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005542 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005543
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005544 if (prevTask == null || task != prevTask) {
5545 if (prevTask != null) {
5546 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5547 }
5548 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5549 }
5550
Wale Ogunwalef6733932018-06-27 05:14:34 -07005551 applyUpdateLockStateLocked(r);
5552 applyUpdateVrModeLocked(r);
5553
Jeff Changd136e772019-11-05 20:33:52 +08005554 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005555 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005556 r == null ? "NULL" : r.shortComponentName,
5557 reason);
5558 }
5559
5560 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5561 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005562 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005563 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005564 updateSleepIfNeededLocked();
5565 return token;
5566 }
5567 }
5568
5569 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005570 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005571 final boolean wasSleeping = mSleeping;
5572 boolean updateOomAdj = false;
5573
5574 if (!shouldSleep) {
5575 // If wasSleeping is true, we need to wake up activity manager state from when
5576 // we started sleeping. In either case, we need to apply the sleep tokens, which
5577 // will wake up stacks or put them to sleep as appropriate.
5578 if (wasSleeping) {
5579 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005580 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5581 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005582 startTimeTrackingFocusedActivityLocked();
5583 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005584 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005585 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5586 }
Louis Chang149d5c82019-12-30 09:47:39 +08005587 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005588 if (wasSleeping) {
5589 updateOomAdj = true;
5590 }
5591 } else if (!mSleeping && shouldSleep) {
5592 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005593 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5594 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005595 if (mCurAppTimeTracker != null) {
5596 mCurAppTimeTracker.stop();
5597 }
5598 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005599 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005600 mStackSupervisor.goingToSleepLocked();
5601 updateResumedAppTrace(null /* resumed */);
5602 updateOomAdj = true;
5603 }
5604 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005605 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005606 }
5607 }
5608
5609 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005610 mH.removeCallbacks(mUpdateOomAdjRunnable);
5611 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005612 }
5613
Wale Ogunwale53783742018-09-16 10:21:51 -07005614 void updateCpuStats() {
5615 mH.post(mAmInternal::updateCpuStats);
5616 }
5617
Hui Yu03d12402018-12-06 18:00:37 -08005618 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5619 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005620 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5621 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005622 mH.sendMessage(m);
5623 }
5624
Hui Yu03d12402018-12-06 18:00:37 -08005625 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005626 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005627 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005628 if (task != null) {
5629 final ActivityRecord rootActivity = task.getRootActivity();
5630 if (rootActivity != null) {
5631 taskRoot = rootActivity.mActivityComponent;
5632 }
5633 }
5634
Hui Yu03d12402018-12-06 18:00:37 -08005635 final Message m = PooledLambda.obtainMessage(
5636 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005637 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005638 mH.sendMessage(m);
5639 }
5640
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005641 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5642 String hostingType) {
5643 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005644 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5645 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005646 + activity.processName);
5647 }
5648 // Post message to start process to avoid possible deadlock of calling into AMS with the
5649 // ATMS lock held.
5650 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5651 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5652 isTop, hostingType, activity.intent.getComponent());
5653 mH.sendMessage(m);
5654 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005655 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005656 }
5657 }
5658
Wale Ogunwale53783742018-09-16 10:21:51 -07005659 void setBooting(boolean booting) {
5660 mAmInternal.setBooting(booting);
5661 }
5662
5663 boolean isBooting() {
5664 return mAmInternal.isBooting();
5665 }
5666
5667 void setBooted(boolean booted) {
5668 mAmInternal.setBooted(booted);
5669 }
5670
5671 boolean isBooted() {
5672 return mAmInternal.isBooted();
5673 }
5674
5675 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5676 mH.post(() -> {
5677 if (finishBooting) {
5678 mAmInternal.finishBooting();
5679 }
5680 if (enableScreen) {
5681 mInternal.enableScreenAfterBoot(isBooted());
5682 }
5683 });
5684 }
5685
5686 void setHeavyWeightProcess(ActivityRecord root) {
5687 mHeavyWeightProcess = root.app;
5688 final Message m = PooledLambda.obtainMessage(
5689 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005690 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005691 mH.sendMessage(m);
5692 }
5693
5694 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5695 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5696 return;
5697 }
5698
5699 mHeavyWeightProcess = null;
5700 final Message m = PooledLambda.obtainMessage(
5701 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5702 proc.mUserId);
5703 mH.sendMessage(m);
5704 }
5705
5706 private void cancelHeavyWeightProcessNotification(int userId) {
5707 final INotificationManager inm = NotificationManager.getService();
5708 if (inm == null) {
5709 return;
5710 }
5711 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005712 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005713 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5714 } catch (RuntimeException e) {
5715 Slog.w(TAG, "Error canceling notification for service", e);
5716 } catch (RemoteException e) {
5717 }
5718
5719 }
5720
5721 private void postHeavyWeightProcessNotification(
5722 WindowProcessController proc, Intent intent, int userId) {
5723 if (proc == null) {
5724 return;
5725 }
5726
5727 final INotificationManager inm = NotificationManager.getService();
5728 if (inm == null) {
5729 return;
5730 }
5731
5732 try {
5733 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5734 String text = mContext.getString(R.string.heavy_weight_notification,
5735 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5736 Notification notification =
5737 new Notification.Builder(context,
5738 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5739 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5740 .setWhen(0)
5741 .setOngoing(true)
5742 .setTicker(text)
5743 .setColor(mContext.getColor(
5744 com.android.internal.R.color.system_notification_accent_color))
5745 .setContentTitle(text)
5746 .setContentText(
5747 mContext.getText(R.string.heavy_weight_notification_detail))
5748 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5749 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5750 new UserHandle(userId)))
5751 .build();
5752 try {
5753 inm.enqueueNotificationWithTag("android", "android", null,
5754 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5755 } catch (RuntimeException e) {
5756 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5757 } catch (RemoteException e) {
5758 }
5759 } catch (PackageManager.NameNotFoundException e) {
5760 Slog.w(TAG, "Unable to create context for heavy notification", e);
5761 }
5762
5763 }
5764
Philip P. Moltmannee295092020-02-10 08:46:26 -08005765 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5766 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5767 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005768
5769 ActivityRecord activity = null;
5770 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5771 activity = ActivityRecord.isInStackLocked(token);
5772 if (activity == null) {
5773 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5774 return null;
5775 }
5776 if (activity.finishing) {
5777 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5778 return null;
5779 }
5780 }
5781
5782 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005783 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5784 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005785 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5786 if (noCreate) {
5787 return rec;
5788 }
5789 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5790 if (activity.pendingResults == null) {
5791 activity.pendingResults = new HashSet<>();
5792 }
5793 activity.pendingResults.add(rec.ref);
5794 }
5795 return rec;
5796 }
5797
Andrii Kulian52d255c2018-07-13 11:32:19 -07005798 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005799 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005800 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005801 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5802 mCurAppTimeTracker.start(resumedActivity.packageName);
5803 }
5804 }
5805
5806 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5807 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005808 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005809 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5810 }
5811 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005812 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005813 constructResumedTraceName(resumed.packageName), 0);
5814 }
5815 mTracedResumedActivity = resumed;
5816 }
5817
5818 private String constructResumedTraceName(String packageName) {
5819 return "focused app: " + packageName;
5820 }
5821
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005822 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005823 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005824 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005825 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005826 // mainStack is null during startup.
5827 if (mainStack != null) {
5828 if (changes != 0 && starting == null) {
5829 // If the configuration changed, and the caller is not already
5830 // in the process of starting an activity, then find the top
5831 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005832 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005833 }
5834
5835 if (starting != null) {
5836 kept = starting.ensureActivityConfiguration(changes,
5837 false /* preserveWindow */);
5838 // And we need to make sure at this point that all other activities
5839 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005840 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005841 !PRESERVE_WINDOWS);
5842 }
5843 }
5844
5845 return kept;
5846 }
5847
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005848 void scheduleAppGcsLocked() {
5849 mH.post(() -> mAmInternal.scheduleAppGcs());
5850 }
5851
Wale Ogunwale53783742018-09-16 10:21:51 -07005852 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5853 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5854 }
5855
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005856 /**
5857 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5858 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5859 * on demand.
5860 */
5861 IPackageManager getPackageManager() {
5862 return AppGlobals.getPackageManager();
5863 }
5864
5865 PackageManagerInternal getPackageManagerInternalLocked() {
5866 if (mPmInternal == null) {
5867 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5868 }
5869 return mPmInternal;
5870 }
5871
Hai Zhangf4da9be2019-05-01 13:46:06 +08005872 PermissionPolicyInternal getPermissionPolicyInternal() {
5873 if (mPermissionPolicyInternal == null) {
5874 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5875 }
5876 return mPermissionPolicyInternal;
5877 }
5878
Wale Ogunwale008163e2018-07-23 23:11:08 -07005879 AppWarnings getAppWarningsLocked() {
5880 return mAppWarnings;
5881 }
5882
Wale Ogunwale214f3482018-10-04 11:00:47 -07005883 Intent getHomeIntent() {
5884 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5885 intent.setComponent(mTopComponent);
5886 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5887 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5888 intent.addCategory(Intent.CATEGORY_HOME);
5889 }
5890 return intent;
5891 }
5892
Chilun2ef71f72018-11-16 17:57:15 +08005893 /**
5894 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5895 * activities.
5896 *
Chilun939b05c2020-02-19 14:50:59 +08005897 * @param preferredPackage Specify a preferred package name, otherwise use the package name
5898 * defined in config_secondaryHomePackage.
Chilun2ef71f72018-11-16 17:57:15 +08005899 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5900 */
5901 Intent getSecondaryHomeIntent(String preferredPackage) {
5902 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005903 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5904 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5905 if (preferredPackage == null || useSystemProvidedLauncher) {
Chilun939b05c2020-02-19 14:50:59 +08005906 // Using the package name stored in config if no preferred package name or forced.
5907 final String secondaryHomePackage = mContext.getResources().getString(
5908 com.android.internal.R.string.config_secondaryHomePackage);
5909 intent.setPackage(secondaryHomePackage);
Chilun2ef71f72018-11-16 17:57:15 +08005910 } else {
5911 intent.setPackage(preferredPackage);
5912 }
5913 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5914 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5915 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5916 }
5917 return intent;
5918 }
5919
Wale Ogunwale214f3482018-10-04 11:00:47 -07005920 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5921 if (info == null) return null;
5922 ApplicationInfo newInfo = new ApplicationInfo(info);
5923 newInfo.initForUser(userId);
5924 return newInfo;
5925 }
5926
Wale Ogunwale9c103022018-10-18 07:44:54 -07005927 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005928 if (uid == SYSTEM_UID) {
5929 // The system gets to run in any process. If there are multiple processes with the same
5930 // uid, just pick the first (this should never happen).
5931 final SparseArray<WindowProcessController> procs =
5932 mProcessNames.getMap().get(processName);
5933 if (procs == null) return null;
5934 final int procCount = procs.size();
5935 for (int i = 0; i < procCount; i++) {
5936 final int procUid = procs.keyAt(i);
5937 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5938 // Don't use an app process or different user process for system component.
5939 continue;
5940 }
5941 return procs.valueAt(i);
5942 }
5943 }
5944
5945 return mProcessNames.get(processName, uid);
5946 }
5947
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005948 WindowProcessController getProcessController(IApplicationThread thread) {
5949 if (thread == null) {
5950 return null;
5951 }
5952
5953 final IBinder threadBinder = thread.asBinder();
5954 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5955 for (int i = pmap.size()-1; i >= 0; i--) {
5956 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5957 for (int j = procs.size() - 1; j >= 0; j--) {
5958 final WindowProcessController proc = procs.valueAt(j);
5959 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5960 return proc;
5961 }
5962 }
5963 }
5964
5965 return null;
5966 }
5967
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005968 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005969 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005970 if (proc == null) return null;
5971 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5972 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005973 }
5974 return null;
5975 }
5976
Riddle Hsua0536432019-02-16 00:38:59 +08005977 int getUidState(int uid) {
5978 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005979 }
5980
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005981 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005982 // A uid is considered to be foreground if it has a visible non-toast window.
5983 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005984 }
5985
Ricky Wai96f5c352019-04-10 18:40:17 +01005986 boolean isDeviceOwner(int uid) {
5987 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005988 }
5989
Ricky Wai96f5c352019-04-10 18:40:17 +01005990 void setDeviceOwnerUid(int uid) {
5991 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005992 }
5993
Wale Ogunwale9de19442018-10-18 19:05:03 -07005994 /**
5995 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5996 * the whitelist
5997 */
5998 String getPendingTempWhitelistTagForUidLocked(int uid) {
5999 return mPendingTempWhitelist.get(uid);
6000 }
6001
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006002 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6003 if (true || Build.IS_USER) {
6004 return;
6005 }
6006
6007 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6008 StrictMode.allowThreadDiskWrites();
6009 try {
6010 File tracesDir = new File("/data/anr");
6011 File tracesFile = null;
6012 try {
6013 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6014
6015 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006016 String timeString =
6017 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6018 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006019 sb.append(": ");
6020 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6021 sb.append(" since ");
6022 sb.append(msg);
6023 FileOutputStream fos = new FileOutputStream(tracesFile);
6024 fos.write(sb.toString().getBytes());
6025 if (app == null) {
6026 fos.write("\n*** No application process!".getBytes());
6027 }
6028 fos.close();
6029 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6030 } catch (IOException e) {
6031 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6032 return;
6033 }
6034
6035 if (app != null && app.getPid() > 0) {
6036 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6037 firstPids.add(app.getPid());
6038 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6039 }
6040
6041 File lastTracesFile = null;
6042 File curTracesFile = null;
6043 for (int i=9; i>=0; i--) {
6044 String name = String.format(Locale.US, "slow%02d.txt", i);
6045 curTracesFile = new File(tracesDir, name);
6046 if (curTracesFile.exists()) {
6047 if (lastTracesFile != null) {
6048 curTracesFile.renameTo(lastTracesFile);
6049 } else {
6050 curTracesFile.delete();
6051 }
6052 }
6053 lastTracesFile = curTracesFile;
6054 }
6055 tracesFile.renameTo(curTracesFile);
6056 } finally {
6057 StrictMode.setThreadPolicy(oldPolicy);
6058 }
6059 }
6060
Michal Karpinskida34cd42019-04-02 19:46:52 +01006061 boolean isAssociatedCompanionApp(int userId, int uid) {
6062 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6063 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006064 return false;
6065 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006066 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006067 }
6068
Issei Suzuki734bc942019-06-05 13:59:52 +02006069 void notifySingleTaskDisplayEmpty(int displayId) {
6070 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6071 }
6072
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006073 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006074 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006075
6076
Wale Ogunwale98875612018-10-12 07:53:02 -07006077 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6078 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006079
Riddle Hsud93a6c42018-11-29 21:50:06 +08006080 H(Looper looper) {
6081 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006082 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006083
6084 @Override
6085 public void handleMessage(Message msg) {
6086 switch (msg.what) {
6087 case REPORT_TIME_TRACKER_MSG: {
6088 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6089 tracker.deliverResult(mContext);
6090 } break;
6091 }
6092 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006093 }
6094
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006095 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006096 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006097
6098 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006099 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006100 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006101
6102 @Override
6103 public void handleMessage(Message msg) {
6104 switch (msg.what) {
6105 case DISMISS_DIALOG_UI_MSG: {
6106 final Dialog d = (Dialog) msg.obj;
6107 d.dismiss();
6108 break;
6109 }
6110 }
6111 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006112 }
6113
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006114 final class LocalService extends ActivityTaskManagerInternal {
6115 @Override
6116 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006117 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006118 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006119 }
6120
6121 @Override
6122 public ComponentName getHomeActivityForUser(int userId) {
6123 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006124 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006125 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006126 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006127 }
6128 }
6129
6130 @Override
6131 public void onLocalVoiceInteractionStarted(IBinder activity,
6132 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6133 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006134 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006135 }
6136 }
6137
6138 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006139 public void notifySingleTaskDisplayDrawn(int displayId) {
6140 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6141 }
6142
6143 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006144 public void notifyAppTransitionFinished() {
6145 synchronized (mGlobalLock) {
6146 mStackSupervisor.notifyAppTransitionDone();
6147 }
6148 }
6149
6150 @Override
6151 public void notifyAppTransitionCancelled() {
6152 synchronized (mGlobalLock) {
6153 mStackSupervisor.notifyAppTransitionDone();
6154 }
6155 }
6156
6157 @Override
6158 public List<IBinder> getTopVisibleActivities() {
6159 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006160 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006161 }
6162 }
6163
6164 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006165 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6166 int userId, Intent[] intents, Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006167 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006168 final String[] resolvedTypes = new String[intents.length];
6169
6170 // UID of the package on user userId.
6171 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6172 // packageUid may not be initialized.
6173 int packageUid = 0;
6174 final long ident = Binder.clearCallingIdentity();
6175
6176 try {
6177 for (int i = 0; i < intents.length; i++) {
6178 resolvedTypes[i] =
6179 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6180 }
6181
6182 packageUid = AppGlobals.getPackageManager().getPackageUid(
6183 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6184 } catch (RemoteException e) {
6185 // Shouldn't happen.
6186 } finally {
6187 Binder.restoreCallingIdentity(ident);
6188 }
6189
Riddle Hsu591bf612019-02-14 17:55:31 +08006190 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006191 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006192 intents, resolvedTypes, null /* resultTo */,
6193 SafeActivityOptions.fromBundle(bOptions), userId,
6194 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6195 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006196 }
6197
6198 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006199 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006200 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6201 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6202 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006203 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006204 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006205 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006206 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006207 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6208 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006209 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006210 }
6211 }
6212
6213 @Override
6214 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006215 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6216 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6217 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6218 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006219 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006220 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006221 synchronized (mGlobalLock) {
6222 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006223 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6224 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6225 reason, validateIncomingUser, originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006226 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006227 }
6228 }
6229
6230 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006231 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006232 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6233 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006234 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006235 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006236 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006237 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006238 false /*validateIncomingUser*/);
6239 }
6240
6241 @Override
lumark588a3e82018-07-20 18:53:54 +08006242 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006243 synchronized (mGlobalLock) {
6244
6245 // We might change the visibilities here, so prepare an empty app transition which
6246 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006247 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006248 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006249 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006250 return;
6251 }
Louis Chang677921f2019-12-06 16:44:24 +08006252 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006253 final boolean wasTransitionSet =
6254 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006255 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006256 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006257 }
Louis Chang149d5c82019-12-30 09:47:39 +08006258 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006259
6260 // If there was a transition set already we don't want to interfere with it as we
6261 // might be starting it too early.
6262 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006263 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006264 }
6265 }
6266 if (callback != null) {
6267 callback.run();
6268 }
6269 }
6270
6271 @Override
6272 public void notifyKeyguardTrustedChanged() {
6273 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006274 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006275 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006276 }
6277 }
6278 }
6279
6280 /**
6281 * Called after virtual display Id is updated by
6282 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6283 * {@param vrVr2dDisplayId}.
6284 */
6285 @Override
6286 public void setVr2dDisplayId(int vr2dDisplayId) {
6287 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6288 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006289 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006290 }
6291 }
6292
6293 @Override
6294 public void setFocusedActivity(IBinder token) {
6295 synchronized (mGlobalLock) {
6296 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6297 if (r == null) {
6298 throw new IllegalArgumentException(
6299 "setFocusedActivity: No activity record matching token=" + token);
6300 }
Louis Chang19443452018-10-09 12:10:21 +08006301 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006302 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006303 }
6304 }
6305 }
6306
6307 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006308 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006309 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006310 }
6311
6312 @Override
6313 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006314 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006315 }
6316
6317 @Override
6318 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006319 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006320 }
6321
6322 @Override
6323 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6324 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6325 }
6326
6327 @Override
6328 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006329 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006330 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006331
6332 @Override
6333 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6334 synchronized (mGlobalLock) {
6335 mActiveVoiceInteractionServiceComponent = component;
6336 }
6337 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006338
6339 @Override
6340 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6341 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6342 return;
6343 }
6344 synchronized (mGlobalLock) {
6345 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6346 if (types == null) {
6347 if (uid < 0) {
6348 return;
6349 }
6350 types = new ArrayMap<>();
6351 mAllowAppSwitchUids.put(userId, types);
6352 }
6353 if (uid < 0) {
6354 types.remove(type);
6355 } else {
6356 types.put(type, uid);
6357 }
6358 }
6359 }
6360
6361 @Override
6362 public void onUserStopped(int userId) {
6363 synchronized (mGlobalLock) {
6364 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6365 mAllowAppSwitchUids.remove(userId);
6366 }
6367 }
6368
6369 @Override
6370 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6371 synchronized (mGlobalLock) {
6372 return ActivityTaskManagerService.this.isGetTasksAllowed(
6373 caller, callingPid, callingUid);
6374 }
6375 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006376
Riddle Hsua0536432019-02-16 00:38:59 +08006377 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006378 @Override
6379 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006380 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006381 mProcessNames.put(proc.mName, proc.mUid, proc);
6382 }
6383 }
6384
Riddle Hsua0536432019-02-16 00:38:59 +08006385 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006386 @Override
6387 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006388 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006389 mProcessNames.remove(name, uid);
6390 }
6391 }
6392
Riddle Hsua0536432019-02-16 00:38:59 +08006393 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006394 @Override
6395 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006396 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006397 if (proc == mHomeProcess) {
6398 mHomeProcess = null;
6399 }
6400 if (proc == mPreviousProcess) {
6401 mPreviousProcess = null;
6402 }
6403 }
6404 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006405
Riddle Hsua0536432019-02-16 00:38:59 +08006406 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006407 @Override
6408 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006409 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006410 return mTopProcessState;
6411 }
6412 }
6413
Riddle Hsua0536432019-02-16 00:38:59 +08006414 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006415 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006416 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006417 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006418 return proc == mHeavyWeightProcess;
6419 }
6420 }
6421
Riddle Hsua0536432019-02-16 00:38:59 +08006422 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006423 @Override
6424 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006425 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006426 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6427 }
6428 }
6429
6430 @Override
6431 public void finishHeavyWeightApp() {
6432 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006433 if (mHeavyWeightProcess != null) {
6434 mHeavyWeightProcess.finishActivities();
6435 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006436 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6437 mHeavyWeightProcess);
6438 }
6439 }
6440
Riddle Hsua0536432019-02-16 00:38:59 +08006441 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006442 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006443 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006444 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006445 return isSleepingLocked();
6446 }
6447 }
6448
6449 @Override
6450 public boolean isShuttingDown() {
6451 synchronized (mGlobalLock) {
6452 return mShuttingDown;
6453 }
6454 }
6455
6456 @Override
6457 public boolean shuttingDown(boolean booted, int timeout) {
6458 synchronized (mGlobalLock) {
6459 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006460 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006461 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006462 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006463 return mStackSupervisor.shutdownLocked(timeout);
6464 }
6465 }
6466
6467 @Override
6468 public void enableScreenAfterBoot(boolean booted) {
6469 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006470 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006471 mWindowManager.enableScreenAfterBoot();
6472 updateEventDispatchingLocked(booted);
6473 }
6474 }
6475
6476 @Override
6477 public boolean showStrictModeViolationDialog() {
6478 synchronized (mGlobalLock) {
6479 return mShowDialogs && !mSleeping && !mShuttingDown;
6480 }
6481 }
6482
6483 @Override
6484 public void showSystemReadyErrorDialogsIfNeeded() {
6485 synchronized (mGlobalLock) {
6486 try {
6487 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6488 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6489 + " data partition or your device will be unstable.");
6490 mUiHandler.post(() -> {
6491 if (mShowDialogs) {
6492 AlertDialog d = new BaseErrorDialog(mUiContext);
6493 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6494 d.setCancelable(false);
6495 d.setTitle(mUiContext.getText(R.string.android_system_label));
6496 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6497 d.setButton(DialogInterface.BUTTON_POSITIVE,
6498 mUiContext.getText(R.string.ok),
6499 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6500 d.show();
6501 }
6502 });
6503 }
6504 } catch (RemoteException e) {
6505 }
6506
6507 if (!Build.isBuildConsistent()) {
6508 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6509 mUiHandler.post(() -> {
6510 if (mShowDialogs) {
6511 AlertDialog d = new BaseErrorDialog(mUiContext);
6512 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6513 d.setCancelable(false);
6514 d.setTitle(mUiContext.getText(R.string.android_system_label));
6515 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6516 d.setButton(DialogInterface.BUTTON_POSITIVE,
6517 mUiContext.getText(R.string.ok),
6518 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6519 d.show();
6520 }
6521 });
6522 }
6523 }
6524 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006525
6526 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006527 public void onProcessMapped(int pid, WindowProcessController proc) {
6528 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006529 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006530 }
6531 }
6532
6533 @Override
6534 public void onProcessUnMapped(int pid) {
6535 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006536 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006537 }
6538 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006539
6540 @Override
6541 public void onPackageDataCleared(String name) {
6542 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006543 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006544 mAppWarnings.onPackageDataCleared(name);
6545 }
6546 }
6547
6548 @Override
6549 public void onPackageUninstalled(String name) {
6550 synchronized (mGlobalLock) {
6551 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006552 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006553 }
6554 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006555
6556 @Override
6557 public void onPackageAdded(String name, boolean replacing) {
6558 synchronized (mGlobalLock) {
6559 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6560 }
6561 }
6562
6563 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006564 public void onPackageReplaced(ApplicationInfo aInfo) {
6565 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006566 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006567 }
6568 }
6569
6570 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006571 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6572 synchronized (mGlobalLock) {
6573 return compatibilityInfoForPackageLocked(ai);
6574 }
6575 }
6576
Yunfan Chen75157d72018-07-27 14:47:21 +09006577 /**
6578 * Set the corresponding display information for the process global configuration. To be
6579 * called when we need to show IME on a different display.
6580 *
6581 * @param pid The process id associated with the IME window.
6582 * @param displayId The ID of the display showing the IME.
6583 */
6584 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006585 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006586 // Don't update process-level configuration for Multi-Client IME process since other
6587 // IMEs on other displays will also receive this configuration change due to IME
6588 // services use the same application config/context.
6589 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006590
Yunfan Chen75157d72018-07-27 14:47:21 +09006591 if (pid == MY_PID || pid < 0) {
6592 if (DEBUG_CONFIGURATION) {
6593 Slog.w(TAG,
6594 "Trying to update display configuration for system/invalid process.");
6595 }
6596 return;
6597 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006598 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006599 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006600 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006601 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006602 // Call might come when display is not yet added or has been removed.
6603 if (DEBUG_CONFIGURATION) {
6604 Slog.w(TAG, "Trying to update display configuration for non-existing "
6605 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006606 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006607 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006608 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006609 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006610 if (process == null) {
6611 if (DEBUG_CONFIGURATION) {
6612 Slog.w(TAG, "Trying to update display configuration for invalid "
6613 + "process, pid=" + pid);
6614 }
6615 return;
6616 }
lumarkddc77fb2019-06-27 22:22:23 +08006617 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006618 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006619 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006620 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006621
6622 @Override
6623 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006624 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006625 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006626 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006627 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006628 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006629 }
6630 }
6631 }
6632
6633 @Override
6634 public void clearPendingResultForActivity(IBinder activityToken,
6635 WeakReference<PendingIntentRecord> pir) {
6636 synchronized (mGlobalLock) {
6637 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6638 if (r != null && r.pendingResults != null) {
6639 r.pendingResults.remove(pir);
6640 }
6641 }
6642 }
6643
6644 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006645 public ActivityTokens getTopActivityForTask(int taskId) {
6646 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006647 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006648 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006649 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6650 + " Requested task not found");
6651 return null;
6652 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006653 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006654 if (activity == null) {
6655 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6656 + " Requested activity not found");
6657 return null;
6658 }
6659 if (!activity.attachedToProcess()) {
6660 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6661 + activity);
6662 return null;
6663 }
6664 return new ActivityTokens(activity.appToken, activity.assistToken,
6665 activity.app.getThread());
6666 }
6667 }
6668
6669 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006670 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006671 @Nullable String featureId, int callingUid, int userId, IBinder token,
6672 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6673 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006674 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006675 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6676 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006677 }
6678 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006679
6680 @Override
6681 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6682 synchronized (mGlobalLock) {
6683 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6684 if (r == null) {
6685 return null;
6686 }
6687 if (r.mServiceConnectionsHolder == null) {
6688 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6689 ActivityTaskManagerService.this, r);
6690 }
6691
6692 return r.mServiceConnectionsHolder;
6693 }
6694 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006695
6696 @Override
6697 public Intent getHomeIntent() {
6698 synchronized (mGlobalLock) {
6699 return ActivityTaskManagerService.this.getHomeIntent();
6700 }
6701 }
6702
6703 @Override
6704 public boolean startHomeActivity(int userId, String reason) {
6705 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006706 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006707 }
6708 }
6709
6710 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006711 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006712 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006713 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006714 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006715 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006716 }
Chilun8b1f1be2019-03-13 17:14:36 +08006717 }
6718
6719 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006720 public boolean startHomeOnAllDisplays(int userId, String reason) {
6721 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006722 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006723 }
6724 }
6725
Riddle Hsua0536432019-02-16 00:38:59 +08006726 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006727 @Override
6728 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006729 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006730 if (mFactoryTest == FACTORY_TEST_OFF) {
6731 return false;
6732 }
6733 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6734 && wpc.mName.equals(mTopComponent.getPackageName())) {
6735 return true;
6736 }
6737 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6738 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6739 }
6740 }
6741
6742 @Override
6743 public void updateTopComponentForFactoryTest() {
6744 synchronized (mGlobalLock) {
6745 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6746 return;
6747 }
6748 final ResolveInfo ri = mContext.getPackageManager()
6749 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6750 final CharSequence errorMsg;
6751 if (ri != null) {
6752 final ActivityInfo ai = ri.activityInfo;
6753 final ApplicationInfo app = ai.applicationInfo;
6754 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6755 mTopAction = Intent.ACTION_FACTORY_TEST;
6756 mTopData = null;
6757 mTopComponent = new ComponentName(app.packageName, ai.name);
6758 errorMsg = null;
6759 } else {
6760 errorMsg = mContext.getResources().getText(
6761 com.android.internal.R.string.factorytest_not_system);
6762 }
6763 } else {
6764 errorMsg = mContext.getResources().getText(
6765 com.android.internal.R.string.factorytest_no_action);
6766 }
6767 if (errorMsg == null) {
6768 return;
6769 }
6770
6771 mTopAction = null;
6772 mTopData = null;
6773 mTopComponent = null;
6774 mUiHandler.post(() -> {
6775 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6776 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006777 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006778 });
6779 }
6780 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006781
Riddle Hsua0536432019-02-16 00:38:59 +08006782 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006783 @Override
6784 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6785 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006786 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006787 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006788 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006789
6790 wpc.clearRecentTasks();
6791 wpc.clearActivities();
6792
6793 if (wpc.isInstrumenting()) {
6794 finishInstrumentationCallback.run();
6795 }
6796
Jorim Jaggid0752812018-10-16 16:07:20 +02006797 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006798 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006799 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006800 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006801 // If there was nothing to resume, and we are not already restarting
6802 // this process, but there is a visible activity that is hosted by the
6803 // process...then make sure all visible activities are running, taking
6804 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006805 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006806 !PRESERVE_WINDOWS);
6807 }
6808 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006809 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006810 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006811 }
6812 }
6813 }
6814
6815 @Override
6816 public void closeSystemDialogs(String reason) {
6817 enforceNotIsolatedCaller("closeSystemDialogs");
6818
6819 final int pid = Binder.getCallingPid();
6820 final int uid = Binder.getCallingUid();
6821 final long origId = Binder.clearCallingIdentity();
6822 try {
6823 synchronized (mGlobalLock) {
6824 // Only allow this from foreground processes, so that background
6825 // applications can't abuse it to prevent system UI from being shown.
6826 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006827 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006828 if (!proc.isPerceptible()) {
6829 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6830 + " from background process " + proc);
6831 return;
6832 }
6833 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006834 mWindowManager.closeSystemDialogs(reason);
6835
Louis Chang149d5c82019-12-30 09:47:39 +08006836 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006837 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006838 // Call into AM outside the synchronized block.
6839 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006840 } finally {
6841 Binder.restoreCallingIdentity(origId);
6842 }
6843 }
6844
6845 @Override
6846 public void cleanupDisabledPackageComponents(
6847 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6848 synchronized (mGlobalLock) {
6849 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006850 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006851 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006852 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006853 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006854 }
6855
6856 // Clean-up disabled tasks
6857 getRecentTasks().cleanupDisabledPackageTasksLocked(
6858 packageName, disabledClasses, userId);
6859 }
6860 }
6861
6862 @Override
6863 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6864 int userId) {
6865 synchronized (mGlobalLock) {
6866
6867 boolean didSomething =
6868 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006869 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006870 null, doit, evenPersistent, userId);
6871 return didSomething;
6872 }
6873 }
6874
6875 @Override
6876 public void resumeTopActivities(boolean scheduleIdle) {
6877 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006878 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006880 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006881 }
6882 }
6883 }
6884
Riddle Hsua0536432019-02-16 00:38:59 +08006885 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006886 @Override
6887 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006888 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006889 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6890 }
6891 }
6892
Riddle Hsua0536432019-02-16 00:38:59 +08006893 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006894 @Override
6895 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006896 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006897 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6898 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6899 }
6900 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006901 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006902 } finally {
6903 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6904 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006905 }
6906 }
6907
6908 @Override
6909 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6910 try {
6911 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6912 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6913 }
6914 } catch (RemoteException ex) {
6915 throw new SecurityException("Fail to check is caller a privileged app", ex);
6916 }
6917
6918 synchronized (mGlobalLock) {
6919 final long ident = Binder.clearCallingIdentity();
6920 try {
6921 if (mAmInternal.shouldConfirmCredentials(userId)) {
6922 if (mKeyguardController.isKeyguardLocked()) {
6923 // Showing launcher to avoid user entering credential twice.
6924 startHomeActivity(currentUserId, "notifyLockedProfile");
6925 }
Louis Chang149d5c82019-12-30 09:47:39 +08006926 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006927 }
6928 } finally {
6929 Binder.restoreCallingIdentity(ident);
6930 }
6931 }
6932 }
6933
6934 @Override
6935 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6936 mAmInternal.enforceCallingPermission(
6937 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6938
6939 synchronized (mGlobalLock) {
6940 final long ident = Binder.clearCallingIdentity();
6941 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006942 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6943 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006944 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006945 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6946 UserHandle.CURRENT);
6947 } finally {
6948 Binder.restoreCallingIdentity(ident);
6949 }
6950 }
6951 }
6952
6953 @Override
6954 public void writeActivitiesToProto(ProtoOutputStream proto) {
6955 synchronized (mGlobalLock) {
6956 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006957 mRootWindowContainer.dumpDebug(
6958 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006959 }
6960 }
6961
6962 @Override
6963 public void saveANRState(String reason) {
6964 synchronized (mGlobalLock) {
6965 final StringWriter sw = new StringWriter();
6966 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6967 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6968 if (reason != null) {
6969 pw.println(" Reason: " + reason);
6970 }
6971 pw.println();
6972 getActivityStartController().dump(pw, " ", null);
6973 pw.println();
6974 pw.println("-------------------------------------------------------------------------------");
6975 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6976 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6977 "" /* header */);
6978 pw.println();
6979 pw.close();
6980
6981 mLastANRState = sw.toString();
6982 }
6983 }
6984
6985 @Override
6986 public void clearSavedANRState() {
6987 synchronized (mGlobalLock) {
6988 mLastANRState = null;
6989 }
6990 }
6991
6992 @Override
6993 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6994 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6995 synchronized (mGlobalLock) {
6996 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6997 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6998 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6999 dumpLastANRLocked(pw);
7000 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7001 dumpLastANRTracesLocked(pw);
7002 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7003 dumpActivityStarterLocked(pw, dumpPackage);
7004 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7005 dumpActivityContainersLocked(pw);
7006 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7007 if (getRecentTasks() != null) {
7008 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7009 }
7010 }
7011 }
7012 }
7013
7014 @Override
7015 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7016 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7017 int wakefulness) {
7018 synchronized (mGlobalLock) {
7019 if (mHomeProcess != null && (dumpPackage == null
7020 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7021 if (needSep) {
7022 pw.println();
7023 needSep = false;
7024 }
7025 pw.println(" mHomeProcess: " + mHomeProcess);
7026 }
7027 if (mPreviousProcess != null && (dumpPackage == null
7028 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7029 if (needSep) {
7030 pw.println();
7031 needSep = false;
7032 }
7033 pw.println(" mPreviousProcess: " + mPreviousProcess);
7034 }
7035 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7036 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7037 StringBuilder sb = new StringBuilder(128);
7038 sb.append(" mPreviousProcessVisibleTime: ");
7039 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7040 pw.println(sb);
7041 }
7042 if (mHeavyWeightProcess != null && (dumpPackage == null
7043 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7044 if (needSep) {
7045 pw.println();
7046 needSep = false;
7047 }
7048 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7049 }
7050 if (dumpPackage == null) {
7051 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007052 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007053 }
7054 if (dumpAll) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007055 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7056 if (dumpPackage == null && topFocusedStack != null) {
7057 pw.println(" mConfigWillChange: " + topFocusedStack.mConfigWillChange);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007058 }
7059 if (mCompatModePackages.getPackages().size() > 0) {
7060 boolean printed = false;
7061 for (Map.Entry<String, Integer> entry
7062 : mCompatModePackages.getPackages().entrySet()) {
7063 String pkg = entry.getKey();
7064 int mode = entry.getValue();
7065 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7066 continue;
7067 }
7068 if (!printed) {
7069 pw.println(" mScreenCompatPackages:");
7070 printed = true;
7071 }
7072 pw.println(" " + pkg + ": " + mode);
7073 }
7074 }
7075 }
7076
7077 if (dumpPackage == null) {
7078 pw.println(" mWakefulness="
7079 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007080 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007081 if (mRunningVoice != null) {
7082 pw.println(" mRunningVoice=" + mRunningVoice);
7083 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7084 }
7085 pw.println(" mSleeping=" + mSleeping);
7086 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7087 pw.println(" mVrController=" + mVrController);
7088 }
7089 if (mCurAppTimeTracker != null) {
7090 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7091 }
7092 if (mAllowAppSwitchUids.size() > 0) {
7093 boolean printed = false;
7094 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7095 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7096 for (int j = 0; j < types.size(); j++) {
7097 if (dumpPackage == null ||
7098 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7099 if (needSep) {
7100 pw.println();
7101 needSep = false;
7102 }
7103 if (!printed) {
7104 pw.println(" mAllowAppSwitchUids:");
7105 printed = true;
7106 }
7107 pw.print(" User ");
7108 pw.print(mAllowAppSwitchUids.keyAt(i));
7109 pw.print(": Type ");
7110 pw.print(types.keyAt(j));
7111 pw.print(" = ");
7112 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7113 pw.println();
7114 }
7115 }
7116 }
7117 }
7118 if (dumpPackage == null) {
7119 if (mController != null) {
7120 pw.println(" mController=" + mController
7121 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7122 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007123 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7124 pw.println(" mLaunchingActivityWakeLock="
7125 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007126 }
7127
7128 return needSep;
7129 }
7130 }
7131
7132 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007133 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7134 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007135 synchronized (mGlobalLock) {
7136 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007137 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007138 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7139 if (topFocusedStack != null) {
7140 proto.write(CONFIG_WILL_CHANGE, topFocusedStack.mConfigWillChange);
7141 }
sanryhuang498e77e2018-12-06 14:57:01 +08007142 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7143 if (mRunningVoice != null) {
7144 final long vrToken = proto.start(
7145 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7146 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7147 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007148 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007149 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7150 proto.end(vrToken);
7151 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007152 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007153 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007154 if (mController != null) {
7155 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007156 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7157 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007158 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7159 proto.end(token);
7160 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007161 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7162 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007163 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007164 }
7165
7166 if (mHomeProcess != null && (dumpPackage == null
7167 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007168 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007169 }
7170
7171 if (mPreviousProcess != null && (dumpPackage == null
7172 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007173 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007174 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7175 }
7176
7177 if (mHeavyWeightProcess != null && (dumpPackage == null
7178 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007179 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007180 }
7181
7182 for (Map.Entry<String, Integer> entry
7183 : mCompatModePackages.getPackages().entrySet()) {
7184 String pkg = entry.getKey();
7185 int mode = entry.getValue();
7186 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7187 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7188 proto.write(PACKAGE, pkg);
7189 proto.write(MODE, mode);
7190 proto.end(compatToken);
7191 }
7192 }
7193
7194 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007195 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007196 }
7197
7198 }
7199 }
7200
7201 @Override
7202 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7203 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7204 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007205 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7206 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007207 }
7208
7209 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007210 public void dumpForOom(PrintWriter pw) {
7211 synchronized (mGlobalLock) {
7212 pw.println(" mHomeProcess: " + mHomeProcess);
7213 pw.println(" mPreviousProcess: " + mPreviousProcess);
7214 if (mHeavyWeightProcess != null) {
7215 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7216 }
7217 }
7218 }
7219
7220 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007221 public boolean canGcNow() {
7222 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007223 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007224 }
7225 }
7226
Riddle Hsua0536432019-02-16 00:38:59 +08007227 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007228 @Override
7229 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007230 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007231 if (mRootWindowContainer == null) {
7232 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007233 // oomadj after AMS created.
7234 return null;
7235 }
Louis Chang149d5c82019-12-30 09:47:39 +08007236 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007237 return top != null ? top.app : null;
7238 }
7239 }
7240
Riddle Hsua0536432019-02-16 00:38:59 +08007241 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007242 @Override
7243 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007244 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007245 if (mRootWindowContainer != null) {
7246 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007247 }
7248 }
7249 }
7250
7251 @Override
7252 public void scheduleDestroyAllActivities(String reason) {
7253 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007254 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007255 }
7256 }
7257
7258 @Override
7259 public void removeUser(int userId) {
7260 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007261 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007262 }
7263 }
7264
7265 @Override
7266 public boolean switchUser(int userId, UserState userState) {
7267 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007268 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007269 }
7270 }
7271
7272 @Override
7273 public void onHandleAppCrash(WindowProcessController wpc) {
7274 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007275 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007276 }
7277 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007278
7279 @Override
7280 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7281 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007282 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007283 }
7284 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007285
Riddle Hsua0536432019-02-16 00:38:59 +08007286 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007287 @Override
7288 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007289 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007290 }
7291
Riddle Hsua0536432019-02-16 00:38:59 +08007292 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007293 @Override
7294 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007295 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007296 }
7297
Riddle Hsua0536432019-02-16 00:38:59 +08007298 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007299 @Override
7300 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007301 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007302 }
7303
Riddle Hsua0536432019-02-16 00:38:59 +08007304 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007305 @Override
7306 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007307 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007308 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007309
7310 @Override
7311 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007312 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007313 mPendingTempWhitelist.put(uid, tag);
7314 }
7315 }
7316
7317 @Override
7318 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007319 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007320 mPendingTempWhitelist.remove(uid);
7321 }
7322 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007323
7324 @Override
7325 public boolean handleAppCrashInActivityController(String processName, int pid,
7326 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7327 Runnable killCrashingAppCallback) {
7328 synchronized (mGlobalLock) {
7329 if (mController == null) {
7330 return false;
7331 }
7332
7333 try {
7334 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7335 stackTrace)) {
7336 killCrashingAppCallback.run();
7337 return true;
7338 }
7339 } catch (RemoteException e) {
7340 mController = null;
7341 Watchdog.getInstance().setActivityController(null);
7342 }
7343 return false;
7344 }
7345 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007346
7347 @Override
7348 public void removeRecentTasksByPackageName(String packageName, int userId) {
7349 synchronized (mGlobalLock) {
7350 mRecentTasks.removeTasksByPackageName(packageName, userId);
7351 }
7352 }
7353
7354 @Override
7355 public void cleanupRecentTasksForUser(int userId) {
7356 synchronized (mGlobalLock) {
7357 mRecentTasks.cleanupLocked(userId);
7358 }
7359 }
7360
7361 @Override
7362 public void loadRecentTasksForUser(int userId) {
7363 synchronized (mGlobalLock) {
7364 mRecentTasks.loadUserRecentsLocked(userId);
7365 }
7366 }
7367
7368 @Override
7369 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7370 synchronized (mGlobalLock) {
7371 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7372 }
7373 }
7374
7375 @Override
7376 public void flushRecentTasks() {
7377 mRecentTasks.flush();
7378 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007379
7380 @Override
7381 public WindowProcessController getHomeProcess() {
7382 synchronized (mGlobalLock) {
7383 return mHomeProcess;
7384 }
7385 }
7386
7387 @Override
7388 public WindowProcessController getPreviousProcess() {
7389 synchronized (mGlobalLock) {
7390 return mPreviousProcess;
7391 }
7392 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007393
7394 @Override
7395 public void clearLockedTasks(String reason) {
7396 synchronized (mGlobalLock) {
7397 getLockTaskController().clearLockedTasks(reason);
7398 }
7399 }
7400
7401 @Override
7402 public void updateUserConfiguration() {
7403 synchronized (mGlobalLock) {
7404 final Configuration configuration = new Configuration(getGlobalConfiguration());
7405 final int currentUserId = mAmInternal.getCurrentUserId();
7406 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7407 configuration, currentUserId, Settings.System.canWrite(mContext));
7408 updateConfigurationLocked(configuration, null /* starting */,
7409 false /* initLocale */, false /* persistent */, currentUserId,
7410 false /* deferResume */);
7411 }
7412 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007413
7414 @Override
7415 public boolean canShowErrorDialogs() {
7416 synchronized (mGlobalLock) {
7417 return mShowDialogs && !mSleeping && !mShuttingDown
7418 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7419 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7420 mAmInternal.getCurrentUserId())
7421 && !(UserManager.isDeviceInDemoMode(mContext)
7422 && mAmInternal.getCurrentUser().isDemo());
7423 }
7424 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007425
7426 @Override
7427 public void setProfileApp(String profileApp) {
7428 synchronized (mGlobalLock) {
7429 mProfileApp = profileApp;
7430 }
7431 }
7432
7433 @Override
7434 public void setProfileProc(WindowProcessController wpc) {
7435 synchronized (mGlobalLock) {
7436 mProfileProc = wpc;
7437 }
7438 }
7439
7440 @Override
7441 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7442 synchronized (mGlobalLock) {
7443 mProfilerInfo = profilerInfo;
7444 }
7445 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007446
7447 @Override
7448 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7449 synchronized (mGlobalLock) {
7450 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7451 }
7452 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007453
7454 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007455 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
Peter Kalauskas4dc04602020-02-12 18:49:03 -08007456 boolean isLowResolution) {
7457 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007458 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007459 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007460
7461 @Override
7462 public boolean isUidForeground(int uid) {
7463 synchronized (mGlobalLock) {
7464 return ActivityTaskManagerService.this.isUidForeground(uid);
7465 }
7466 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007467
7468 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007469 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007470 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007471 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007472 }
7473 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007474
7475 @Override
7476 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007477 // Translate package names into UIDs
7478 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007479 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007480 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7481 if (uid >= 0) {
7482 result.add(uid);
7483 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007484 }
7485 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007486 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007487 }
7488 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007489 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007490}