blob: 98c8b61b07422ea4f804f9a18ea6923117db9f1f [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;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700291import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400292import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700293import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700295import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700296import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000297import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700298import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700299
300/**
301 * System service for managing activities and their containers (task, stacks, displays,... ).
302 *
303 * {@hide}
304 */
305public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700306 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800307 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000308 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700309 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
310 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
311 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
312 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700313 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700314
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700316 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700318 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100319 // How long we permit background activity starts after an activity in the process
320 // started or finished.
321 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700322
Wale Ogunwale98875612018-10-12 07:53:02 -0700323 /** Used to indicate that an app transition should be animated. */
324 static final boolean ANIMATE = true;
325
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700326 /** Hardware-reported OpenGLES version. */
327 final int GL_ES_VERSION;
328
Wale Ogunwale31913b52018-10-13 08:29:31 -0700329 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
330 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
331 public static final String DUMP_LASTANR_CMD = "lastanr" ;
332 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
333 public static final String DUMP_STARTER_CMD = "starter" ;
334 public static final String DUMP_CONTAINERS_CMD = "containers" ;
335 public static final String DUMP_RECENTS_CMD = "recents" ;
336 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
337
Wale Ogunwale64258362018-10-16 15:13:37 -0700338 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
339 public static final int RELAUNCH_REASON_NONE = 0;
340 /** This activity is being relaunched due to windowing mode change. */
341 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
342 /** This activity is being relaunched due to a free-resize operation. */
343 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
344
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700345 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700346
Wale Ogunwalef6733932018-06-27 05:14:34 -0700347 /**
348 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
349 * change at runtime. Use mContext for non-UI purposes.
350 */
351 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700352 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700353 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700354 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700355 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700356 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700357 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800358 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800359 @VisibleForTesting
360 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700361 PowerManagerInternal mPowerManagerInternal;
362 private UsageStatsManagerInternal mUsageStatsInternal;
363
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700364 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700365 IntentFirewall mIntentFirewall;
366
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700367 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800368 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800369 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700370 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800371 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
372 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
373 *
374 * @see WindowManagerThreadPriorityBooster
375 */
376 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700377 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800378 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700379 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700380 private UserManagerService mUserManager;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800381 private AppOpsManager mAppOpsManager;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700382 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800383 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700384 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700385 /** All processes currently running that might have a window organized by name. */
386 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100387 /** All processes we currently have running mapped by pid and uid */
388 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700389 /** This is the process holding what we currently consider to be the "home" activity. */
390 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700391 /** The currently running heavy-weight process, if any. */
392 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700393 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700394 /**
395 * This is the process holding the activity the user last visited that is in a different process
396 * from the one they are currently in.
397 */
398 WindowProcessController mPreviousProcess;
399 /** The time at which the previous process was last visible. */
400 long mPreviousProcessVisibleTime;
401
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700402 /** List of intents that were used to start the most recent tasks. */
403 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700404 /** State of external calls telling us if the device is awake or asleep. */
405 private boolean mKeyguardShown = false;
406
407 // Wrapper around VoiceInteractionServiceManager
408 private AssistUtils mAssistUtils;
409
410 // VoiceInteraction session ID that changes for each new request except when
411 // being called for multi-window assist in a single session.
412 private int mViSessionId = 1000;
413
414 // How long to wait in getAssistContextExtras for the activity and foreground services
415 // to respond with the result.
416 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
417
418 // How long top wait when going through the modern assist (which doesn't need to block
419 // on getting this result before starting to launch its UI).
420 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
421
422 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
423 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
424
Alison Cichowlas3e340502018-08-07 17:15:01 -0400425 // Permission tokens are used to temporarily granted a trusted app the ability to call
426 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
427 // showing any appropriate error messages to the user.
428 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
429 10 * MINUTE_IN_MILLIS;
430
431 // How long before the service actually expires a token. This is slightly longer than
432 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
433 // expiration exception.
434 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
435 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
436
437 // How long the service will remember expired tokens, for the purpose of providing error
438 // messaging when a client uses an expired token.
439 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
440 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
441
442 // Activity tokens of system activities that are delegating their call to
443 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
444 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
445
446 // Permission tokens that have expired, but we remember for error reporting.
447 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
448
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700449 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
450
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700451 // Keeps track of the active voice interaction service component, notified from
452 // VoiceInteractionManagerService
453 ComponentName mActiveVoiceInteractionServiceComponent;
454
Michal Karpinskida34cd42019-04-02 19:46:52 +0100455 // A map userId and all its companion app uids
456 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000457
Wale Ogunwalee2172292018-10-25 10:11:10 -0700458 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700459 KeyguardController mKeyguardController;
460 private final ClientLifecycleManager mLifecycleManager;
461 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700462 /** The controller for all operations related to locktask. */
463 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700464 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700465
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700466 boolean mSuppressResizeConfigChanges;
467
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700468 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700469 new UpdateConfigurationResult();
470
471 static final class UpdateConfigurationResult {
472 // Configuration changes that were updated.
473 int changes;
474 // If the activity was relaunched to match the new configuration.
475 boolean activityRelaunched;
476
477 void reset() {
478 changes = 0;
479 activityRelaunched = false;
480 }
481 }
482
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700483 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700484 private int mConfigurationSeq;
485 // To cache the list of supported system locales
486 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700487
488 /**
489 * Temp object used when global and/or display override configuration is updated. It is also
490 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
491 * anyone...
492 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700493 private Configuration mTempConfig = new Configuration();
494
Wale Ogunwalef6733932018-06-27 05:14:34 -0700495 /** Temporary to avoid allocations. */
496 final StringBuilder mStringBuilder = new StringBuilder(256);
497
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700498 // Amount of time after a call to stopAppSwitches() during which we will
499 // prevent further untrusted switches from happening.
500 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
501
502 /**
503 * The time at which we will allow normal application switches again,
504 * after a call to {@link #stopAppSwitches()}.
505 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700506 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700507 /**
508 * This is set to true after the first switch after mAppSwitchesAllowedTime
509 * is set; any switches after that will clear the time.
510 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700511 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700512
Ricky Wai906af482019-06-03 17:25:28 +0100513 /**
514 * Last stop app switches time, apps finished before this time cannot start background activity
515 * even if they are in grace period.
516 */
517 private long mLastStopAppSwitchesTime;
518
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700519 IActivityController mController = null;
520 boolean mControllerIsAMonkey = false;
521
Wale Ogunwale214f3482018-10-04 11:00:47 -0700522 final int mFactoryTest;
523
524 /** Used to control how we initialize the service. */
525 ComponentName mTopComponent;
526 String mTopAction = Intent.ACTION_MAIN;
527 String mTopData;
528
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800529 /** Profiling app information. */
530 String mProfileApp = null;
531 WindowProcessController mProfileProc = null;
532 ProfilerInfo mProfilerInfo = null;
533
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700534 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700535 * Dump of the activity state at the time of the last ANR. Cleared after
536 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
537 */
538 String mLastANRState;
539
540 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700541 * Used to retain an update lock when the foreground activity is in
542 * immersive mode.
543 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700544 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700545
546 /**
547 * Packages that are being allowed to perform unrestricted app switches. Mapping is
548 * User -> Type -> uid.
549 */
550 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
551
552 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700553 private int mThumbnailWidth;
554 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700555
556 /**
557 * Flag that indicates if multi-window is enabled.
558 *
559 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
560 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
561 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
562 * At least one of the forms of multi-window must be enabled in order for this flag to be
563 * initialized to 'true'.
564 *
565 * @see #mSupportsSplitScreenMultiWindow
566 * @see #mSupportsFreeformWindowManagement
567 * @see #mSupportsPictureInPicture
568 * @see #mSupportsMultiDisplay
569 */
570 boolean mSupportsMultiWindow;
571 boolean mSupportsSplitScreenMultiWindow;
572 boolean mSupportsFreeformWindowManagement;
573 boolean mSupportsPictureInPicture;
574 boolean mSupportsMultiDisplay;
575 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700576 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700577
578 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
579
580 // VR Vr2d Display Id.
581 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700582
Wale Ogunwalef6733932018-06-27 05:14:34 -0700583 /**
584 * Set while we are wanting to sleep, to prevent any
585 * activities from being started/resumed.
586 *
587 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
588 *
589 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
590 * while in the sleep state until there is a pending transition out of sleep, in which case
591 * mSleeping is set to false, and remains false while awake.
592 *
593 * Whether mSleeping can quickly toggled between true/false without the device actually
594 * display changing states is undefined.
595 */
596 private boolean mSleeping = false;
597
598 /**
599 * The process state used for processes that are running the top activities.
600 * This changes between TOP and TOP_SLEEPING to following mSleeping.
601 */
602 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
603
Riddle Hsua0022cd2019-09-09 21:12:41 +0800604 @Retention(RetentionPolicy.SOURCE)
605 @IntDef({
606 LAYOUT_REASON_CONFIG_CHANGED,
607 LAYOUT_REASON_VISIBILITY_CHANGED,
608 })
609 @interface LayoutReason {}
610 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
611 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
612
613 /** The reasons to perform surface placement. */
614 @LayoutReason
615 private int mLayoutReasons;
616
Wale Ogunwalef6733932018-06-27 05:14:34 -0700617 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
618 // automatically. Important for devices without direct input devices.
619 private boolean mShowDialogs = true;
620
621 /** Set if we are shutting down the system, similar to sleeping. */
622 boolean mShuttingDown = false;
623
624 /**
625 * We want to hold a wake lock while running a voice interaction session, since
626 * this may happen with the screen off and we need to keep the CPU running to
627 * be able to continue to interact with the user.
628 */
629 PowerManager.WakeLock mVoiceWakeLock;
630
631 /**
632 * Set while we are running a voice interaction. This overrides sleeping while it is active.
633 */
634 IVoiceInteractionSession mRunningVoice;
635
636 /**
637 * The last resumed activity. This is identical to the current resumed activity most
638 * of the time but could be different when we're pausing one activity before we resume
639 * another activity.
640 */
641 ActivityRecord mLastResumedActivity;
642
643 /**
644 * The activity that is currently being traced as the active resumed activity.
645 *
646 * @see #updateResumedAppTrace
647 */
648 private @Nullable ActivityRecord mTracedResumedActivity;
649
650 /** If non-null, we are tracking the time the user spends in the currently focused app. */
651 AppTimeTracker mCurAppTimeTracker;
652
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700653 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700654
Wale Ogunwale53783742018-09-16 10:21:51 -0700655 /**
656 * Packages that the user has asked to have run in screen size
657 * compatibility mode instead of filling the screen.
658 */
659 CompatModePackages mCompatModePackages;
660
Wale Ogunwalef6733932018-06-27 05:14:34 -0700661 private FontScaleSettingObserver mFontScaleSettingObserver;
662
Robert Carr8a2f9132019-11-11 15:03:15 -0800663 /**
664 * Stores the registration and state of TaskOrganizers in use.
665 */
Evan Rosky0037e5f2019-11-05 10:26:24 -0800666 TaskOrganizerController mTaskOrganizerController = new TaskOrganizerController(this);
Robert Carr8a2f9132019-11-11 15:03:15 -0800667
Ricky Wai96f5c352019-04-10 18:40:17 +0100668 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000669
Wale Ogunwalef6733932018-06-27 05:14:34 -0700670 private final class FontScaleSettingObserver extends ContentObserver {
671 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
672 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
673
674 public FontScaleSettingObserver() {
675 super(mH);
676 final ContentResolver resolver = mContext.getContentResolver();
677 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
678 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
679 UserHandle.USER_ALL);
680 }
681
682 @Override
683 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
684 if (mFontScaleUri.equals(uri)) {
685 updateFontScaleIfNeeded(userId);
686 } else if (mHideErrorDialogsUri.equals(uri)) {
687 synchronized (mGlobalLock) {
688 updateShouldShowDialogsLocked(getGlobalConfiguration());
689 }
690 }
691 }
692 }
693
Riddle Hsua0536432019-02-16 00:38:59 +0800694 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
695 @Target(ElementType.METHOD)
696 @Retention(RetentionPolicy.SOURCE)
697 @interface HotPath {
698 int NONE = 0;
699 int OOM_ADJUSTMENT = 1;
700 int LRU_UPDATE = 2;
701 int PROCESS_CHANGE = 3;
702 int caller() default NONE;
703 }
704
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800705 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
706 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900707 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800708 mAmInternal.updateOomAdj();
709 }
710 };
711
Charles Chen8d98dd22018-12-26 17:36:54 +0800712 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
713 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700714 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700715 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700716 mSystemThread = ActivityThread.currentActivityThread();
717 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700718 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800719 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700720 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700721 }
722
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700723 public void onSystemReady() {
724 synchronized (mGlobalLock) {
725 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
726 PackageManager.FEATURE_CANT_SAVE_STATE);
727 mAssistUtils = new AssistUtils(mContext);
728 mVrController.onSystemReady();
729 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700730 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700731 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700732 }
733
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700734 public void onInitPowerManagement() {
735 synchronized (mGlobalLock) {
736 mStackSupervisor.initPowerManagement();
737 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
738 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
739 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
740 mVoiceWakeLock.setReferenceCounted(false);
741 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700742 }
743
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700744 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700745 mFontScaleSettingObserver = new FontScaleSettingObserver();
746 }
747
Wale Ogunwale59507092018-10-29 09:00:30 -0700748 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700749 final boolean freeformWindowManagement =
750 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
751 || Settings.Global.getInt(
752 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
753
754 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
755 final boolean supportsPictureInPicture = supportsMultiWindow &&
756 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
757 final boolean supportsSplitScreenMultiWindow =
758 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
759 final boolean supportsMultiDisplay = mContext.getPackageManager()
760 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700761 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
762 final boolean forceResizable = Settings.Global.getInt(
763 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700764 final boolean sizeCompatFreeform = Settings.Global.getInt(
765 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700766
767 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900768 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700769
770 final Configuration configuration = new Configuration();
771 Settings.System.getConfiguration(resolver, configuration);
772 if (forceRtl) {
773 // This will take care of setting the correct layout direction flags
774 configuration.setLayoutDirection(configuration.locale);
775 }
776
777 synchronized (mGlobalLock) {
778 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700779 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700780 final boolean multiWindowFormEnabled = freeformWindowManagement
781 || supportsSplitScreenMultiWindow
782 || supportsPictureInPicture
783 || supportsMultiDisplay;
784 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
785 mSupportsMultiWindow = true;
786 mSupportsFreeformWindowManagement = freeformWindowManagement;
787 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
788 mSupportsPictureInPicture = supportsPictureInPicture;
789 mSupportsMultiDisplay = supportsMultiDisplay;
790 } else {
791 mSupportsMultiWindow = false;
792 mSupportsFreeformWindowManagement = false;
793 mSupportsSplitScreenMultiWindow = false;
794 mSupportsPictureInPicture = false;
795 mSupportsMultiDisplay = false;
796 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700797 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700798 // This happens before any activities are started, so we can change global configuration
799 // in-place.
800 updateConfigurationLocked(configuration, null, true);
801 final Configuration globalConfig = getGlobalConfiguration();
802 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
803
804 // Load resources only after the current configuration has been set.
805 final Resources res = mContext.getResources();
806 mThumbnailWidth = res.getDimensionPixelSize(
807 com.android.internal.R.dimen.thumbnail_width);
808 mThumbnailHeight = res.getDimensionPixelSize(
809 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700810 }
811 }
812
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800813 public WindowManagerGlobalLock getGlobalLock() {
814 return mGlobalLock;
815 }
816
Yunfan Chen585f2932019-01-29 16:04:45 +0900817 /** For test purpose only. */
818 @VisibleForTesting
819 public ActivityTaskManagerInternal getAtmInternal() {
820 return mInternal;
821 }
822
Riddle Hsud93a6c42018-11-29 21:50:06 +0800823 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
824 Looper looper) {
825 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700826 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700827 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700828 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800829 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700830 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700831 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700832 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700833
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700834 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700835 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700836 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700837 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700838 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700839 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700840 mKeyguardController = mStackSupervisor.getKeyguardController();
841 }
842
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700843 public void onActivityManagerInternalAdded() {
844 synchronized (mGlobalLock) {
845 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
846 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
847 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700848 }
849
Yunfan Chen75157d72018-07-27 14:47:21 +0900850 int increaseConfigurationSeqLocked() {
851 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
852 return mConfigurationSeq;
853 }
854
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700855 protected ActivityStackSupervisor createStackSupervisor() {
856 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
857 supervisor.initialize();
858 return supervisor;
859 }
860
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800861 protected AppWarnings createAppWarnings(
862 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
863 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
864 }
865
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700866 public void setWindowManager(WindowManagerService wm) {
867 synchronized (mGlobalLock) {
868 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800869 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800870 mTempConfig.setToDefaults();
871 mTempConfig.setLocales(LocaleList.getDefault());
872 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800873 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700874 mLockTaskController.setWindowManager(wm);
875 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800876 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700877 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700878 }
879
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700880 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
881 synchronized (mGlobalLock) {
882 mUsageStatsInternal = usageStatsManager;
883 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700884 }
885
Wale Ogunwalef6733932018-06-27 05:14:34 -0700886 UserManagerService getUserManager() {
887 if (mUserManager == null) {
888 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
889 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
890 }
891 return mUserManager;
892 }
893
Philip P. Moltmannee295092020-02-10 08:46:26 -0800894 AppOpsManager getAppOpsManager() {
895 if (mAppOpsManager == null) {
896 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Wale Ogunwalef6733932018-06-27 05:14:34 -0700897 }
Philip P. Moltmannee295092020-02-10 08:46:26 -0800898 return mAppOpsManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700899 }
900
901 boolean hasUserRestriction(String restriction, int userId) {
902 return getUserManager().hasUserRestriction(restriction, userId);
903 }
904
Michal Karpinski15486842019-04-25 17:33:42 +0100905 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
Philip P. Moltmannee295092020-02-10 08:46:26 -0800906 final int mode = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
907 callingUid, callingPackage, /* featureId */ null, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100908 if (mode == AppOpsManager.MODE_DEFAULT) {
909 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
910 == PERMISSION_GRANTED;
911 }
912 return mode == AppOpsManager.MODE_ALLOWED;
913 }
914
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700915 @VisibleForTesting
916 protected void setRecentTasks(RecentTasks recentTasks) {
917 mRecentTasks = recentTasks;
918 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700919 }
920
921 RecentTasks getRecentTasks() {
922 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700923 }
924
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700925 ClientLifecycleManager getLifecycleManager() {
926 return mLifecycleManager;
927 }
928
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700929 ActivityStartController getActivityStartController() {
930 return mActivityStartController;
931 }
932
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700933 TaskChangeNotificationController getTaskChangeNotificationController() {
934 return mTaskChangeNotificationController;
935 }
936
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700937 LockTaskController getLockTaskController() {
938 return mLockTaskController;
939 }
940
Yunfan Chen75157d72018-07-27 14:47:21 +0900941 /**
942 * Return the global configuration used by the process corresponding to the input pid. This is
943 * usually the global configuration with some overrides specific to that process.
944 */
945 Configuration getGlobalConfigurationForCallingPid() {
946 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800947 return getGlobalConfigurationForPid(pid);
948 }
949
950 /**
951 * Return the global configuration used by the process corresponding to the given pid.
952 */
953 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900954 if (pid == MY_PID || pid < 0) {
955 return getGlobalConfiguration();
956 }
957 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100958 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900959 return app != null ? app.getConfiguration() : getGlobalConfiguration();
960 }
961 }
962
963 /**
964 * Return the device configuration info used by the process corresponding to the input pid.
965 * The value is consistent with the global configuration for the process.
966 */
967 @Override
968 public ConfigurationInfo getDeviceConfigurationInfo() {
969 ConfigurationInfo config = new ConfigurationInfo();
970 synchronized (mGlobalLock) {
971 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
972 config.reqTouchScreen = globalConfig.touchscreen;
973 config.reqKeyboardType = globalConfig.keyboard;
974 config.reqNavigation = globalConfig.navigation;
975 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
976 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
977 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
978 }
979 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
980 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
981 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
982 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700983 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900984 }
985 return config;
986 }
987
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700988 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700989 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700990 }
991
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700992 public static final class Lifecycle extends SystemService {
993 private final ActivityTaskManagerService mService;
994
995 public Lifecycle(Context context) {
996 super(context);
997 mService = new ActivityTaskManagerService(context);
998 }
999
1000 @Override
1001 public void onStart() {
1002 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001003 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001004 }
1005
Garfield Tan891146c2018-10-09 12:14:00 -07001006 @Override
1007 public void onUnlockUser(int userId) {
1008 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001009 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001010 }
1011 }
1012
1013 @Override
1014 public void onCleanupUser(int userId) {
1015 synchronized (mService.getGlobalLock()) {
1016 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1017 }
1018 }
1019
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001020 public ActivityTaskManagerService getService() {
1021 return mService;
1022 }
1023 }
1024
1025 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001026 public final int startActivity(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001027 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1028 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1029 Bundle bOptions) {
1030 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1031 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001032 UserHandle.getCallingUserId());
1033 }
1034
1035 @Override
1036 public final int startActivities(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001037 String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
1038 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001039 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001041 enforceNotIsolatedCaller(reason);
1042 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001044 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001045 callingFeatureId, intents, resolvedTypes, resultTo,
1046 SafeActivityOptions.fromBundle(bOptions), userId, reason,
1047 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001048 }
1049
1050 @Override
1051 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001052 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1053 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1054 Bundle bOptions, int userId) {
1055 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1056 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001057 true /*validateIncomingUser*/);
1058 }
1059
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001060 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001061 @Nullable String callingFeatureId, Intent intent, String resolvedType,
1062 IBinder resultTo, String resultWho, int requestCode, int startFlags,
1063 ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001064 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001065 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001067 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001068 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1069
1070 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001071 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001072 .setCaller(caller)
1073 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001074 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001075 .setResolvedType(resolvedType)
1076 .setResultTo(resultTo)
1077 .setResultWho(resultWho)
1078 .setRequestCode(requestCode)
1079 .setStartFlags(startFlags)
1080 .setProfilerInfo(profilerInfo)
1081 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001082 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001083 .execute();
1084
1085 }
1086
1087 @Override
1088 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1089 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001090 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1091 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001092 // Refuse possible leaked file descriptors
1093 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1094 throw new IllegalArgumentException("File descriptors passed in Intent");
1095 }
1096
1097 if (!(target instanceof PendingIntentRecord)) {
1098 throw new IllegalArgumentException("Bad PendingIntent object");
1099 }
1100
1101 PendingIntentRecord pir = (PendingIntentRecord)target;
1102
1103 synchronized (mGlobalLock) {
1104 // If this is coming from the currently resumed activity, it is
1105 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001106 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001107 if (stack.mResumedActivity != null &&
1108 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001109 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001110 }
1111 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001112 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001113 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001114 }
1115
1116 @Override
1117 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1118 Bundle bOptions) {
1119 // Refuse possible leaked file descriptors
1120 if (intent != null && intent.hasFileDescriptors()) {
1121 throw new IllegalArgumentException("File descriptors passed in Intent");
1122 }
1123 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1124
1125 synchronized (mGlobalLock) {
1126 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1127 if (r == null) {
1128 SafeActivityOptions.abort(options);
1129 return false;
1130 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001131 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001132 // The caller is not running... d'oh!
1133 SafeActivityOptions.abort(options);
1134 return false;
1135 }
1136 intent = new Intent(intent);
1137 // The caller is not allowed to change the data.
1138 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1139 // And we are resetting to find the next component...
1140 intent.setComponent(null);
1141
1142 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1143
1144 ActivityInfo aInfo = null;
1145 try {
1146 List<ResolveInfo> resolves =
1147 AppGlobals.getPackageManager().queryIntentActivities(
1148 intent, r.resolvedType,
1149 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1150 UserHandle.getCallingUserId()).getList();
1151
1152 // Look for the original activity in the list...
1153 final int N = resolves != null ? resolves.size() : 0;
1154 for (int i=0; i<N; i++) {
1155 ResolveInfo rInfo = resolves.get(i);
1156 if (rInfo.activityInfo.packageName.equals(r.packageName)
1157 && rInfo.activityInfo.name.equals(r.info.name)) {
1158 // We found the current one... the next matching is
1159 // after it.
1160 i++;
1161 if (i<N) {
1162 aInfo = resolves.get(i).activityInfo;
1163 }
1164 if (debug) {
1165 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1166 + "/" + r.info.name);
1167 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1168 ? "null" : aInfo.packageName + "/" + aInfo.name));
1169 }
1170 break;
1171 }
1172 }
1173 } catch (RemoteException e) {
1174 }
1175
1176 if (aInfo == null) {
1177 // Nobody who is next!
1178 SafeActivityOptions.abort(options);
1179 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1180 return false;
1181 }
1182
1183 intent.setComponent(new ComponentName(
1184 aInfo.applicationInfo.packageName, aInfo.name));
1185 intent.setFlags(intent.getFlags()&~(
1186 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1187 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1188 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1189 FLAG_ACTIVITY_NEW_TASK));
1190
1191 // Okay now we need to start the new activity, replacing the currently running activity.
1192 // This is a little tricky because we want to start the new one as if the current one is
1193 // finished, but not finish the current one first so that there is no flicker.
1194 // And thus...
1195 final boolean wasFinishing = r.finishing;
1196 r.finishing = true;
1197
1198 // Propagate reply information over to the new activity.
1199 final ActivityRecord resultTo = r.resultTo;
1200 final String resultWho = r.resultWho;
1201 final int requestCode = r.requestCode;
1202 r.resultTo = null;
1203 if (resultTo != null) {
1204 resultTo.removeResultsLocked(r, resultWho, requestCode);
1205 }
1206
1207 final long origId = Binder.clearCallingIdentity();
1208 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001209 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001210 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001211 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001212 .setResolvedType(r.resolvedType)
1213 .setActivityInfo(aInfo)
1214 .setResultTo(resultTo != null ? resultTo.appToken : null)
1215 .setResultWho(resultWho)
1216 .setRequestCode(requestCode)
1217 .setCallingPid(-1)
1218 .setCallingUid(r.launchedFromUid)
1219 .setCallingPackage(r.launchedFromPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001220 .setCallingFeatureId(r.launchedFromFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001221 .setRealCallingPid(-1)
1222 .setRealCallingUid(r.launchedFromUid)
1223 .setActivityOptions(options)
1224 .execute();
1225 Binder.restoreCallingIdentity(origId);
1226
1227 r.finishing = wasFinishing;
1228 if (res != ActivityManager.START_SUCCESS) {
1229 return false;
1230 }
1231 return true;
1232 }
1233 }
1234
1235 @Override
Galia Peycheva6861e912019-08-21 10:20:23 +02001236 public boolean startDreamActivity(Intent intent) {
Galia Peycheva52e89222020-02-18 23:41:43 +01001237 final WindowProcessController process = mProcessMap.getProcess(Binder.getCallingPid());
1238 final long origId = Binder.clearCallingIdentity();
1239
1240 // The dream activity is only called for non-doze dreams.
1241 final ComponentName currentDream = LocalServices.getService(DreamManagerInternal.class)
1242 .getActiveDreamComponent(/* doze= */ false);
1243
1244 if (currentDream == null || currentDream.getPackageName() == null
1245 || !currentDream.getPackageName().equals(process.mInfo.packageName)) {
1246 Slog.e(TAG, "Calling package is not the current dream package. "
1247 + "Aborting startDreamActivity...");
1248 return false;
1249 }
1250
Galia Peycheva6861e912019-08-21 10:20:23 +02001251 final ActivityInfo a = new ActivityInfo();
1252 a.theme = com.android.internal.R.style.Theme_Dream;
1253 a.exported = true;
1254 a.name = DreamActivity.class.getName();
1255
Galia Peycheva6861e912019-08-21 10:20:23 +02001256
1257 a.packageName = process.mInfo.packageName;
1258 a.applicationInfo = process.mInfo;
1259 a.processName = process.mInfo.processName;
1260 a.uiOptions = process.mInfo.uiOptions;
1261 a.taskAffinity = "android:" + a.packageName + "/dream";
1262 a.enabled = true;
1263 a.launchMode = ActivityInfo.LAUNCH_SINGLE_INSTANCE;
1264
1265 a.persistableMode = ActivityInfo.PERSIST_NEVER;
1266 a.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1267 a.colorMode = ActivityInfo.COLOR_MODE_DEFAULT;
1268 a.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1269
Galia Peycheva6861e912019-08-21 10:20:23 +02001270 try {
1271 getActivityStartController().obtainStarter(intent, "dream")
1272 .setActivityInfo(a)
1273 .setIsDream(true)
1274 .execute();
1275 return true;
1276 } finally {
1277 Binder.restoreCallingIdentity(origId);
1278 }
1279 }
1280
1281 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001282 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001283 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1284 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1285 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001286 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001287 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001288 enforceNotIsolatedCaller("startActivityAndWait");
1289 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1290 userId, "startActivityAndWait");
1291 // TODO: Switch to user app stacks here.
1292 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1293 .setCaller(caller)
1294 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001295 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001296 .setResolvedType(resolvedType)
1297 .setResultTo(resultTo)
1298 .setResultWho(resultWho)
1299 .setRequestCode(requestCode)
1300 .setStartFlags(startFlags)
1301 .setActivityOptions(bOptions)
1302 .setUserId(userId)
1303 .setProfilerInfo(profilerInfo)
1304 .setWaitResult(res)
1305 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001306 return res;
1307 }
1308
1309 @Override
1310 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001311 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1312 String resultWho, int requestCode, int startFlags, Configuration config,
1313 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001314 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001315 enforceNotIsolatedCaller("startActivityWithConfig");
1316 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1317 "startActivityWithConfig");
1318 // TODO: Switch to user app stacks here.
1319 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1320 .setCaller(caller)
1321 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001322 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001323 .setResolvedType(resolvedType)
1324 .setResultTo(resultTo)
1325 .setResultWho(resultWho)
1326 .setRequestCode(requestCode)
1327 .setStartFlags(startFlags)
1328 .setGlobalConfiguration(config)
1329 .setActivityOptions(bOptions)
1330 .setUserId(userId)
1331 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001332 }
1333
Robert Carr8a2f9132019-11-11 15:03:15 -08001334 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001335 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1336 int callingUid = Binder.getCallingUid();
1337 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1338 throw new SecurityException("Only the system process can request a permission token, "
1339 + "received request from uid: " + callingUid);
1340 }
1341 IBinder permissionToken = new Binder();
1342 synchronized (mGlobalLock) {
1343 mStartActivitySources.put(permissionToken, delegatorToken);
1344 }
1345
1346 Message expireMsg = PooledLambda.obtainMessage(
1347 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1348 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1349
1350 Message forgetMsg = PooledLambda.obtainMessage(
1351 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1352 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1353
1354 return permissionToken;
1355 }
1356
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001357 @Override
1358 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1359 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001360 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1361 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001362 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001363 // permission grants) as any app that may launch one of your own activities. So we only
1364 // allow this in two cases:
1365 // 1) The caller is an activity that is part of the core framework, and then only when it
1366 // is running as the system.
1367 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1368 // can only be requested by a system activity, which may then delegate this call to
1369 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001370 final ActivityRecord sourceRecord;
1371 final int targetUid;
1372 final String targetPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001373 final String targetFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001374 final boolean isResolver;
1375 synchronized (mGlobalLock) {
1376 if (resultTo == null) {
1377 throw new SecurityException("Must be called from an activity");
1378 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001379 final IBinder sourceToken;
1380 if (permissionToken != null) {
1381 // To even attempt to use a permissionToken, an app must also have this signature
1382 // permission.
1383 mAmInternal.enforceCallingPermission(
1384 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1385 "startActivityAsCaller");
1386 // If called with a permissionToken, we want the sourceRecord from the delegator
1387 // activity that requested this token.
1388 sourceToken = mStartActivitySources.remove(permissionToken);
1389 if (sourceToken == null) {
1390 // Invalid permissionToken, check if it recently expired.
1391 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1392 throw new SecurityException("Called with expired permission token: "
1393 + permissionToken);
1394 } else {
1395 throw new SecurityException("Called with invalid permission token: "
1396 + permissionToken);
1397 }
1398 }
1399 } else {
1400 // This method was called directly by the source.
1401 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001402 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001403
Louis Chang149d5c82019-12-30 09:47:39 +08001404 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001405 if (sourceRecord == null) {
1406 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001407 }
1408 if (sourceRecord.app == null) {
1409 throw new SecurityException("Called without a process attached to activity");
1410 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001411
1412 // Whether called directly or from a delegate, the source activity must be from the
1413 // android package.
1414 if (!sourceRecord.info.packageName.equals("android")) {
1415 throw new SecurityException("Must be called from an activity that is "
1416 + "declared in the android package");
1417 }
1418
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001419 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001420 // This is still okay, as long as this activity is running under the
1421 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001422 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001423 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001424 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001425 + " must be system uid or original calling uid "
1426 + sourceRecord.launchedFromUid);
1427 }
1428 }
1429 if (ignoreTargetSecurity) {
1430 if (intent.getComponent() == null) {
1431 throw new SecurityException(
1432 "Component must be specified with ignoreTargetSecurity");
1433 }
1434 if (intent.getSelector() != null) {
1435 throw new SecurityException(
1436 "Selector not allowed with ignoreTargetSecurity");
1437 }
1438 }
1439 targetUid = sourceRecord.launchedFromUid;
1440 targetPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001441 targetFeatureId = sourceRecord.launchedFromFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001442 isResolver = sourceRecord.isResolverOrChildActivity();
1443 }
1444
1445 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001446 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001447 }
1448
1449 // TODO: Switch to user app stacks here.
1450 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001451 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452 .setCallingUid(targetUid)
1453 .setCallingPackage(targetPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001454 .setCallingFeatureId(targetFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455 .setResolvedType(resolvedType)
1456 .setResultTo(resultTo)
1457 .setResultWho(resultWho)
1458 .setRequestCode(requestCode)
1459 .setStartFlags(startFlags)
1460 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001461 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001462 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1463 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001464 // The target may well be in the background, which would normally prevent it
1465 // from starting an activity. Here we definitely want the start to succeed.
1466 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001467 .execute();
1468 } catch (SecurityException e) {
1469 // XXX need to figure out how to propagate to original app.
1470 // A SecurityException here is generally actually a fault of the original
1471 // calling activity (such as a fairly granting permissions), so propagate it
1472 // back to them.
1473 /*
1474 StringBuilder msg = new StringBuilder();
1475 msg.append("While launching");
1476 msg.append(intent.toString());
1477 msg.append(": ");
1478 msg.append(e.getMessage());
1479 */
1480 throw e;
1481 }
1482 }
1483
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001484 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1485 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001486 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001487 }
1488
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001489 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001490 public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1491 int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001492 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1493 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001494 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001495 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001496 if (session == null || interactor == null) {
1497 throw new NullPointerException("null session or interactor");
1498 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001499 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001500 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001501 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001502 .setCallingUid(callingUid)
1503 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001504 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001505 .setResolvedType(resolvedType)
1506 .setVoiceSession(session)
1507 .setVoiceInteractor(interactor)
1508 .setStartFlags(startFlags)
1509 .setProfilerInfo(profilerInfo)
1510 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001511 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001512 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001513 .execute();
1514 }
1515
1516 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001517 public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1518 int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1519 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001520 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001521 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1522 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001523
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001524 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001525 .setCallingUid(callingUid)
1526 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001527 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001528 .setResolvedType(resolvedType)
1529 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001530 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001531 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001532 .execute();
1533 }
1534
Riddle Hsu609a8e22019-06-27 16:46:29 -06001535 /**
1536 * Start the recents activity to perform the recents animation.
1537 *
1538 * @param intent The intent to start the recents activity.
1539 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1540 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001541 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001542 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1543 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001544 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001545 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001546 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001547 final long origId = Binder.clearCallingIdentity();
1548 try {
1549 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001550 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
Philip P. Moltmannee295092020-02-10 08:46:26 -08001551 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001552 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001553 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001554
1555 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001556 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001557 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001558 recentsFeatureId, recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001559 if (recentsAnimationRunner == null) {
1560 anim.preloadRecentsActivity();
1561 } else {
1562 anim.startRecentsActivity(recentsAnimationRunner);
1563 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001564 }
1565 } finally {
1566 Binder.restoreCallingIdentity(origId);
1567 }
1568 }
1569
1570 @Override
1571 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001572 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001573 "startActivityFromRecents()");
1574
1575 final int callingPid = Binder.getCallingPid();
1576 final int callingUid = Binder.getCallingUid();
1577 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1578 final long origId = Binder.clearCallingIdentity();
1579 try {
1580 synchronized (mGlobalLock) {
1581 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1582 safeOptions);
1583 }
1584 } finally {
1585 Binder.restoreCallingIdentity(origId);
1586 }
1587 }
1588
1589 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001590 * Public API to check if the client is allowed to start an activity on specified display.
1591 *
1592 * If the target display is private or virtual, some restrictions will apply.
1593 *
1594 * @param displayId Target display id.
1595 * @param intent Intent used to launch the activity.
1596 * @param resolvedType The MIME type of the intent.
1597 * @param userId The id of the user for whom the call is made.
1598 * @return {@code true} if a call to start an activity on the target display should succeed and
1599 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1600 */
1601 @Override
1602 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1603 String resolvedType, int userId) {
1604 final int callingUid = Binder.getCallingUid();
1605 final int callingPid = Binder.getCallingPid();
1606 final long origId = Binder.clearCallingIdentity();
1607
1608 try {
1609 // Collect information about the target of the Intent.
1610 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1611 0 /* startFlags */, null /* profilerInfo */, userId,
1612 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1613 UserHandle.USER_NULL));
1614 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1615
1616 synchronized (mGlobalLock) {
1617 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1618 aInfo);
1619 }
1620 } finally {
1621 Binder.restoreCallingIdentity(origId);
1622 }
1623 }
1624
1625 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001626 * This is the internal entry point for handling Activity.finish().
1627 *
1628 * @param token The Binder token referencing the Activity we want to finish.
1629 * @param resultCode Result code, if any, from this Activity.
1630 * @param resultData Result data (Intent), if any, from this Activity.
1631 * @param finishTask Whether to finish the task associated with this Activity.
1632 *
1633 * @return Returns true if the activity successfully finished, or false if it is still running.
1634 */
1635 @Override
1636 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1637 int finishTask) {
1638 // Refuse possible leaked file descriptors
1639 if (resultData != null && resultData.hasFileDescriptors()) {
1640 throw new IllegalArgumentException("File descriptors passed in Intent");
1641 }
1642
1643 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001644 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001645 if (r == null) {
1646 return true;
1647 }
1648 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001649 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001650 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001651 if (rootR == null) {
1652 Slog.w(TAG, "Finishing task with all activities already finished");
1653 }
1654 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1655 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001656 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001657 return false;
1658 }
1659
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001660 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1661 // We should consolidate.
1662 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001663 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001664 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001665 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001666 if (next != null) {
1667 // ask watcher if this is allowed
1668 boolean resumeOK = true;
1669 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001670 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001671 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001672 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001673 Watchdog.getInstance().setActivityController(null);
1674 }
1675
1676 if (!resumeOK) {
1677 Slog.i(TAG, "Not finishing activity because controller resumed");
1678 return false;
1679 }
1680 }
1681 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001682
1683 // note down that the process has finished an activity and is in background activity
1684 // starts grace period
1685 if (r.app != null) {
1686 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1687 }
1688
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001689 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001690 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001691 try {
1692 boolean res;
1693 final boolean finishWithRootActivity =
1694 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1695 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1696 || (finishWithRootActivity && r == rootR)) {
1697 // If requested, remove the task that is associated to this activity only if it
1698 // was the root activity in the task. The result code and data is ignored
1699 // because we don't support returning them across task boundaries. Also, to
1700 // keep backwards compatibility we remove the task from recents when finishing
1701 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001702 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001703 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001704 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001705 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001706 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001707 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001708 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001709 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001710 if (!res) {
1711 Slog.i(TAG, "Failed to finish by app-request");
1712 }
1713 }
1714 return res;
1715 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001716 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001717 Binder.restoreCallingIdentity(origId);
1718 }
1719 }
1720 }
1721
1722 @Override
1723 public boolean finishActivityAffinity(IBinder token) {
1724 synchronized (mGlobalLock) {
1725 final long origId = Binder.clearCallingIdentity();
1726 try {
1727 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1728 if (r == null) {
1729 return false;
1730 }
1731
1732 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1733 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001734 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001735 return false;
1736 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001737
1738 final PooledFunction p = PooledLambda.obtainFunction(
1739 ActivityRecord::finishIfSameAffinity, r,
1740 PooledLambda.__(ActivityRecord.class));
1741 r.getTask().forAllActivities(
1742 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1743 p.recycle();
1744
Andrii Kuliande93eff2019-07-12 12:21:27 -07001745 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001746 } finally {
1747 Binder.restoreCallingIdentity(origId);
1748 }
1749 }
1750 }
1751
1752 @Override
1753 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1754 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001755 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001756 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001757 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001758 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1759 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001760 return;
1761 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001762 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1763 false /* processPausingActivities */, config);
1764 if (stopProfiling && r.hasProcess()) {
1765 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001766 }
1767 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001768 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001769 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001770 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001771 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001772 }
1773
1774 @Override
1775 public final void activityResumed(IBinder token) {
1776 final long origId = Binder.clearCallingIdentity();
1777 synchronized (mGlobalLock) {
1778 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001779 }
1780 Binder.restoreCallingIdentity(origId);
1781 }
1782
1783 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001784 public final void activityTopResumedStateLost() {
1785 final long origId = Binder.clearCallingIdentity();
1786 synchronized (mGlobalLock) {
1787 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1788 }
1789 Binder.restoreCallingIdentity(origId);
1790 }
1791
1792 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001793 public final void activityPaused(IBinder token) {
1794 final long origId = Binder.clearCallingIdentity();
1795 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001796 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001797 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1798 if (r != null) {
1799 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001801 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001802 }
1803 Binder.restoreCallingIdentity(origId);
1804 }
1805
1806 @Override
1807 public final void activityStopped(IBinder token, Bundle icicle,
1808 PersistableBundle persistentState, CharSequence description) {
1809 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1810
1811 // Refuse possible leaked file descriptors
1812 if (icicle != null && icicle.hasFileDescriptors()) {
1813 throw new IllegalArgumentException("File descriptors passed in Bundle");
1814 }
1815
1816 final long origId = Binder.clearCallingIdentity();
1817
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001818 String restartingName = null;
1819 int restartingUid = 0;
1820 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001821 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001822 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001823 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001824 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001825 if (r.attachedToProcess()
1826 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1827 // The activity was requested to restart from
1828 // {@link #restartActivityProcessIfVisible}.
1829 restartingName = r.app.mName;
1830 restartingUid = r.app.mUid;
1831 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001832 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001833 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001834 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001835 }
1836
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001837 if (restartingName != null) {
1838 // In order to let the foreground activity can be restarted with its saved state from
1839 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1840 // until the activity reports stopped with the state. And the activity record will be
1841 // kept because the record state is restarting, then the activity will be restarted
1842 // immediately if it is still the top one.
1843 mStackSupervisor.removeRestartTimeouts(r);
1844 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1845 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001846 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001847
1848 Binder.restoreCallingIdentity(origId);
1849 }
1850
1851 @Override
1852 public final void activityDestroyed(IBinder token) {
1853 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1854 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001855 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001856 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001857 try {
1858 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1859 if (activity != null) {
1860 activity.destroyed("activityDestroyed");
1861 }
1862 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001863 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001864 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001865 }
1866 }
1867 }
1868
1869 @Override
1870 public final void activityRelaunched(IBinder token) {
1871 final long origId = Binder.clearCallingIdentity();
1872 synchronized (mGlobalLock) {
1873 mStackSupervisor.activityRelaunchedLocked(token);
1874 }
1875 Binder.restoreCallingIdentity(origId);
1876 }
1877
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001878 @Override
1879 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1880 synchronized (mGlobalLock) {
1881 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1882 if (r == null) {
1883 return;
1884 }
1885 final long origId = Binder.clearCallingIdentity();
1886 try {
1887 r.setRequestedOrientation(requestedOrientation);
1888 } finally {
1889 Binder.restoreCallingIdentity(origId);
1890 }
1891 }
1892 }
1893
1894 @Override
1895 public int getRequestedOrientation(IBinder token) {
1896 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001897 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1898 return (r != null)
1899 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001900 }
1901 }
1902
1903 @Override
1904 public void setImmersive(IBinder token, boolean immersive) {
1905 synchronized (mGlobalLock) {
1906 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1907 if (r == null) {
1908 throw new IllegalArgumentException();
1909 }
1910 r.immersive = immersive;
1911
1912 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001913 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001914 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001915 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001916 }
1917 }
1918 }
1919
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001920 void applyUpdateLockStateLocked(ActivityRecord r) {
1921 // Modifications to the UpdateLock state are done on our handler, outside
1922 // the activity manager's locks. The new state is determined based on the
1923 // state *now* of the relevant activity record. The object is passed to
1924 // the handler solely for logging detail, not to be consulted/modified.
1925 final boolean nextState = r != null && r.immersive;
1926 mH.post(() -> {
1927 if (mUpdateLock.isHeld() != nextState) {
1928 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1929 "Applying new update lock state '" + nextState + "' for " + r);
1930 if (nextState) {
1931 mUpdateLock.acquire();
1932 } else {
1933 mUpdateLock.release();
1934 }
1935 }
1936 });
1937 }
1938
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001939 @Override
1940 public boolean isImmersive(IBinder token) {
1941 synchronized (mGlobalLock) {
1942 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1943 if (r == null) {
1944 throw new IllegalArgumentException();
1945 }
1946 return r.immersive;
1947 }
1948 }
1949
1950 @Override
1951 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001952 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001953 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001954 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001955 return (r != null) ? r.immersive : false;
1956 }
1957 }
1958
1959 @Override
1960 public void overridePendingTransition(IBinder token, String packageName,
1961 int enterAnim, int exitAnim) {
1962 synchronized (mGlobalLock) {
1963 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1964 if (self == null) {
1965 return;
1966 }
1967
1968 final long origId = Binder.clearCallingIdentity();
1969
1970 if (self.isState(
1971 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001972 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001973 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001974 }
1975
1976 Binder.restoreCallingIdentity(origId);
1977 }
1978 }
1979
1980 @Override
1981 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001982 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001983 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001984 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001985 if (r == null) {
1986 return ActivityManager.COMPAT_MODE_UNKNOWN;
1987 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001988 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001989 }
1990 }
1991
1992 @Override
1993 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001994 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001995 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001996 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001997 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001998 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001999 if (r == null) {
2000 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
2001 return;
2002 }
2003 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07002004 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002005 }
2006 }
2007
2008 @Override
2009 public int getLaunchedFromUid(IBinder activityToken) {
2010 ActivityRecord srec;
2011 synchronized (mGlobalLock) {
2012 srec = ActivityRecord.forTokenLocked(activityToken);
2013 }
2014 if (srec == null) {
2015 return -1;
2016 }
2017 return srec.launchedFromUid;
2018 }
2019
2020 @Override
2021 public String getLaunchedFromPackage(IBinder activityToken) {
2022 ActivityRecord srec;
2023 synchronized (mGlobalLock) {
2024 srec = ActivityRecord.forTokenLocked(activityToken);
2025 }
2026 if (srec == null) {
2027 return null;
2028 }
2029 return srec.launchedFromPackage;
2030 }
2031
2032 @Override
2033 public boolean convertFromTranslucent(IBinder token) {
2034 final long origId = Binder.clearCallingIdentity();
2035 try {
2036 synchronized (mGlobalLock) {
2037 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2038 if (r == null) {
2039 return false;
2040 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002041 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002042 }
2043 } finally {
2044 Binder.restoreCallingIdentity(origId);
2045 }
2046 }
2047
2048 @Override
2049 public boolean convertToTranslucent(IBinder token, Bundle options) {
2050 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2051 final long origId = Binder.clearCallingIdentity();
2052 try {
2053 synchronized (mGlobalLock) {
2054 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2055 if (r == null) {
2056 return false;
2057 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002058 final ActivityRecord under = r.getTask().getActivityBelow(r);
2059 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2061 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002062 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002063 }
2064 } finally {
2065 Binder.restoreCallingIdentity(origId);
2066 }
2067 }
2068
2069 @Override
2070 public void notifyActivityDrawn(IBinder token) {
2071 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2072 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002073 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002074 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002075 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002076 }
2077 }
2078 }
2079
2080 @Override
2081 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2082 synchronized (mGlobalLock) {
2083 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2084 if (r == null) {
2085 return;
2086 }
2087 r.reportFullyDrawnLocked(restoredFromBundle);
2088 }
2089 }
2090
2091 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002092 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002093 synchronized (mGlobalLock) {
2094 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002095 if (stack != null) {
2096 final int displayId = stack.getDisplayId();
2097 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002098 }
2099 return DEFAULT_DISPLAY;
2100 }
2101 }
2102
2103 @Override
2104 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002105 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002106 long ident = Binder.clearCallingIdentity();
2107 try {
2108 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002109 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002110 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002111 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002112 }
2113 return null;
2114 }
2115 } finally {
2116 Binder.restoreCallingIdentity(ident);
2117 }
2118 }
2119
2120 @Override
2121 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002122 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002123 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2124 final long callingId = Binder.clearCallingIdentity();
2125 try {
2126 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002127 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002128 if (stack == null) {
2129 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2130 return;
2131 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002132 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002133 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002134 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002135 }
2136 }
2137 } finally {
2138 Binder.restoreCallingIdentity(callingId);
2139 }
2140 }
2141
2142 @Override
2143 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002144 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002145 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2146 final long callingId = Binder.clearCallingIdentity();
2147 try {
2148 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002149 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002150 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002151 if (task == null) {
2152 return;
2153 }
2154 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002155 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002156 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002157 }
2158 }
2159 } finally {
2160 Binder.restoreCallingIdentity(callingId);
2161 }
2162 }
2163
2164 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002165 public void restartActivityProcessIfVisible(IBinder activityToken) {
2166 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2167 final long callingId = Binder.clearCallingIdentity();
2168 try {
2169 synchronized (mGlobalLock) {
2170 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2171 if (r == null) {
2172 return;
2173 }
2174 r.restartProcessIfVisible();
2175 }
2176 } finally {
2177 Binder.restoreCallingIdentity(callingId);
2178 }
2179 }
2180
2181 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002182 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002183 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002184 synchronized (mGlobalLock) {
2185 final long ident = Binder.clearCallingIdentity();
2186 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002187 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002188 "remove-task");
2189 } finally {
2190 Binder.restoreCallingIdentity(ident);
2191 }
2192 }
2193 }
2194
2195 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002196 public void removeAllVisibleRecentTasks() {
2197 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2198 synchronized (mGlobalLock) {
2199 final long ident = Binder.clearCallingIdentity();
2200 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002201 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002202 } finally {
2203 Binder.restoreCallingIdentity(ident);
2204 }
2205 }
2206 }
2207
2208 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002209 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2210 synchronized (mGlobalLock) {
2211 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2212 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002213 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002214 }
2215 }
2216 return false;
2217 }
2218
2219 @Override
2220 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2221 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002222
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002223 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002224 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2225 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002226 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002227 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002228 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002229 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002230 }
2231 }
2232
2233 /**
2234 * Attempts to move a task backwards in z-order (the order of activities within the task is
2235 * unchanged).
2236 *
2237 * There are several possible results of this call:
2238 * - if the task is locked, then we will show the lock toast
2239 * - if there is a task behind the provided task, then that task is made visible and resumed as
2240 * this task is moved to the back
2241 * - otherwise, if there are no other tasks in the stack:
2242 * - if this task is in the pinned stack, then we remove the stack completely, which will
2243 * have the effect of moving the task to the top or bottom of the fullscreen stack
2244 * (depending on whether it is visible)
2245 * - otherwise, we simply return home and hide this task
2246 *
2247 * @param token A reference to the activity we wish to move
2248 * @param nonRoot If false then this only works if the activity is the root
2249 * of a task; if true it will work for any activity in a task.
2250 * @return Returns true if the move completed, false if not.
2251 */
2252 @Override
2253 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002254 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002255 synchronized (mGlobalLock) {
2256 final long origId = Binder.clearCallingIdentity();
2257 try {
2258 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002259 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002260 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002261 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002262 }
2263 } finally {
2264 Binder.restoreCallingIdentity(origId);
2265 }
2266 }
2267 return false;
2268 }
2269
2270 @Override
2271 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002272 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002273 long ident = Binder.clearCallingIdentity();
2274 Rect rect = new Rect();
2275 try {
2276 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002277 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002278 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2279 if (task == null) {
2280 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2281 return rect;
2282 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002283 if (task.getParent() != null) {
2284 rect.set(task.getBounds());
2285 } else if (task.mLastNonFullscreenBounds != null) {
2286 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002287 }
2288 }
2289 } finally {
2290 Binder.restoreCallingIdentity(ident);
2291 }
2292 return rect;
2293 }
2294
2295 @Override
2296 public ActivityManager.TaskDescription getTaskDescription(int id) {
2297 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002298 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002299 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002300 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002301 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2302 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002303 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002304 }
2305 }
2306 return null;
2307 }
2308
2309 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002310 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002311 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08002312 return setTaskWindowingModeSplitScreenPrimary(taskId, toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002313 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002314 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002315 synchronized (mGlobalLock) {
2316 final long ident = Binder.clearCallingIdentity();
2317 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002318 if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2319 return setTaskWindowingModeSplitScreen(taskId, windowingMode, toTop);
2320 }
Louis Chang149d5c82019-12-30 09:47:39 +08002321 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002322 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002323 if (task == null) {
2324 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002325 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002326 }
2327
2328 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2329 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2330
2331 if (!task.isActivityTypeStandardOrUndefined()) {
2332 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2333 + " non-standard task " + taskId + " to windowing mode="
2334 + windowingMode);
2335 }
2336
2337 final ActivityStack stack = task.getStack();
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002338 // Convert some windowing-mode changes into root-task reparents for split-screen.
2339 if (stack.getTile() != null) {
2340 stack.getDisplay().onSplitScreenModeDismissed();
2341 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002342 if (toTop) {
2343 stack.moveToFront("setTaskWindowingMode", task);
2344 }
2345 stack.setWindowingMode(windowingMode);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002346 stack.getDisplay().ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2347 true /* notifyClients */);
Winson Chung7ccc6812020-01-23 16:15:10 -08002348 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002349 } finally {
2350 Binder.restoreCallingIdentity(ident);
2351 }
2352 }
2353 }
2354
2355 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002356 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002357 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002358 ActivityRecord r = getCallingRecordLocked(token);
2359 return r != null ? r.info.packageName : null;
2360 }
2361 }
2362
2363 @Override
2364 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002365 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002366 ActivityRecord r = getCallingRecordLocked(token);
2367 return r != null ? r.intent.getComponent() : null;
2368 }
2369 }
2370
2371 private ActivityRecord getCallingRecordLocked(IBinder token) {
2372 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2373 if (r == null) {
2374 return null;
2375 }
2376 return r.resultTo;
2377 }
2378
2379 @Override
2380 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002381 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002382
2383 synchronized (mGlobalLock) {
2384 final long origId = Binder.clearCallingIdentity();
2385 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002386 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002387 } finally {
2388 Binder.restoreCallingIdentity(origId);
2389 }
2390 }
2391 }
2392
Mark Renouf446251d2019-04-26 10:22:41 -04002393 @Override
2394 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2395 synchronized (mGlobalLock) {
2396 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2397 if (r == null) {
2398 return;
2399 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002400 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002401 if (stack != null && stack.isSingleTaskInstance()) {
2402 // Single-task stacks are used for activities which are presented in floating
2403 // windows above full screen activities. Instead of directly finishing the
2404 // task, a task change listener is used to notify SystemUI so the action can be
2405 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002406 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002407 mTaskChangeNotificationController
2408 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2409 } else {
2410 try {
2411 callback.requestFinish();
2412 } catch (RemoteException e) {
2413 Slog.e(TAG, "Failed to invoke request finish callback", e);
2414 }
2415 }
2416 }
2417 }
2418
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002419 /**
2420 * TODO: Add mController hook
2421 */
2422 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002423 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2424 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002425 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002426
2427 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2428 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002429 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2430 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002431 }
2432 }
2433
Ricky Waiaca8a772019-04-04 16:01:06 +01002434 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2435 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002436 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002437 final int callingPid = Binder.getCallingPid();
2438 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002439 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002440 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002441 SafeActivityOptions.abort(options);
2442 return;
2443 }
2444 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002445 WindowProcessController callerApp = null;
2446 if (appThread != null) {
2447 callerApp = getProcessController(appThread);
2448 }
2449 final ActivityStarter starter = getActivityStartController().obtainStarter(
2450 null /* intent */, "moveTaskToFront");
2451 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
Galia Peycheva6861e912019-08-21 10:20:23 +02002452 -1, callerApp, null, false, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002453 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002454 return;
2455 }
2456 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002457 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002458 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002459 if (task == null) {
2460 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002461 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002462 return;
2463 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002464 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002465 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002466 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002467 return;
2468 }
2469 ActivityOptions realOptions = options != null
2470 ? options.getOptions(mStackSupervisor)
2471 : null;
2472 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2473 false /* forceNonResizable */);
2474
Wale Ogunwale21e06482019-11-18 05:14:15 -08002475 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002476 if (topActivity != null) {
2477
2478 // We are reshowing a task, use a starting window to hide the initial draw delay
2479 // so the transition can start earlier.
2480 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2481 true /* taskSwitch */, fromRecents);
2482 }
2483 } finally {
2484 Binder.restoreCallingIdentity(origId);
2485 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002486 }
2487
Ricky Waiaca8a772019-04-04 16:01:06 +01002488 /**
2489 * Return true if callingUid is system, or packageName belongs to that callingUid.
2490 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002491 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002492 try {
2493 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2494 if (packageName == null) {
2495 return false;
2496 }
2497 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2498 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2499 UserHandle.getUserId(callingUid));
2500 return UserHandle.isSameApp(callingUid, uid);
2501 }
2502 } catch (RemoteException e) {
2503 // Should not happen
2504 }
2505 return true;
2506 }
2507
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002508 /**
2509 * Checks that the provided package name matches the current calling UID, throws a security
2510 * exception if it doesn't.
2511 */
2512 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2513 final int callingUid = Binder.getCallingUid();
2514 if (isSameApp(callingUid, packageName)) {
2515 return;
2516 }
2517 final String msg = "Permission Denial: package=" + packageName
2518 + " does not belong to uid=" + callingUid;
2519 Slog.w(TAG, msg);
2520 throw new SecurityException(msg);
2521 }
2522
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002523 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2524 int callingPid, int callingUid, String name) {
2525 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2526 return true;
2527 }
2528
2529 if (getRecentTasks().isCallerRecents(sourceUid)) {
2530 return true;
2531 }
2532
2533 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2534 if (perm == PackageManager.PERMISSION_GRANTED) {
2535 return true;
2536 }
2537 if (checkAllowAppSwitchUid(sourceUid)) {
2538 return true;
2539 }
2540
2541 // If the actual IPC caller is different from the logical source, then
2542 // also see if they are allowed to control app switches.
2543 if (callingUid != -1 && callingUid != sourceUid) {
2544 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2545 if (perm == PackageManager.PERMISSION_GRANTED) {
2546 return true;
2547 }
2548 if (checkAllowAppSwitchUid(callingUid)) {
2549 return true;
2550 }
2551 }
2552
2553 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2554 return false;
2555 }
2556
2557 private boolean checkAllowAppSwitchUid(int uid) {
2558 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2559 if (types != null) {
2560 for (int i = types.size() - 1; i >= 0; i--) {
2561 if (types.valueAt(i).intValue() == uid) {
2562 return true;
2563 }
2564 }
2565 }
2566 return false;
2567 }
2568
2569 @Override
2570 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2571 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2572 "setActivityController()");
2573 synchronized (mGlobalLock) {
2574 mController = controller;
2575 mControllerIsAMonkey = imAMonkey;
2576 Watchdog.getInstance().setActivityController(controller);
2577 }
2578 }
2579
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002580 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002581 synchronized (mGlobalLock) {
2582 return mController != null && mControllerIsAMonkey;
2583 }
2584 }
2585
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002586 @Override
2587 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2588 synchronized (mGlobalLock) {
2589 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2590 }
2591 }
2592
2593 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002594 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2595 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2596 }
2597
2598 @Override
2599 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2600 @WindowConfiguration.ActivityType int ignoreActivityType,
2601 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2602 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002603 final int callingPid = Binder.getCallingPid();
2604 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002605 final int[] profileIds = getUserManager().getProfileIds(
2606 UserHandle.getUserId(callingUid), true);
2607 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2608 for (int i = 0; i < profileIds.length; i++) {
2609 callingProfileIds.add(profileIds[i]);
2610 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002611 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2612
2613 synchronized (mGlobalLock) {
2614 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2615
Nicholas Sauer0259e532019-08-30 08:24:55 -07002616 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002617 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002618 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002619 }
2620
2621 return list;
2622 }
2623
2624 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002625 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2626 synchronized (mGlobalLock) {
2627 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002628 try {
2629 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2630 if (r == null) return;
2631
2632 final PooledConsumer c = PooledLambda.obtainConsumer(
2633 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2634 r, resultWho, requestCode);
2635 // TODO: This should probably only loop over the task since you need to be in the
2636 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002637 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002638 c.recycle();
2639
2640 updateOomAdj();
2641 } finally {
2642 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002643 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002644 }
2645 }
2646
2647 @Override
2648 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002649 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002650 ActivityStack stack = ActivityRecord.getStackLocked(token);
2651 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002652 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002653 }
2654 return false;
2655 }
2656 }
2657
2658 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002659 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002660 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002661 synchronized (mGlobalLock) {
2662 final long ident = Binder.clearCallingIdentity();
2663 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002664 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002665 if (task == null) {
2666 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2667 return;
2668 }
2669
2670 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2671 + " to stackId=" + stackId + " toTop=" + toTop);
2672
Louis Chang149d5c82019-12-30 09:47:39 +08002673 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002674 if (stack == null) {
2675 throw new IllegalStateException(
2676 "moveTaskToStack: No stack for stackId=" + stackId);
2677 }
2678 if (!stack.isActivityTypeStandardOrUndefined()) {
2679 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2680 + taskId + " to stack " + stackId);
2681 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002682 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2683 "moveTaskToStack");
2684 } finally {
2685 Binder.restoreCallingIdentity(ident);
2686 }
2687 }
2688 }
2689
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002690 /**
2691 * Moves the specified task to the primary-split-screen stack.
2692 *
2693 * @param taskId Id of task to move.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002694 * @param toTop If the task and stack should be moved to the top.
Winson Chung7ccc6812020-01-23 16:15:10 -08002695 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002696 */
2697 @Override
Evan Rosky73a7fe92019-11-18 18:28:01 -08002698 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002699 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002700 "setTaskWindowingModeSplitScreenPrimary()");
2701 synchronized (mGlobalLock) {
2702 final long ident = Binder.clearCallingIdentity();
2703 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002704 return setTaskWindowingModeSplitScreen(taskId, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY,
2705 toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002706 } finally {
2707 Binder.restoreCallingIdentity(ident);
2708 }
2709 }
2710 }
2711
2712 /**
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002713 * Moves the specified task into a split-screen tile.
2714 */
2715 private boolean setTaskWindowingModeSplitScreen(int taskId, int windowingMode, boolean toTop) {
2716 if (!WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2717 throw new IllegalArgumentException("Calling setTaskWindowingModeSplitScreen with non"
2718 + "split-screen mode: " + windowingMode);
2719 }
2720 if (isInLockTaskMode()) {
2721 Slog.w(TAG, "setTaskWindowingModeSplitScreen: Is in lock task mode="
2722 + getLockTaskModeState());
2723 return false;
2724 }
2725
2726 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2727 MATCH_TASK_IN_STACKS_ONLY);
2728 if (task == null) {
2729 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2730 return false;
2731 }
2732 if (!task.isActivityTypeStandardOrUndefined()) {
2733 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2734 + " non-standard task " + taskId + " to split-screen windowing mode");
2735 }
Wale Ogunwale0d465192020-01-23 19:14:44 -08002736 if (!task.supportsSplitScreenWindowingMode()) {
2737 return false;
2738 }
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002739
2740 final int prevMode = task.getWindowingMode();
Wale Ogunwale0d465192020-01-23 19:14:44 -08002741 moveTaskToSplitScreenPrimaryTile(task, toTop);
2742 return prevMode != task.getWindowingMode();
2743 }
2744
2745 void moveTaskToSplitScreenPrimaryTile(Task task, boolean toTop) {
2746 ActivityStack stack = task.getStack();
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002747 TaskTile tile = null;
2748 for (int i = stack.getDisplay().getStackCount() - 1; i >= 0; --i) {
2749 tile = stack.getDisplay().getStackAt(i).asTile();
2750 if (tile != null && tile.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2751 break;
2752 }
2753 }
2754 if (tile == null) {
2755 throw new IllegalStateException("Can't enter split without associated tile");
2756 }
2757 WindowContainerTransaction wct = new WindowContainerTransaction();
2758 wct.reparent(stack.mRemoteToken, tile.mRemoteToken, toTop);
2759 mTaskOrganizerController.applyContainerTransaction(wct, null);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002760 }
2761
2762 /**
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002763 * Removes stacks in the input windowing modes from the system if they are of activity type
2764 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2765 */
2766 @Override
2767 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002768 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002769 "removeStacksInWindowingModes()");
2770
2771 synchronized (mGlobalLock) {
2772 final long ident = Binder.clearCallingIdentity();
2773 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002774 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002775 } finally {
2776 Binder.restoreCallingIdentity(ident);
2777 }
2778 }
2779 }
2780
2781 @Override
2782 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002783 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002784 "removeStacksWithActivityTypes()");
2785
2786 synchronized (mGlobalLock) {
2787 final long ident = Binder.clearCallingIdentity();
2788 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002789 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002790 } finally {
2791 Binder.restoreCallingIdentity(ident);
2792 }
2793 }
2794 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002795
2796 @Override
2797 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2798 int userId) {
2799 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002800 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2801 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002802 callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002803 synchronized (mGlobalLock) {
Winson Chung66b08f02020-03-03 14:32:35 -08002804 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, userId, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002805 }
2806 }
2807
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002808 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 @Override
2810 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002811 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002812 long ident = Binder.clearCallingIdentity();
2813 try {
2814 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002815 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002816 }
2817 } finally {
2818 Binder.restoreCallingIdentity(ident);
2819 }
2820 }
2821
2822 @Override
2823 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002824 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002825 long ident = Binder.clearCallingIdentity();
2826 try {
2827 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002828 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002829 }
2830 } finally {
2831 Binder.restoreCallingIdentity(ident);
2832 }
2833 }
2834
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002835 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002836 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002837 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2838 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2839 long ident = Binder.clearCallingIdentity();
2840 try {
2841 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002842 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002843 }
2844 } finally {
2845 Binder.restoreCallingIdentity(ident);
2846 }
2847 }
2848
2849 @Override
2850 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2851 int displayId) {
2852 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2853 long ident = Binder.clearCallingIdentity();
2854 try {
2855 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002856 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002857 }
2858 } finally {
2859 Binder.restoreCallingIdentity(ident);
2860 }
2861 }
2862
2863 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002865 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002866 final long callingUid = Binder.getCallingUid();
2867 final long origId = Binder.clearCallingIdentity();
2868 try {
2869 synchronized (mGlobalLock) {
2870 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002871 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002872 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2873 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2874 }
2875 } finally {
2876 Binder.restoreCallingIdentity(origId);
2877 }
2878 }
2879
2880 @Override
2881 public void startLockTaskModeByToken(IBinder token) {
2882 synchronized (mGlobalLock) {
2883 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2884 if (r == null) {
2885 return;
2886 }
Louis Changcdec0802019-11-11 11:45:07 +08002887 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002888 }
2889 }
2890
2891 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002892 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002893 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002894 // This makes inner call to look as if it was initiated by system.
2895 long ident = Binder.clearCallingIdentity();
2896 try {
2897 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002898 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002899 MATCH_TASK_IN_STACKS_ONLY);
2900 if (task == null) {
2901 return;
2902 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002903
2904 // When starting lock task mode the stack must be in front and focused
2905 task.getStack().moveToFront("startSystemLockTaskMode");
2906 startLockTaskModeLocked(task, true /* isSystemCaller */);
2907 }
2908 } finally {
2909 Binder.restoreCallingIdentity(ident);
2910 }
2911 }
2912
2913 @Override
2914 public void stopLockTaskModeByToken(IBinder token) {
2915 synchronized (mGlobalLock) {
2916 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2917 if (r == null) {
2918 return;
2919 }
Louis Changcdec0802019-11-11 11:45:07 +08002920 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002921 }
2922 }
2923
2924 /**
2925 * This API should be called by SystemUI only when user perform certain action to dismiss
2926 * lock task mode. We should only dismiss pinned lock task mode in this case.
2927 */
2928 @Override
2929 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002930 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002931 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2932 }
2933
Louis Changcdec0802019-11-11 11:45:07 +08002934 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002935 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2936 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2937 return;
2938 }
2939
Louis Chang149d5c82019-12-30 09:47:39 +08002940 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002941 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002942 throw new IllegalArgumentException("Invalid task, not in foreground");
2943 }
2944
2945 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2946 // system or a specific app.
2947 // * System-initiated requests will only start the pinned mode (screen pinning)
2948 // * App-initiated requests
2949 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2950 // - will start the pinned mode, otherwise
2951 final int callingUid = Binder.getCallingUid();
2952 long ident = Binder.clearCallingIdentity();
2953 try {
2954 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002955 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002956
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002957 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002958 } finally {
2959 Binder.restoreCallingIdentity(ident);
2960 }
2961 }
2962
Louis Changcdec0802019-11-11 11:45:07 +08002963 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002964 final int callingUid = Binder.getCallingUid();
2965 long ident = Binder.clearCallingIdentity();
2966 try {
2967 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002968 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002969 }
2970 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2971 // task and jumping straight into a call in the case of emergency call back.
2972 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2973 if (tm != null) {
2974 tm.showInCallScreen(false);
2975 }
2976 } finally {
2977 Binder.restoreCallingIdentity(ident);
2978 }
2979 }
2980
2981 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002982 public void updateLockTaskPackages(int userId, String[] packages) {
2983 final int callingUid = Binder.getCallingUid();
2984 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2985 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2986 "updateLockTaskPackages()");
2987 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002988 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002989 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2990 + Arrays.toString(packages));
2991 getLockTaskController().updateLockTaskPackages(userId, packages);
2992 }
2993 }
2994
2995 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002996 public boolean isInLockTaskMode() {
2997 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2998 }
2999
3000 @Override
3001 public int getLockTaskModeState() {
3002 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003003 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003004 }
3005 }
3006
3007 @Override
3008 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3009 synchronized (mGlobalLock) {
3010 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3011 if (r != null) {
3012 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003013 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003014 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003015 }
3016 }
3017 }
3018
3019 @Override
3020 public Bundle getActivityOptions(IBinder token) {
3021 final long origId = Binder.clearCallingIdentity();
3022 try {
3023 synchronized (mGlobalLock) {
3024 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3025 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003026 final ActivityOptions activityOptions = r.takeOptionsLocked(
3027 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003028 return activityOptions == null ? null : activityOptions.toBundle();
3029 }
3030 return null;
3031 }
3032 } finally {
3033 Binder.restoreCallingIdentity(origId);
3034 }
3035 }
3036
3037 @Override
3038 public List<IBinder> getAppTasks(String callingPackage) {
3039 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003040 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003041 long ident = Binder.clearCallingIdentity();
3042 try {
3043 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003044 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003045 }
3046 } finally {
3047 Binder.restoreCallingIdentity(ident);
3048 }
3049 }
3050
3051 @Override
3052 public void finishVoiceTask(IVoiceInteractionSession session) {
3053 synchronized (mGlobalLock) {
3054 final long origId = Binder.clearCallingIdentity();
3055 try {
3056 // TODO: VI Consider treating local voice interactions and voice tasks
3057 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003058 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003059 } finally {
3060 Binder.restoreCallingIdentity(origId);
3061 }
3062 }
3063
3064 }
3065
3066 @Override
3067 public boolean isTopOfTask(IBinder token) {
3068 synchronized (mGlobalLock) {
3069 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003070 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003071 }
3072 }
3073
3074 @Override
3075 public void notifyLaunchTaskBehindComplete(IBinder token) {
3076 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3077 }
3078
3079 @Override
3080 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003081 mH.post(() -> {
3082 synchronized (mGlobalLock) {
3083 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003084 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003085 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003086 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003087 } catch (RemoteException e) {
3088 }
3089 }
3090 }
3091
3092 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003093 }
3094
3095 /** Called from an app when assist data is ready. */
3096 @Override
3097 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3098 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003099 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003100 synchronized (pae) {
3101 pae.result = extras;
3102 pae.structure = structure;
3103 pae.content = content;
3104 if (referrer != null) {
3105 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3106 }
3107 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003108 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003109 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003110 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003111 structure.setHomeActivity(pae.isHome);
3112 }
3113 pae.haveResult = true;
3114 pae.notifyAll();
3115 if (pae.intent == null && pae.receiver == null) {
3116 // Caller is just waiting for the result.
3117 return;
3118 }
3119 }
3120 // We are now ready to launch the assist activity.
3121 IAssistDataReceiver sendReceiver = null;
3122 Bundle sendBundle = null;
3123 synchronized (mGlobalLock) {
3124 buildAssistBundleLocked(pae, extras);
3125 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003126 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003127 if (!exists) {
3128 // Timed out.
3129 return;
3130 }
3131
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003132 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003133 // Caller wants result sent back to them.
3134 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003135 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003136 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003137 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3138 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003139 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3140 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3141 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3142 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3143 }
3144 }
3145 if (sendReceiver != null) {
3146 try {
3147 sendReceiver.onHandleAssistData(sendBundle);
3148 } catch (RemoteException e) {
3149 }
3150 return;
3151 }
3152
3153 final long ident = Binder.clearCallingIdentity();
3154 try {
3155 if (TextUtils.equals(pae.intent.getAction(),
3156 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003157 // Start voice interaction through VoiceInteractionManagerService.
3158 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3159 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003160 } else {
3161 pae.intent.replaceExtras(pae.extras);
3162 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3163 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3164 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003165 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003166
3167 try {
3168 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3169 } catch (ActivityNotFoundException e) {
3170 Slog.w(TAG, "No activity to handle assist action.", e);
3171 }
3172 }
3173 } finally {
3174 Binder.restoreCallingIdentity(ident);
3175 }
3176 }
3177
3178 @Override
3179 public int addAppTask(IBinder activityToken, Intent intent,
3180 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3181 final int callingUid = Binder.getCallingUid();
3182 final long callingIdent = Binder.clearCallingIdentity();
3183
3184 try {
3185 synchronized (mGlobalLock) {
3186 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3187 if (r == null) {
3188 throw new IllegalArgumentException("Activity does not exist; token="
3189 + activityToken);
3190 }
3191 ComponentName comp = intent.getComponent();
3192 if (comp == null) {
3193 throw new IllegalArgumentException("Intent " + intent
3194 + " must specify explicit component");
3195 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003196 if (thumbnail.getWidth() != mThumbnailWidth
3197 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003198 throw new IllegalArgumentException("Bad thumbnail size: got "
3199 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003200 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003201 }
3202 if (intent.getSelector() != null) {
3203 intent.setSelector(null);
3204 }
3205 if (intent.getSourceBounds() != null) {
3206 intent.setSourceBounds(null);
3207 }
3208 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3209 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3210 // The caller has added this as an auto-remove task... that makes no
3211 // sense, so turn off auto-remove.
3212 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3213 }
3214 }
3215 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3216 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3217 if (ainfo.applicationInfo.uid != callingUid) {
3218 throw new SecurityException(
3219 "Can't add task for another application: target uid="
3220 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3221 }
3222
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003223 final ActivityStack stack = r.getRootTask();
Wale Ogunwale0d465192020-01-23 19:14:44 -08003224 final Task task = stack.getDisplay().createStack(stack.getWindowingMode(),
3225 stack.getActivityType(), !ON_TOP, ainfo, intent);
3226
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003227 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003228 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003229 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003230 return INVALID_TASK_ID;
3231 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003232 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003233
3234 // TODO: Send the thumbnail to WM to store it.
3235
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003236 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003237 }
3238 } finally {
3239 Binder.restoreCallingIdentity(callingIdent);
3240 }
3241 }
3242
3243 @Override
3244 public Point getAppTaskThumbnailSize() {
3245 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003246 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003247 }
3248 }
3249
3250 @Override
3251 public void setTaskResizeable(int taskId, int resizeableMode) {
3252 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003253 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003254 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3255 if (task == null) {
3256 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3257 return;
3258 }
3259 task.setResizeMode(resizeableMode);
3260 }
3261 }
3262
3263 @Override
3264 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003265 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003266 long ident = Binder.clearCallingIdentity();
3267 try {
3268 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003269 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003270 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003271 if (task == null) {
3272 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3273 return;
3274 }
3275 // Place the task in the right stack if it isn't there already based on
3276 // the requested bounds.
3277 // The stack transition logic is:
3278 // - a null bounds on a freeform task moves that task to fullscreen
3279 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3280 // that task to freeform
3281 // - otherwise the task is not moved
3282 ActivityStack stack = task.getStack();
3283 if (!task.getWindowConfiguration().canResizeTask()) {
3284 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3285 }
3286 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3287 stack = stack.getDisplay().getOrCreateStack(
3288 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3289 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3290 stack = stack.getDisplay().getOrCreateStack(
3291 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3292 }
3293
3294 // Reparent the task to the right stack if necessary
3295 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3296 if (stack != task.getStack()) {
3297 // Defer resume until the task is resized below
3298 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3299 DEFER_RESUME, "resizeTask");
3300 preserveWindow = false;
3301 }
3302
3303 // After reparenting (which only resizes the task to the stack bounds), resize the
3304 // task to the actual bounds provided
3305 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3306 }
3307 } finally {
3308 Binder.restoreCallingIdentity(ident);
3309 }
3310 }
3311
3312 @Override
3313 public boolean releaseActivityInstance(IBinder token) {
3314 synchronized (mGlobalLock) {
3315 final long origId = Binder.clearCallingIdentity();
3316 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003317 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3318 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003319 return false;
3320 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003321 r.destroyImmediately(true /* removeFromApp */, "app-req");
3322 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003323 } finally {
3324 Binder.restoreCallingIdentity(origId);
3325 }
3326 }
3327 }
3328
3329 @Override
3330 public void releaseSomeActivities(IApplicationThread appInt) {
3331 synchronized (mGlobalLock) {
3332 final long origId = Binder.clearCallingIdentity();
3333 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003334 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003335 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003336 } finally {
3337 Binder.restoreCallingIdentity(origId);
3338 }
3339 }
3340 }
3341
3342 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003343 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003344 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003345 != PackageManager.PERMISSION_GRANTED) {
3346 throw new SecurityException("Requires permission "
3347 + android.Manifest.permission.DEVICE_POWER);
3348 }
3349
3350 synchronized (mGlobalLock) {
3351 long ident = Binder.clearCallingIdentity();
3352 if (mKeyguardShown != keyguardShowing) {
3353 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003354 final Message msg = PooledLambda.obtainMessage(
3355 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3356 keyguardShowing);
3357 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003358 }
3359 try {
wilsonshih177261f2019-02-22 12:02:18 +08003360 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003361 } finally {
3362 Binder.restoreCallingIdentity(ident);
3363 }
3364 }
3365
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003366 mH.post(() -> {
3367 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3368 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3369 }
3370 });
3371 }
3372
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003373 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003374 mH.post(() -> {
3375 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3376 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3377 }
3378 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003379 }
3380
3381 @Override
3382 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003383 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3384 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003385
3386 final File passedIconFile = new File(filePath);
3387 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3388 passedIconFile.getName());
3389 if (!legitIconFile.getPath().equals(filePath)
3390 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3391 throw new IllegalArgumentException("Bad file path: " + filePath
3392 + " passed for userId " + userId);
3393 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003394 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003395 }
3396
3397 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003398 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003399 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003400 synchronized (mGlobalLock) {
3401 final long ident = Binder.clearCallingIdentity();
3402 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003403 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 if (stack == null) {
3405 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3406 return;
3407 }
3408 if (!stack.isActivityTypeStandardOrUndefined()) {
3409 throw new IllegalArgumentException(
3410 "Removing non-standard stack is not allowed.");
3411 }
3412 mStackSupervisor.removeStack(stack);
3413 } finally {
3414 Binder.restoreCallingIdentity(ident);
3415 }
3416 }
3417 }
3418
3419 @Override
3420 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003421 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422
3423 synchronized (mGlobalLock) {
3424 final long ident = Binder.clearCallingIdentity();
3425 try {
3426 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3427 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003428 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003429 } finally {
3430 Binder.restoreCallingIdentity(ident);
3431 }
3432 }
3433 }
3434
3435 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003436 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003437 synchronized (mGlobalLock) {
3438 long ident = Binder.clearCallingIdentity();
3439 try {
3440 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3441 if (r == null) {
3442 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003443 "toggleFreeformWindowingMode: No activity record matching token="
3444 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003445 }
3446
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003447 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003448 if (stack == null) {
3449 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3450 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003451 }
3452
Yunfan Chend967af82019-01-17 18:30:18 +09003453 if (!stack.inFreeformWindowingMode()
3454 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3455 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3456 + "toggle between fullscreen and freeform.");
3457 }
3458
3459 if (stack.inFreeformWindowingMode()) {
3460 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003461 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003462 throw new IllegalStateException("Size-compat windows are currently not"
3463 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003464 } else if (stack.getParent().inFreeformWindowingMode()) {
3465 // If the window is on a freeform display, set it to undefined. It will be
3466 // resolved to freeform and it can adjust windowing mode when the display mode
3467 // changes in runtime.
3468 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003469 } else {
3470 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3471 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003472 } finally {
3473 Binder.restoreCallingIdentity(ident);
3474 }
3475 }
3476 }
3477
3478 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3479 @Override
3480 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003481 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003482 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003483 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003484 }
3485
3486 /** Unregister a task stack listener so that it stops receiving callbacks. */
3487 @Override
3488 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003489 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003490 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003491 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003492 }
3493
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003494 @Override
3495 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3496 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3497 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3498 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3499 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3500 }
3501
3502 @Override
3503 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3504 IBinder activityToken, int flags) {
3505 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3506 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3507 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3508 }
3509
3510 @Override
3511 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3512 Bundle args) {
3513 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3514 true /* focused */, true /* newSessionId */, userHandle, args,
3515 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3516 }
3517
3518 @Override
3519 public Bundle getAssistContextExtras(int requestType) {
3520 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3521 null, null, true /* focused */, true /* newSessionId */,
3522 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3523 if (pae == null) {
3524 return null;
3525 }
3526 synchronized (pae) {
3527 while (!pae.haveResult) {
3528 try {
3529 pae.wait();
3530 } catch (InterruptedException e) {
3531 }
3532 }
3533 }
3534 synchronized (mGlobalLock) {
3535 buildAssistBundleLocked(pae, pae.result);
3536 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003537 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003538 }
3539 return pae.extras;
3540 }
3541
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003542 /**
3543 * Binder IPC calls go through the public entry point.
3544 * This can be called with or without the global lock held.
3545 */
3546 private static int checkCallingPermission(String permission) {
3547 return checkPermission(
3548 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3549 }
3550
3551 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003552 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003553 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3554 mAmInternal.enforceCallingPermission(permission, func);
3555 }
3556 }
3557
3558 @VisibleForTesting
3559 int checkGetTasksPermission(String permission, int pid, int uid) {
3560 return checkPermission(permission, pid, uid);
3561 }
3562
3563 static int checkPermission(String permission, int pid, int uid) {
3564 if (permission == null) {
3565 return PackageManager.PERMISSION_DENIED;
3566 }
3567 return checkComponentPermission(permission, pid, uid, -1, true);
3568 }
3569
Wale Ogunwale214f3482018-10-04 11:00:47 -07003570 public static int checkComponentPermission(String permission, int pid, int uid,
3571 int owningUid, boolean exported) {
3572 return ActivityManagerService.checkComponentPermission(
3573 permission, pid, uid, owningUid, exported);
3574 }
3575
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003576 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3577 if (getRecentTasks().isCallerRecents(callingUid)) {
3578 // Always allow the recents component to get tasks
3579 return true;
3580 }
3581
3582 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3583 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3584 if (!allowed) {
3585 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3586 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3587 // Temporary compatibility: some existing apps on the system image may
3588 // still be requesting the old permission and not switched to the new
3589 // one; if so, we'll still allow them full access. This means we need
3590 // to see if they are holding the old permission and are a system app.
3591 try {
3592 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3593 allowed = true;
3594 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3595 + " is using old GET_TASKS but privileged; allowing");
3596 }
3597 } catch (RemoteException e) {
3598 }
3599 }
3600 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3601 + " does not hold REAL_GET_TASKS; limiting output");
3602 }
3603 return allowed;
3604 }
3605
Nicholas Sauer0259e532019-08-30 08:24:55 -07003606 boolean isCrossUserAllowed(int pid, int uid) {
3607 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3608 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3609 }
3610
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003611 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3612 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3613 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3614 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003615 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003616 "enqueueAssistContext()");
3617
3618 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003619 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003620 if (activity == null) {
3621 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3622 return null;
3623 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003624 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003625 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3626 return null;
3627 }
3628 if (focused) {
3629 if (activityToken != null) {
3630 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3631 if (activity != caller) {
3632 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3633 + " is not current top " + activity);
3634 return null;
3635 }
3636 }
3637 } else {
3638 activity = ActivityRecord.forTokenLocked(activityToken);
3639 if (activity == null) {
3640 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3641 + " couldn't be found");
3642 return null;
3643 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003644 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003645 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3646 return null;
3647 }
3648 }
3649
3650 PendingAssistExtras pae;
3651 Bundle extras = new Bundle();
3652 if (args != null) {
3653 extras.putAll(args);
3654 }
3655 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003656 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003657
3658 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3659 userHandle);
3660 pae.isHome = activity.isActivityTypeHome();
3661
3662 // Increment the sessionId if necessary
3663 if (newSessionId) {
3664 mViSessionId++;
3665 }
3666 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003667 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3668 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003669 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003670 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003671 } catch (RemoteException e) {
3672 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3673 return null;
3674 }
3675 return pae;
3676 }
3677 }
3678
3679 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3680 if (result != null) {
3681 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3682 }
3683 if (pae.hint != null) {
3684 pae.extras.putBoolean(pae.hint, true);
3685 }
3686 }
3687
3688 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3689 IAssistDataReceiver receiver;
3690 synchronized (mGlobalLock) {
3691 mPendingAssistExtras.remove(pae);
3692 receiver = pae.receiver;
3693 }
3694 if (receiver != null) {
3695 // Caller wants result sent back to them.
3696 Bundle sendBundle = new Bundle();
3697 // At least return the receiver extras
3698 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3699 try {
3700 pae.receiver.onHandleAssistData(sendBundle);
3701 } catch (RemoteException e) {
3702 }
3703 }
3704 }
3705
3706 public class PendingAssistExtras extends Binder implements Runnable {
3707 public final ActivityRecord activity;
3708 public boolean isHome;
3709 public final Bundle extras;
3710 public final Intent intent;
3711 public final String hint;
3712 public final IAssistDataReceiver receiver;
3713 public final int userHandle;
3714 public boolean haveResult = false;
3715 public Bundle result = null;
3716 public AssistStructure structure = null;
3717 public AssistContent content = null;
3718 public Bundle receiverExtras;
3719
3720 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3721 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3722 int _userHandle) {
3723 activity = _activity;
3724 extras = _extras;
3725 intent = _intent;
3726 hint = _hint;
3727 receiver = _receiver;
3728 receiverExtras = _receiverExtras;
3729 userHandle = _userHandle;
3730 }
3731
3732 @Override
3733 public void run() {
3734 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3735 synchronized (this) {
3736 haveResult = true;
3737 notifyAll();
3738 }
3739 pendingAssistExtrasTimedOut(this);
3740 }
3741 }
3742
3743 @Override
3744 public boolean isAssistDataAllowedOnCurrentActivity() {
3745 int userId;
3746 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003747 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003748 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3749 return false;
3750 }
3751
Wale Ogunwale21e06482019-11-18 05:14:15 -08003752 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003753 if (activity == null) {
3754 return false;
3755 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003756 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003757 }
3758 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3759 }
3760
3761 @Override
3762 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3763 long ident = Binder.clearCallingIdentity();
3764 try {
3765 synchronized (mGlobalLock) {
3766 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003767 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003768 if (top != caller) {
3769 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3770 + " is not current top " + top);
3771 return false;
3772 }
3773 if (!top.nowVisible) {
3774 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3775 + " is not visible");
3776 return false;
3777 }
3778 }
3779 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3780 token);
3781 } finally {
3782 Binder.restoreCallingIdentity(ident);
3783 }
3784 }
3785
3786 @Override
3787 public boolean isRootVoiceInteraction(IBinder token) {
3788 synchronized (mGlobalLock) {
3789 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3790 if (r == null) {
3791 return false;
3792 }
3793 return r.rootVoiceInteraction;
3794 }
3795 }
3796
Wale Ogunwalef6733932018-06-27 05:14:34 -07003797 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3798 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3799 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3800 if (activityToCallback == null) return;
3801 activityToCallback.setVoiceSessionLocked(voiceSession);
3802
3803 // Inform the activity
3804 try {
3805 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3806 voiceInteractor);
3807 long token = Binder.clearCallingIdentity();
3808 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003809 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003810 } finally {
3811 Binder.restoreCallingIdentity(token);
3812 }
3813 // TODO: VI Should we cache the activity so that it's easier to find later
3814 // rather than scan through all the stacks and activities?
3815 } catch (RemoteException re) {
3816 activityToCallback.clearVoiceSessionLocked();
3817 // TODO: VI Should this terminate the voice session?
3818 }
3819 }
3820
3821 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3822 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3823 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3824 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3825 boolean wasRunningVoice = mRunningVoice != null;
3826 mRunningVoice = session;
3827 if (!wasRunningVoice) {
3828 mVoiceWakeLock.acquire();
3829 updateSleepIfNeededLocked();
3830 }
3831 }
3832 }
3833
3834 void finishRunningVoiceLocked() {
3835 if (mRunningVoice != null) {
3836 mRunningVoice = null;
3837 mVoiceWakeLock.release();
3838 updateSleepIfNeededLocked();
3839 }
3840 }
3841
3842 @Override
3843 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3844 synchronized (mGlobalLock) {
3845 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3846 if (keepAwake) {
3847 mVoiceWakeLock.acquire();
3848 } else {
3849 mVoiceWakeLock.release();
3850 }
3851 }
3852 }
3853 }
3854
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003855 @Override
3856 public ComponentName getActivityClassForToken(IBinder token) {
3857 synchronized (mGlobalLock) {
3858 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3859 if (r == null) {
3860 return null;
3861 }
3862 return r.intent.getComponent();
3863 }
3864 }
3865
3866 @Override
3867 public String getPackageForToken(IBinder token) {
3868 synchronized (mGlobalLock) {
3869 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3870 if (r == null) {
3871 return null;
3872 }
3873 return r.packageName;
3874 }
3875 }
3876
3877 @Override
3878 public void showLockTaskEscapeMessage(IBinder token) {
3879 synchronized (mGlobalLock) {
3880 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3881 if (r == null) {
3882 return;
3883 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003884 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003885 }
3886 }
3887
3888 @Override
3889 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003890 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003891 final long token = Binder.clearCallingIdentity();
3892 try {
3893 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003894 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003895 }
3896 } finally {
3897 Binder.restoreCallingIdentity(token);
3898 }
3899 }
3900
3901 /**
3902 * Try to place task to provided position. The final position might be different depending on
3903 * current user and stacks state. The task will be moved to target stack if it's currently in
3904 * different stack.
3905 */
3906 @Override
3907 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003908 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003909 synchronized (mGlobalLock) {
3910 long ident = Binder.clearCallingIdentity();
3911 try {
3912 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3913 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003914 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003915 if (task == null) {
3916 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3917 + taskId);
3918 }
3919
Louis Chang149d5c82019-12-30 09:47:39 +08003920 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003921
3922 if (stack == null) {
3923 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3924 + stackId);
3925 }
3926 if (!stack.isActivityTypeStandardOrUndefined()) {
3927 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3928 + " the position of task " + taskId + " in/to non-standard stack");
3929 }
3930
3931 // TODO: Have the callers of this API call a separate reparent method if that is
3932 // what they intended to do vs. having this method also do reparenting.
3933 if (task.getStack() == stack) {
3934 // Change position in current stack.
3935 stack.positionChildAt(task, position);
3936 } else {
3937 // Reparent to new stack.
3938 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3939 !DEFER_RESUME, "positionTaskInStack");
3940 }
3941 } finally {
3942 Binder.restoreCallingIdentity(ident);
3943 }
3944 }
3945 }
3946
3947 @Override
3948 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3949 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3950 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003951 + Arrays.toString(horizontalSizeConfiguration) + " "
3952 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003953 synchronized (mGlobalLock) {
3954 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3955 if (record == null) {
3956 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3957 + "found for: " + token);
3958 }
3959 record.setSizeConfigurations(horizontalSizeConfiguration,
3960 verticalSizeConfigurations, smallestSizeConfigurations);
3961 }
3962 }
3963
3964 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003965 * Dismisses Pip
3966 * @param animate True if the dismissal should be animated.
3967 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3968 * default animation duration should be used.
3969 */
3970 @Override
3971 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003972 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003973 final long ident = Binder.clearCallingIdentity();
3974 try {
3975 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003976 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08003977 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003978 if (stack == null) {
3979 Slog.w(TAG, "dismissPip: pinned stack not found.");
3980 return;
3981 }
3982 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3983 throw new IllegalArgumentException("Stack: " + stack
3984 + " doesn't support animated resize.");
3985 }
Hongwei Wang85cf41f2020-01-15 15:14:47 -08003986 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003987 }
3988 } finally {
3989 Binder.restoreCallingIdentity(ident);
3990 }
3991 }
3992
3993 @Override
3994 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003995 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003996 synchronized (mGlobalLock) {
3997 mSuppressResizeConfigChanges = suppress;
3998 }
3999 }
4000
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004001 @Override
4002 // TODO: API should just be about changing windowing modes...
4003 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004004 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004005 "moveTasksToFullscreenStack()");
4006 synchronized (mGlobalLock) {
4007 final long origId = Binder.clearCallingIdentity();
4008 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004009 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004010 if (stack != null){
4011 if (!stack.isActivityTypeStandardOrUndefined()) {
4012 throw new IllegalArgumentException(
4013 "You can't move tasks from non-standard stacks.");
4014 }
4015 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4016 }
4017 } finally {
4018 Binder.restoreCallingIdentity(origId);
4019 }
4020 }
4021 }
4022
4023 /**
4024 * Moves the top activity in the input stackId to the pinned stack.
4025 *
4026 * @param stackId Id of stack to move the top activity to pinned stack.
4027 * @param bounds Bounds to use for pinned stack.
4028 *
4029 * @return True if the top activity of the input stack was successfully moved to the pinned
4030 * stack.
4031 */
4032 @Override
4033 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004034 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004035 "moveTopActivityToPinnedStack()");
4036 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004037 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004038 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4039 + "Device doesn't support picture-in-picture mode");
4040 }
4041
4042 long ident = Binder.clearCallingIdentity();
4043 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004044 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004045 } finally {
4046 Binder.restoreCallingIdentity(ident);
4047 }
4048 }
4049 }
4050
4051 @Override
4052 public boolean isInMultiWindowMode(IBinder token) {
4053 final long origId = Binder.clearCallingIdentity();
4054 try {
4055 synchronized (mGlobalLock) {
4056 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4057 if (r == null) {
4058 return false;
4059 }
4060 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4061 return r.inMultiWindowMode();
4062 }
4063 } finally {
4064 Binder.restoreCallingIdentity(origId);
4065 }
4066 }
4067
4068 @Override
4069 public boolean isInPictureInPictureMode(IBinder token) {
4070 final long origId = Binder.clearCallingIdentity();
4071 try {
4072 synchronized (mGlobalLock) {
4073 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4074 }
4075 } finally {
4076 Binder.restoreCallingIdentity(origId);
4077 }
4078 }
4079
4080 private boolean isInPictureInPictureMode(ActivityRecord r) {
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004081 return r != null
4082 && r.getRootTask() != null
4083 && r.inPinnedWindowingMode()
4084 && r.getRootTask().isInStackLocked(r) != null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004085 }
4086
4087 @Override
4088 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4089 final long origId = Binder.clearCallingIdentity();
4090 try {
4091 synchronized (mGlobalLock) {
4092 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4093 "enterPictureInPictureMode", token, params);
4094
4095 // If the activity is already in picture in picture mode, then just return early
4096 if (isInPictureInPictureMode(r)) {
4097 return true;
4098 }
4099
4100 // Activity supports picture-in-picture, now check that we can enter PiP at this
4101 // point, if it is
4102 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4103 false /* beforeStopping */)) {
4104 return false;
4105 }
4106
4107 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004108 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004109 if (r.getParent() == null) {
4110 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4111 return;
4112 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004113 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004114 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004115 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4116 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4117 // Adjust the source bounds by the insets for the transition down
4118 final Rect sourceBounds = new Rect(
4119 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004120 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004121 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004122 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004123 stack.setPictureInPictureAspectRatio(aspectRatio);
4124 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004125 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4126 r.info.applicationInfo.uid, r.shortComponentName,
4127 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004128 logPictureInPictureArgs(params);
4129 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004130 };
4131
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004132 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004133 // If the keyguard is showing or occluded, then try and dismiss it before
4134 // entering picture-in-picture (this will prompt the user to authenticate if the
4135 // device is currently locked).
4136 dismissKeyguard(token, new KeyguardDismissCallback() {
4137 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004138 public void onDismissSucceeded() {
4139 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004140 }
4141 }, null /* message */);
4142 } else {
4143 // Enter picture in picture immediately otherwise
4144 enterPipRunnable.run();
4145 }
4146 return true;
4147 }
4148 } finally {
4149 Binder.restoreCallingIdentity(origId);
4150 }
4151 }
4152
4153 @Override
4154 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4155 final long origId = Binder.clearCallingIdentity();
4156 try {
4157 synchronized (mGlobalLock) {
4158 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4159 "setPictureInPictureParams", token, params);
4160
4161 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004162 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004163 if (r.inPinnedWindowingMode()) {
4164 // If the activity is already in picture-in-picture, update the pinned stack now
4165 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4166 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004167 final ActivityStack stack = r.getRootTask();
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004168 stack.setPictureInPictureAspectRatio(
4169 r.pictureInPictureArgs.getAspectRatio());
4170 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004171 }
4172 logPictureInPictureArgs(params);
4173 }
4174 } finally {
4175 Binder.restoreCallingIdentity(origId);
4176 }
4177 }
4178
4179 @Override
4180 public int getMaxNumPictureInPictureActions(IBinder token) {
4181 // Currently, this is a static constant, but later, we may change this to be dependent on
4182 // the context of the activity
4183 return 3;
4184 }
4185
4186 private void logPictureInPictureArgs(PictureInPictureParams params) {
4187 if (params.hasSetActions()) {
4188 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4189 params.getActions().size());
4190 }
4191 if (params.hasSetAspectRatio()) {
4192 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4193 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4194 MetricsLogger.action(lm);
4195 }
4196 }
4197
4198 /**
4199 * Checks the state of the system and the activity associated with the given {@param token} to
4200 * verify that picture-in-picture is supported for that activity.
4201 *
4202 * @return the activity record for the given {@param token} if all the checks pass.
4203 */
4204 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4205 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004206 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004207 throw new IllegalStateException(caller
4208 + ": Device doesn't support picture-in-picture mode.");
4209 }
4210
4211 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4212 if (r == null) {
4213 throw new IllegalStateException(caller
4214 + ": Can't find activity for token=" + token);
4215 }
4216
4217 if (!r.supportsPictureInPicture()) {
4218 throw new IllegalStateException(caller
4219 + ": Current activity does not support picture-in-picture.");
4220 }
4221
4222 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004223 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004224 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004225 final float minAspectRatio = mContext.getResources().getFloat(
4226 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4227 final float maxAspectRatio = mContext.getResources().getFloat(
4228 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4229 throw new IllegalArgumentException(String.format(caller
4230 + ": Aspect ratio is too extreme (must be between %f and %f).",
4231 minAspectRatio, maxAspectRatio));
4232 }
4233
4234 // Truncate the number of actions if necessary
4235 params.truncateActions(getMaxNumPictureInPictureActions(token));
4236
4237 return r;
4238 }
4239
4240 @Override
4241 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004242 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004243 synchronized (mGlobalLock) {
4244 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4245 if (r == null) {
4246 throw new IllegalArgumentException("Activity does not exist; token="
4247 + activityToken);
4248 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004249 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004250 }
4251 }
4252
Evan Rosky73a7fe92019-11-18 18:28:01 -08004253 // TODO(b/149338177): remove when CTS no-longer requires it
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004254 @Override
4255 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4256 Rect tempDockedTaskInsetBounds,
4257 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004258 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004259 long ident = Binder.clearCallingIdentity();
4260 try {
4261 synchronized (mGlobalLock) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08004262 final DisplayContent dc = mRootWindowContainer.getDefaultDisplay();
4263 TaskTile primary = null;
4264 TaskTile secondary = null;
4265 for (int i = dc.getStackCount() - 1; i >= 0; --i) {
4266 final TaskTile t = dc.getStackAt(i).asTile();
4267 if (t == null) {
4268 continue;
4269 }
4270 if (t.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
4271 primary = t;
4272 } else if (t.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY) {
4273 secondary = t;
4274 }
4275 }
4276 if (primary == null || secondary == null) {
4277 return;
4278 }
4279 final WindowContainerTransaction wct = new WindowContainerTransaction();
4280 final Rect primaryRect =
4281 tempDockedTaskInsetBounds != null ? tempDockedTaskInsetBounds
4282 : (tempDockedTaskBounds != null ? tempDockedTaskBounds
4283 : dockedBounds);
4284 wct.setBounds(primary.mRemoteToken, primaryRect);
4285 Rect otherRect = tempOtherTaskInsetBounds != null ? tempOtherTaskInsetBounds
4286 : tempOtherTaskBounds;
4287 if (otherRect == null) {
4288 // Temporary estimation... again this is just for tests.
4289 otherRect = new Rect(secondary.getBounds());
4290 if (dc.getBounds().width() > dc.getBounds().height()) {
4291 otherRect.left = primaryRect.right + 6;
4292 } else {
4293 otherRect.top = primaryRect.bottom + 6;
4294 }
4295 }
4296 wct.setBounds(secondary.mRemoteToken, otherRect);
4297 mTaskOrganizerController.applyContainerTransaction(wct, null /* organizer */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004298 }
4299 } finally {
4300 Binder.restoreCallingIdentity(ident);
4301 }
4302 }
4303
4304 @Override
4305 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004306 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004307 final long ident = Binder.clearCallingIdentity();
4308 try {
4309 synchronized (mGlobalLock) {
4310 mStackSupervisor.setSplitScreenResizing(resizing);
4311 }
4312 } finally {
4313 Binder.restoreCallingIdentity(ident);
4314 }
4315 }
4316
Evan Rosky0037e5f2019-11-05 10:26:24 -08004317 @Override
4318 public ITaskOrganizerController getTaskOrganizerController() {
4319 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
4320 "getTaskOrganizerController()");
4321 return mTaskOrganizerController;
4322 }
4323
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004324 /**
4325 * Check that we have the features required for VR-related API calls, and throw an exception if
4326 * not.
4327 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004328 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004329 if (!mContext.getPackageManager().hasSystemFeature(
4330 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4331 throw new UnsupportedOperationException("VR mode not supported on this device!");
4332 }
4333 }
4334
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004335 @Override
4336 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004337 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004338
4339 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4340
4341 ActivityRecord r;
4342 synchronized (mGlobalLock) {
4343 r = ActivityRecord.isInStackLocked(token);
4344 }
4345
4346 if (r == null) {
4347 throw new IllegalArgumentException();
4348 }
4349
4350 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004351 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004352 VrManagerInternal.NO_ERROR) {
4353 return err;
4354 }
4355
4356 // Clear the binder calling uid since this path may call moveToTask().
4357 final long callingId = Binder.clearCallingIdentity();
4358 try {
4359 synchronized (mGlobalLock) {
4360 r.requestedVrComponent = (enabled) ? packageName : null;
4361
4362 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004363 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004364 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004365 }
4366 return 0;
4367 }
4368 } finally {
4369 Binder.restoreCallingIdentity(callingId);
4370 }
4371 }
4372
4373 @Override
4374 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4375 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4376 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004377 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004378 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4379 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4380 }
Louis Changcdec0802019-11-11 11:45:07 +08004381 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004382 || activity.voiceSession != null) {
4383 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4384 return;
4385 }
4386 if (activity.pendingVoiceInteractionStart) {
4387 Slog.w(TAG, "Pending start of voice interaction already.");
4388 return;
4389 }
4390 activity.pendingVoiceInteractionStart = true;
4391 }
4392 LocalServices.getService(VoiceInteractionManagerInternal.class)
4393 .startLocalVoiceInteraction(callingActivity, options);
4394 }
4395
4396 @Override
4397 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4398 LocalServices.getService(VoiceInteractionManagerInternal.class)
4399 .stopLocalVoiceInteraction(callingActivity);
4400 }
4401
4402 @Override
4403 public boolean supportsLocalVoiceInteraction() {
4404 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4405 .supportsLocalVoiceInteraction();
4406 }
4407
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004408 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004409 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004410 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004411
4412 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004413 if (mWindowManager == null) {
4414 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4415 return false;
4416 }
4417
4418 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004419 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004420 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004421 }
4422
Riddle Hsua0022cd2019-09-09 21:12:41 +08004423 mH.sendMessage(PooledLambda.obtainMessage(
4424 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4425 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004426
4427 final long origId = Binder.clearCallingIdentity();
4428 try {
4429 if (values != null) {
4430 Settings.System.clearConfiguration(values);
4431 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004432 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004433 UserHandle.USER_NULL, false /* deferResume */,
4434 mTmpUpdateConfigurationResult);
4435 return mTmpUpdateConfigurationResult.changes != 0;
4436 } finally {
4437 Binder.restoreCallingIdentity(origId);
4438 }
4439 }
4440 }
4441
4442 @Override
4443 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4444 CharSequence message) {
4445 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004446 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004447 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4448 }
4449 final long callingId = Binder.clearCallingIdentity();
4450 try {
4451 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004452 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004453 }
4454 } finally {
4455 Binder.restoreCallingIdentity(callingId);
4456 }
4457 }
4458
4459 @Override
4460 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004461 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004462 "cancelTaskWindowTransition()");
4463 final long ident = Binder.clearCallingIdentity();
4464 try {
4465 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004466 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004467 MATCH_TASK_IN_STACKS_ONLY);
4468 if (task == null) {
4469 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4470 return;
4471 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004472 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004473 }
4474 } finally {
4475 Binder.restoreCallingIdentity(ident);
4476 }
4477 }
4478
4479 @Override
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004480 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004481 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004482 final long ident = Binder.clearCallingIdentity();
4483 try {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004484 return getTaskSnapshot(taskId, isLowResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004485 } finally {
4486 Binder.restoreCallingIdentity(ident);
4487 }
4488 }
4489
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004490 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004491 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004492 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004493 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004494 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004495 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4496 if (task == null) {
4497 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4498 return null;
4499 }
4500 }
4501 // Don't call this while holding the lock as this operation might hit the disk.
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004502 return task.getSnapshot(isLowResolution, restoreFromDisk);
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004503 }
4504
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004505 @Override
4506 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4507 synchronized (mGlobalLock) {
4508 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4509 if (r == null) {
4510 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4511 + token);
4512 return;
4513 }
4514 final long origId = Binder.clearCallingIdentity();
4515 try {
4516 r.setDisablePreviewScreenshots(disable);
4517 } finally {
4518 Binder.restoreCallingIdentity(origId);
4519 }
4520 }
4521 }
4522
Riddle Hsu440f88b2019-11-06 22:17:35 +08004523 @Override
4524 public void invalidateHomeTaskSnapshot(IBinder token) {
4525 synchronized (mGlobalLock) {
4526 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4527 if (r == null || !r.isActivityTypeHome()) {
4528 return;
4529 }
4530 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4531 }
4532 }
4533
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004534 /** Return the user id of the last resumed activity. */
4535 @Override
4536 public @UserIdInt
4537 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004538 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004539 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4540 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004541 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004542 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004543 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004544 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004545 }
4546 }
4547
4548 @Override
4549 public void updateLockTaskFeatures(int userId, int flags) {
4550 final int callingUid = Binder.getCallingUid();
4551 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004552 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004553 "updateLockTaskFeatures()");
4554 }
4555 synchronized (mGlobalLock) {
4556 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4557 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004558 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004559 }
4560 }
4561
4562 @Override
4563 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4564 synchronized (mGlobalLock) {
4565 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4566 if (r == null) {
4567 return;
4568 }
4569 final long origId = Binder.clearCallingIdentity();
4570 try {
4571 r.setShowWhenLocked(showWhenLocked);
4572 } finally {
4573 Binder.restoreCallingIdentity(origId);
4574 }
4575 }
4576 }
4577
4578 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004579 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4580 synchronized (mGlobalLock) {
4581 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4582 if (r == null) {
4583 return;
4584 }
4585 final long origId = Binder.clearCallingIdentity();
4586 try {
4587 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4588 } finally {
4589 Binder.restoreCallingIdentity(origId);
4590 }
4591 }
4592 }
4593
4594 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004595 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4596 synchronized (mGlobalLock) {
4597 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4598 if (r == null) {
4599 return;
4600 }
4601 final long origId = Binder.clearCallingIdentity();
4602 try {
4603 r.setTurnScreenOn(turnScreenOn);
4604 } finally {
4605 Binder.restoreCallingIdentity(origId);
4606 }
4607 }
4608 }
4609
4610 @Override
4611 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004612 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004613 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004614 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004615 synchronized (mGlobalLock) {
4616 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4617 if (r == null) {
4618 return;
4619 }
4620 final long origId = Binder.clearCallingIdentity();
4621 try {
4622 r.registerRemoteAnimations(definition);
4623 } finally {
4624 Binder.restoreCallingIdentity(origId);
4625 }
4626 }
4627 }
4628
4629 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004630 public void unregisterRemoteAnimations(IBinder token) {
4631 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4632 "unregisterRemoteAnimations");
4633 synchronized (mGlobalLock) {
4634 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4635 if (r == null) {
4636 return;
4637 }
4638 final long origId = Binder.clearCallingIdentity();
4639 try {
4640 r.unregisterRemoteAnimations();
4641 } finally {
4642 Binder.restoreCallingIdentity(origId);
4643 }
4644 }
4645 }
4646
4647 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004648 public void registerRemoteAnimationForNextActivityStart(String packageName,
4649 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004650 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004651 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004652 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004653 synchronized (mGlobalLock) {
4654 final long origId = Binder.clearCallingIdentity();
4655 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004656 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004657 packageName, adapter);
4658 } finally {
4659 Binder.restoreCallingIdentity(origId);
4660 }
4661 }
4662 }
4663
Evan Rosky966759f2019-01-15 10:33:58 -08004664 @Override
4665 public void registerRemoteAnimationsForDisplay(int displayId,
4666 RemoteAnimationDefinition definition) {
4667 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4668 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004669 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004670 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004671 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004672 if (display == null) {
4673 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4674 return;
4675 }
4676 final long origId = Binder.clearCallingIdentity();
4677 try {
4678 display.mDisplayContent.registerRemoteAnimations(definition);
4679 } finally {
4680 Binder.restoreCallingIdentity(origId);
4681 }
4682 }
4683 }
4684
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004685 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4686 @Override
4687 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4688 synchronized (mGlobalLock) {
4689 final long origId = Binder.clearCallingIdentity();
4690 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004691 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004692 } finally {
4693 Binder.restoreCallingIdentity(origId);
4694 }
4695 }
4696 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004697
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004698 @Override
4699 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004700 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004701 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004702 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004703 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004704 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004705 }
4706 }
4707
4708 @Override
4709 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004710 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004711 != PERMISSION_GRANTED) {
4712 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4713 + Binder.getCallingPid()
4714 + ", uid=" + Binder.getCallingUid()
4715 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4716 Slog.w(TAG, msg);
4717 throw new SecurityException(msg);
4718 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004719 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004720 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004721 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004722 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004723 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004724 }
4725 }
4726
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004727 @Override
4728 public void stopAppSwitches() {
4729 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4730 synchronized (mGlobalLock) {
4731 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004732 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004733 mDidAppSwitch = false;
4734 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4735 }
4736 }
4737
4738 @Override
4739 public void resumeAppSwitches() {
4740 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4741 synchronized (mGlobalLock) {
4742 // Note that we don't execute any pending app switches... we will
4743 // let those wait until either the timeout, or the next start
4744 // activity request.
4745 mAppSwitchesAllowedTime = 0;
4746 }
4747 }
4748
Ricky Wai906af482019-06-03 17:25:28 +01004749 long getLastStopAppSwitchesTime() {
4750 return mLastStopAppSwitchesTime;
4751 }
4752
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004753 void onStartActivitySetDidAppSwitch() {
4754 if (mDidAppSwitch) {
4755 // This is the second allowed switch since we stopped switches, so now just generally
4756 // allow switches. Use case:
4757 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4758 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4759 // anyone to switch again).
4760 mAppSwitchesAllowedTime = 0;
4761 } else {
4762 mDidAppSwitch = true;
4763 }
4764 }
4765
4766 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004767 boolean shouldDisableNonVrUiLocked() {
4768 return mVrController.shouldDisableNonVrUiLocked();
4769 }
4770
Wale Ogunwale53783742018-09-16 10:21:51 -07004771 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004772 // 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 +00004773 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004774 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004775 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4776 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004777 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004778 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004779 }
4780 mH.post(() -> {
4781 if (!mVrController.onVrModeChanged(r)) {
4782 return;
4783 }
4784 synchronized (mGlobalLock) {
4785 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4786 mWindowManager.disableNonVrUi(disableNonVrUi);
4787 if (disableNonVrUi) {
4788 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4789 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004790 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004791 }
4792 }
4793 });
4794 }
4795
Wale Ogunwale53783742018-09-16 10:21:51 -07004796 @Override
4797 public int getPackageScreenCompatMode(String packageName) {
4798 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4799 synchronized (mGlobalLock) {
4800 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4801 }
4802 }
4803
4804 @Override
4805 public void setPackageScreenCompatMode(String packageName, int mode) {
4806 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4807 "setPackageScreenCompatMode");
4808 synchronized (mGlobalLock) {
4809 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4810 }
4811 }
4812
4813 @Override
4814 public boolean getPackageAskScreenCompat(String packageName) {
4815 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4816 synchronized (mGlobalLock) {
4817 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4818 }
4819 }
4820
4821 @Override
4822 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4823 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4824 "setPackageAskScreenCompat");
4825 synchronized (mGlobalLock) {
4826 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4827 }
4828 }
4829
Wale Ogunwale64258362018-10-16 15:13:37 -07004830 public static String relaunchReasonToString(int relaunchReason) {
4831 switch (relaunchReason) {
4832 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4833 return "window_resize";
4834 case RELAUNCH_REASON_FREE_RESIZE:
4835 return "free_resize";
4836 default:
4837 return null;
4838 }
4839 }
4840
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004841 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004842 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004843 }
4844
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004845 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004846 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004847 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4848 }
4849
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004850 boolean isKeyguardLocked() {
4851 return mKeyguardController.isKeyguardLocked();
4852 }
4853
Garfield Tan01548632018-11-27 10:15:48 -08004854 /**
4855 * Clears launch params for the given package.
4856 * @param packageNames the names of the packages of which the launch params are to be cleared
4857 */
4858 @Override
4859 public void clearLaunchParamsForPackages(List<String> packageNames) {
4860 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4861 "clearLaunchParamsForPackages");
4862 synchronized (mGlobalLock) {
4863 for (int i = 0; i < packageNames.size(); ++i) {
4864 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4865 }
4866 }
4867 }
4868
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004869 /**
4870 * Makes the display with the given id a single task instance display. I.e the display can only
4871 * contain one task.
4872 */
4873 @Override
4874 public void setDisplayToSingleTaskInstance(int displayId) {
4875 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4876 "setDisplayToSingleTaskInstance");
4877 final long origId = Binder.clearCallingIdentity();
4878 try {
Louis Chang677921f2019-12-06 16:44:24 +08004879 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004880 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004881 if (display != null) {
4882 display.setDisplayToSingleTaskInstance();
4883 }
4884 } finally {
4885 Binder.restoreCallingIdentity(origId);
4886 }
4887 }
4888
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004889 /**
4890 * Requests that an activity should enter picture-in-picture mode if possible.
4891 */
4892 @Override
4893 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4894 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4895 "requestPictureInPictureMode");
4896 final long origId = Binder.clearCallingIdentity();
4897 try {
4898 synchronized (mGlobalLock) {
4899 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4900 if (activity == null) {
4901 return;
4902 }
4903
4904 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4905 "requestPictureInPictureMode", /* beforeStopping */ false);
4906 if (!canEnterPictureInPicture) {
4907 throw new IllegalStateException(
4908 "Requested PIP on an activity that doesn't support it");
4909 }
4910
4911 try {
4912 final ClientTransaction transaction = ClientTransaction.obtain(
4913 activity.app.getThread(),
4914 activity.token);
4915 transaction.addCallback(EnterPipRequestedItem.obtain());
4916 getLifecycleManager().scheduleTransaction(transaction);
4917 } catch (Exception e) {
4918 Slog.w(TAG, "Failed to send enter pip requested item: "
4919 + activity.intent.getComponent(), e);
4920 }
4921 }
4922 } finally {
4923 Binder.restoreCallingIdentity(origId);
4924 }
4925 }
4926
Wale Ogunwale31913b52018-10-13 08:29:31 -07004927 void dumpLastANRLocked(PrintWriter pw) {
4928 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4929 if (mLastANRState == null) {
4930 pw.println(" <no ANR has occurred since boot>");
4931 } else {
4932 pw.println(mLastANRState);
4933 }
4934 }
4935
4936 void dumpLastANRTracesLocked(PrintWriter pw) {
4937 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4938
4939 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4940 if (ArrayUtils.isEmpty(files)) {
4941 pw.println(" <no ANR has occurred since boot>");
4942 return;
4943 }
4944 // Find the latest file.
4945 File latest = null;
4946 for (File f : files) {
4947 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4948 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004949 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004950 }
4951 pw.print("File: ");
4952 pw.print(latest.getName());
4953 pw.println();
4954 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4955 String line;
4956 while ((line = in.readLine()) != null) {
4957 pw.println(line);
4958 }
4959 } catch (IOException e) {
4960 pw.print("Unable to read: ");
4961 pw.print(e);
4962 pw.println();
4963 }
4964 }
4965
4966 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4967 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4968 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4969 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4970 }
4971
4972 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4973 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4974 pw.println(header);
4975
Louis Chang149d5c82019-12-30 09:47:39 +08004976 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004977 dumpPackage);
4978 boolean needSep = printedAnything;
4979
4980 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08004981 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004982 " ResumedActivity: ");
4983 if (printed) {
4984 printedAnything = true;
4985 needSep = false;
4986 }
4987
4988 if (dumpPackage == null) {
4989 if (needSep) {
4990 pw.println();
4991 }
4992 printedAnything = true;
4993 mStackSupervisor.dump(pw, " ");
4994 }
4995
4996 if (!printedAnything) {
4997 pw.println(" (nothing)");
4998 }
4999 }
5000
5001 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005002 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005003 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005004 pw.println(" ");
5005 }
5006
5007 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5008 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5009 getActivityStartController().dump(pw, "", dumpPackage);
5010 }
5011
5012 /**
5013 * There are three things that cmd can be:
5014 * - a flattened component name that matches an existing activity
5015 * - the cmd arg isn't the flattened component name of an existing activity:
5016 * dump all activity whose component contains the cmd as a substring
5017 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005018 * <p>
5019 * The caller should not hold lock when calling this method because it will wait for the
5020 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005021 *
5022 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5023 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5024 */
5025 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5026 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5027 ArrayList<ActivityRecord> activities;
5028
5029 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005030 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005031 dumpFocusedStackOnly);
5032 }
5033
5034 if (activities.size() <= 0) {
5035 return false;
5036 }
5037
5038 String[] newArgs = new String[args.length - opti];
5039 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5040
Louis Changcdec0802019-11-11 11:45:07 +08005041 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005042 boolean needSep = false;
5043 for (int i = activities.size() - 1; i >= 0; i--) {
5044 ActivityRecord r = activities.get(i);
5045 if (needSep) {
5046 pw.println();
5047 }
5048 needSep = true;
5049 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005050 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005051 if (lastTask != task) {
5052 lastTask = task;
5053 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005054 pw.print(" id="); pw.print(lastTask.mTaskId);
5055 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005056 if (dumpAll) {
5057 lastTask.dump(pw, " ");
5058 }
5059 }
5060 }
5061 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5062 }
5063 return true;
5064 }
5065
5066 /**
5067 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5068 * there is a thread associated with the activity.
5069 */
5070 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5071 final ActivityRecord r, String[] args, boolean dumpAll) {
5072 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005073 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005074 synchronized (mGlobalLock) {
5075 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5076 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5077 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005078 if (r.hasProcess()) {
5079 pw.println(r.app.getPid());
5080 appThread = r.app.getThread();
5081 } else {
5082 pw.println("(not running)");
5083 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005084 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005085 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005086 }
5087 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005088 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005089 // flush anything that is already in the PrintWriter since the thread is going
5090 // to write to the file descriptor directly
5091 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005092 try (TransferPipe tp = new TransferPipe()) {
5093 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5094 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005095 } catch (IOException e) {
5096 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5097 } catch (RemoteException e) {
5098 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5099 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005100 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005101 }
5102
sanryhuang498e77e2018-12-06 14:57:01 +08005103 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5104 boolean testPssMode) {
5105 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5106 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5107 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005108 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005109 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5110 st.toString());
5111 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005112 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5113 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5114 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005115 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5116 testPssMode);
5117 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005118 }
5119
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005120 int getCurrentUserId() {
5121 return mAmInternal.getCurrentUserId();
5122 }
5123
5124 private void enforceNotIsolatedCaller(String caller) {
5125 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5126 throw new SecurityException("Isolated process not allowed to call " + caller);
5127 }
5128 }
5129
Wale Ogunwalef6733932018-06-27 05:14:34 -07005130 public Configuration getConfiguration() {
5131 Configuration ci;
5132 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005133 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005134 ci.userSetLocale = false;
5135 }
5136 return ci;
5137 }
5138
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005139 /**
5140 * Current global configuration information. Contains general settings for the entire system,
5141 * also corresponds to the merged configuration of the default display.
5142 */
5143 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005144 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005145 // while initializing process record for system, see {@link
5146 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005147 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005148 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005149 }
5150
5151 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5152 boolean initLocale) {
5153 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5154 }
5155
5156 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5157 boolean initLocale, boolean deferResume) {
5158 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5159 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5160 UserHandle.USER_NULL, deferResume);
5161 }
5162
Wale Ogunwale59507092018-10-29 09:00:30 -07005163 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005164 final long origId = Binder.clearCallingIdentity();
5165 try {
5166 synchronized (mGlobalLock) {
5167 updateConfigurationLocked(values, null, false, true, userId,
5168 false /* deferResume */);
5169 }
5170 } finally {
5171 Binder.restoreCallingIdentity(origId);
5172 }
5173 }
5174
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005175 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5176 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5177 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5178 deferResume, null /* result */);
5179 }
5180
5181 /**
5182 * Do either or both things: (1) change the current configuration, and (2)
5183 * make sure the given activity is running with the (now) current
5184 * configuration. Returns true if the activity has been left running, or
5185 * false if <var>starting</var> is being destroyed to match the new
5186 * configuration.
5187 *
5188 * @param userId is only used when persistent parameter is set to true to persist configuration
5189 * for that particular user
5190 */
5191 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5192 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5193 ActivityTaskManagerService.UpdateConfigurationResult result) {
5194 int changes = 0;
5195 boolean kept = true;
5196
Riddle Hsua0022cd2019-09-09 21:12:41 +08005197 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005198 try {
5199 if (values != null) {
5200 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5201 deferResume);
5202 }
5203
5204 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5205 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005206 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005207 }
5208
5209 if (result != null) {
5210 result.changes = changes;
5211 result.activityRelaunched = !kept;
5212 }
5213 return kept;
5214 }
5215
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005216 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005217 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005218 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005219
Louis Chang677921f2019-12-06 16:44:24 +08005220 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005221 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005222
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005223 mTempConfig.setTo(getGlobalConfiguration());
5224 final int changes = mTempConfig.updateFrom(values);
5225 if (changes == 0) {
5226 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5227 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5228 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5229 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005230 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005231 return 0;
5232 }
5233
5234 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5235 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005236 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005237 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005238 values.colorMode,
5239 values.densityDpi,
5240 values.fontScale,
5241 values.hardKeyboardHidden,
5242 values.keyboard,
5243 values.keyboardHidden,
5244 values.mcc,
5245 values.mnc,
5246 values.navigation,
5247 values.navigationHidden,
5248 values.orientation,
5249 values.screenHeightDp,
5250 values.screenLayout,
5251 values.screenWidthDp,
5252 values.smallestScreenWidthDp,
5253 values.touchscreen,
5254 values.uiMode);
5255
5256
5257 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5258 final LocaleList locales = values.getLocales();
5259 int bestLocaleIndex = 0;
5260 if (locales.size() > 1) {
5261 if (mSupportedSystemLocales == null) {
5262 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5263 }
5264 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5265 }
5266 SystemProperties.set("persist.sys.locale",
5267 locales.get(bestLocaleIndex).toLanguageTag());
5268 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005269
5270 final Message m = PooledLambda.obtainMessage(
5271 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5272 locales.get(bestLocaleIndex));
5273 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005274 }
5275
Yunfan Chen75157d72018-07-27 14:47:21 +09005276 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005277
5278 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005279 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005280
5281 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5282 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005283 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005284
5285 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005286 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005287
5288 AttributeCache ac = AttributeCache.instance();
5289 if (ac != null) {
5290 ac.updateConfiguration(mTempConfig);
5291 }
5292
5293 // Make sure all resources in our process are updated right now, so that anyone who is going
5294 // to retrieve resource values after we return will be sure to get the new ones. This is
5295 // especially important during boot, where the first config change needs to guarantee all
5296 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005297 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005298
5299 // We need another copy of global config because we're scheduling some calls instead of
5300 // running them in place. We need to be sure that object we send will be handled unchanged.
5301 final Configuration configCopy = new Configuration(mTempConfig);
5302 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005303 final Message msg = PooledLambda.obtainMessage(
5304 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5305 this, userId, configCopy);
5306 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005307 }
5308
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005309 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5310 for (int i = pidMap.size() - 1; i >= 0; i--) {
5311 final int pid = pidMap.keyAt(i);
5312 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005313 if (DEBUG_CONFIGURATION) {
5314 Slog.v(TAG_CONFIGURATION, "Update process config of "
5315 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005316 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005317 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005318 }
5319
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005320 final Message msg = PooledLambda.obtainMessage(
5321 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5322 mAmInternal, changes, initLocale);
5323 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005324
5325 // Override configuration of the default display duplicates global config, so we need to
5326 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005327 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005328 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005329
5330 return changes;
5331 }
5332
Riddle Hsua0022cd2019-09-09 21:12:41 +08005333 /** @see WindowSurfacePlacer#deferLayout */
5334 void deferWindowLayout() {
5335 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5336 // Reset the reasons at the first entrance because we only care about the changes in the
5337 // deferred scope.
5338 mLayoutReasons = 0;
5339 }
5340
5341 mWindowManager.mWindowPlacerLocked.deferLayout();
5342 }
5343
5344 /** @see WindowSurfacePlacer#continueLayout */
5345 void continueWindowLayout() {
5346 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5347 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5348 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5349 }
5350 }
5351
5352 /**
5353 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5354 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5355 * defer count is gone.
5356 */
5357 void addWindowLayoutReasons(@LayoutReason int reasons) {
5358 mLayoutReasons |= reasons;
5359 }
5360
Wale Ogunwalef6733932018-06-27 05:14:34 -07005361 private void updateEventDispatchingLocked(boolean booted) {
5362 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5363 }
5364
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005365 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5366 final ContentResolver resolver = mContext.getContentResolver();
5367 Settings.System.putConfigurationForUser(resolver, config, userId);
5368 }
5369
5370 private void sendLocaleToMountDaemonMsg(Locale l) {
5371 try {
5372 IBinder service = ServiceManager.getService("mount");
5373 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5374 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5375 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5376 } catch (RemoteException e) {
5377 Log.e(TAG, "Error storing locale for decryption UI", e);
5378 }
5379 }
5380
Alison Cichowlas3e340502018-08-07 17:15:01 -04005381 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5382 mStartActivitySources.remove(permissionToken);
5383 mExpiredStartAsCallerTokens.add(permissionToken);
5384 }
5385
5386 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5387 mExpiredStartAsCallerTokens.remove(permissionToken);
5388 }
5389
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005390 boolean isActivityStartsLoggingEnabled() {
5391 return mAmInternal.isActivityStartsLoggingEnabled();
5392 }
5393
Michal Karpinski8596ded2018-11-14 14:43:48 +00005394 boolean isBackgroundActivityStartsEnabled() {
5395 return mAmInternal.isBackgroundActivityStartsEnabled();
5396 }
5397
Wale Ogunwalef6733932018-06-27 05:14:34 -07005398 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005399 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005400 mWindowManager.enableScreenAfterBoot();
5401
5402 synchronized (mGlobalLock) {
5403 updateEventDispatchingLocked(booted);
5404 }
5405 }
5406
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005407 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5408 if (r == null || !r.hasProcess()) {
5409 return KEY_DISPATCHING_TIMEOUT_MS;
5410 }
5411 return getInputDispatchingTimeoutLocked(r.app);
5412 }
5413
5414 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005415 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005416 }
5417
Wale Ogunwalef6733932018-06-27 05:14:34 -07005418 /**
5419 * Decide based on the configuration whether we should show the ANR,
5420 * crash, etc dialogs. The idea is that if there is no affordance to
5421 * press the on-screen buttons, or the user experience would be more
5422 * greatly impacted than the crash itself, we shouldn't show the dialog.
5423 *
5424 * A thought: SystemUI might also want to get told about this, the Power
5425 * dialog / global actions also might want different behaviors.
5426 */
5427 private void updateShouldShowDialogsLocked(Configuration config) {
5428 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5429 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5430 && config.navigation == Configuration.NAVIGATION_NONAV);
5431 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5432 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5433 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5434 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5435 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5436 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5437 HIDE_ERROR_DIALOGS, 0) != 0;
5438 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5439 }
5440
5441 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5442 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5443 FONT_SCALE, 1.0f, userId);
5444
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005445 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005446 if (getGlobalConfiguration().fontScale == scaleFactor) {
5447 return;
5448 }
5449
5450 final Configuration configuration
5451 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5452 configuration.fontScale = scaleFactor;
5453 updatePersistentConfiguration(configuration, userId);
5454 }
5455 }
5456
5457 // Actually is sleeping or shutting down or whatever else in the future
5458 // is an inactive state.
5459 boolean isSleepingOrShuttingDownLocked() {
5460 return isSleepingLocked() || mShuttingDown;
5461 }
5462
5463 boolean isSleepingLocked() {
5464 return mSleeping;
5465 }
5466
Riddle Hsu16567132018-08-16 21:37:47 +08005467 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005468 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005469 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005470 if (task.isActivityTypeStandard()) {
5471 if (mCurAppTimeTracker != r.appTimeTracker) {
5472 // We are switching app tracking. Complete the current one.
5473 if (mCurAppTimeTracker != null) {
5474 mCurAppTimeTracker.stop();
5475 mH.obtainMessage(
5476 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005477 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005478 mCurAppTimeTracker = null;
5479 }
5480 if (r.appTimeTracker != null) {
5481 mCurAppTimeTracker = r.appTimeTracker;
5482 startTimeTrackingFocusedActivityLocked();
5483 }
5484 } else {
5485 startTimeTrackingFocusedActivityLocked();
5486 }
5487 } else {
5488 r.appTimeTracker = null;
5489 }
5490 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5491 // TODO: Probably not, because we don't want to resume voice on switching
5492 // back to this activity
5493 if (task.voiceInteractor != null) {
5494 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5495 } else {
5496 finishRunningVoiceLocked();
5497
5498 if (mLastResumedActivity != null) {
5499 final IVoiceInteractionSession session;
5500
Louis Changcdec0802019-11-11 11:45:07 +08005501 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005502 if (lastResumedActivityTask != null
5503 && lastResumedActivityTask.voiceSession != null) {
5504 session = lastResumedActivityTask.voiceSession;
5505 } else {
5506 session = mLastResumedActivity.voiceSession;
5507 }
5508
5509 if (session != null) {
5510 // We had been in a voice interaction session, but now focused has
5511 // move to something different. Just finish the session, we can't
5512 // return to it and retain the proper state and synchronization with
5513 // the voice interaction service.
5514 finishVoiceTask(session);
5515 }
5516 }
5517 }
5518
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005519 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5520 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005521 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005522 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5523
Wale Ogunwalef6733932018-06-27 05:14:34 -07005524 updateResumedAppTrace(r);
5525 mLastResumedActivity = r;
5526
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005527 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005528
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005529 if (prevTask == null || task != prevTask) {
5530 if (prevTask != null) {
5531 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5532 }
5533 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5534 }
5535
Wale Ogunwalef6733932018-06-27 05:14:34 -07005536 applyUpdateLockStateLocked(r);
5537 applyUpdateVrModeLocked(r);
5538
Jeff Changd136e772019-11-05 20:33:52 +08005539 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005540 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005541 r == null ? "NULL" : r.shortComponentName,
5542 reason);
5543 }
5544
5545 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5546 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005547 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005548 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005549 updateSleepIfNeededLocked();
5550 return token;
5551 }
5552 }
5553
5554 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005555 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005556 final boolean wasSleeping = mSleeping;
5557 boolean updateOomAdj = false;
5558
5559 if (!shouldSleep) {
5560 // If wasSleeping is true, we need to wake up activity manager state from when
5561 // we started sleeping. In either case, we need to apply the sleep tokens, which
5562 // will wake up stacks or put them to sleep as appropriate.
5563 if (wasSleeping) {
5564 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005565 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5566 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005567 startTimeTrackingFocusedActivityLocked();
5568 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005569 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005570 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5571 }
Louis Chang149d5c82019-12-30 09:47:39 +08005572 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005573 if (wasSleeping) {
5574 updateOomAdj = true;
5575 }
5576 } else if (!mSleeping && shouldSleep) {
5577 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005578 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5579 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005580 if (mCurAppTimeTracker != null) {
5581 mCurAppTimeTracker.stop();
5582 }
5583 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005584 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005585 mStackSupervisor.goingToSleepLocked();
5586 updateResumedAppTrace(null /* resumed */);
5587 updateOomAdj = true;
5588 }
5589 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005590 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005591 }
5592 }
5593
5594 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005595 mH.removeCallbacks(mUpdateOomAdjRunnable);
5596 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005597 }
5598
Wale Ogunwale53783742018-09-16 10:21:51 -07005599 void updateCpuStats() {
5600 mH.post(mAmInternal::updateCpuStats);
5601 }
5602
Hui Yu03d12402018-12-06 18:00:37 -08005603 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5604 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005605 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5606 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005607 mH.sendMessage(m);
5608 }
5609
Hui Yu03d12402018-12-06 18:00:37 -08005610 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005611 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005612 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005613 if (task != null) {
5614 final ActivityRecord rootActivity = task.getRootActivity();
5615 if (rootActivity != null) {
5616 taskRoot = rootActivity.mActivityComponent;
5617 }
5618 }
5619
Hui Yu03d12402018-12-06 18:00:37 -08005620 final Message m = PooledLambda.obtainMessage(
5621 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005622 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005623 mH.sendMessage(m);
5624 }
5625
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005626 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5627 String hostingType) {
5628 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005629 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5630 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005631 + activity.processName);
5632 }
5633 // Post message to start process to avoid possible deadlock of calling into AMS with the
5634 // ATMS lock held.
5635 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5636 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5637 isTop, hostingType, activity.intent.getComponent());
5638 mH.sendMessage(m);
5639 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005640 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005641 }
5642 }
5643
Wale Ogunwale53783742018-09-16 10:21:51 -07005644 void setBooting(boolean booting) {
5645 mAmInternal.setBooting(booting);
5646 }
5647
5648 boolean isBooting() {
5649 return mAmInternal.isBooting();
5650 }
5651
5652 void setBooted(boolean booted) {
5653 mAmInternal.setBooted(booted);
5654 }
5655
5656 boolean isBooted() {
5657 return mAmInternal.isBooted();
5658 }
5659
5660 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5661 mH.post(() -> {
5662 if (finishBooting) {
5663 mAmInternal.finishBooting();
5664 }
5665 if (enableScreen) {
5666 mInternal.enableScreenAfterBoot(isBooted());
5667 }
5668 });
5669 }
5670
5671 void setHeavyWeightProcess(ActivityRecord root) {
5672 mHeavyWeightProcess = root.app;
5673 final Message m = PooledLambda.obtainMessage(
5674 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005675 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005676 mH.sendMessage(m);
5677 }
5678
5679 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5680 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5681 return;
5682 }
5683
5684 mHeavyWeightProcess = null;
5685 final Message m = PooledLambda.obtainMessage(
5686 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5687 proc.mUserId);
5688 mH.sendMessage(m);
5689 }
5690
5691 private void cancelHeavyWeightProcessNotification(int userId) {
5692 final INotificationManager inm = NotificationManager.getService();
5693 if (inm == null) {
5694 return;
5695 }
5696 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005697 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005698 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5699 } catch (RuntimeException e) {
5700 Slog.w(TAG, "Error canceling notification for service", e);
5701 } catch (RemoteException e) {
5702 }
5703
5704 }
5705
5706 private void postHeavyWeightProcessNotification(
5707 WindowProcessController proc, Intent intent, int userId) {
5708 if (proc == null) {
5709 return;
5710 }
5711
5712 final INotificationManager inm = NotificationManager.getService();
5713 if (inm == null) {
5714 return;
5715 }
5716
5717 try {
5718 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5719 String text = mContext.getString(R.string.heavy_weight_notification,
5720 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5721 Notification notification =
5722 new Notification.Builder(context,
5723 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5724 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5725 .setWhen(0)
5726 .setOngoing(true)
5727 .setTicker(text)
5728 .setColor(mContext.getColor(
5729 com.android.internal.R.color.system_notification_accent_color))
5730 .setContentTitle(text)
5731 .setContentText(
5732 mContext.getText(R.string.heavy_weight_notification_detail))
5733 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5734 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5735 new UserHandle(userId)))
5736 .build();
5737 try {
5738 inm.enqueueNotificationWithTag("android", "android", null,
5739 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5740 } catch (RuntimeException e) {
5741 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5742 } catch (RemoteException e) {
5743 }
5744 } catch (PackageManager.NameNotFoundException e) {
5745 Slog.w(TAG, "Unable to create context for heavy notification", e);
5746 }
5747
5748 }
5749
Philip P. Moltmannee295092020-02-10 08:46:26 -08005750 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5751 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5752 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005753
5754 ActivityRecord activity = null;
5755 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5756 activity = ActivityRecord.isInStackLocked(token);
5757 if (activity == null) {
5758 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5759 return null;
5760 }
5761 if (activity.finishing) {
5762 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5763 return null;
5764 }
5765 }
5766
5767 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005768 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5769 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005770 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5771 if (noCreate) {
5772 return rec;
5773 }
5774 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5775 if (activity.pendingResults == null) {
5776 activity.pendingResults = new HashSet<>();
5777 }
5778 activity.pendingResults.add(rec.ref);
5779 }
5780 return rec;
5781 }
5782
Andrii Kulian52d255c2018-07-13 11:32:19 -07005783 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005784 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005785 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005786 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5787 mCurAppTimeTracker.start(resumedActivity.packageName);
5788 }
5789 }
5790
5791 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5792 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005793 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005794 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5795 }
5796 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005797 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005798 constructResumedTraceName(resumed.packageName), 0);
5799 }
5800 mTracedResumedActivity = resumed;
5801 }
5802
5803 private String constructResumedTraceName(String packageName) {
5804 return "focused app: " + packageName;
5805 }
5806
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005807 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005808 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005809 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005810 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005811 // mainStack is null during startup.
5812 if (mainStack != null) {
5813 if (changes != 0 && starting == null) {
5814 // If the configuration changed, and the caller is not already
5815 // in the process of starting an activity, then find the top
5816 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005817 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005818 }
5819
5820 if (starting != null) {
5821 kept = starting.ensureActivityConfiguration(changes,
5822 false /* preserveWindow */);
5823 // And we need to make sure at this point that all other activities
5824 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005825 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005826 !PRESERVE_WINDOWS);
5827 }
5828 }
5829
5830 return kept;
5831 }
5832
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005833 void scheduleAppGcsLocked() {
5834 mH.post(() -> mAmInternal.scheduleAppGcs());
5835 }
5836
Wale Ogunwale53783742018-09-16 10:21:51 -07005837 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5838 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5839 }
5840
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005841 /**
5842 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5843 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5844 * on demand.
5845 */
5846 IPackageManager getPackageManager() {
5847 return AppGlobals.getPackageManager();
5848 }
5849
5850 PackageManagerInternal getPackageManagerInternalLocked() {
5851 if (mPmInternal == null) {
5852 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5853 }
5854 return mPmInternal;
5855 }
5856
Hai Zhangf4da9be2019-05-01 13:46:06 +08005857 PermissionPolicyInternal getPermissionPolicyInternal() {
5858 if (mPermissionPolicyInternal == null) {
5859 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5860 }
5861 return mPermissionPolicyInternal;
5862 }
5863
Wale Ogunwale008163e2018-07-23 23:11:08 -07005864 AppWarnings getAppWarningsLocked() {
5865 return mAppWarnings;
5866 }
5867
Wale Ogunwale214f3482018-10-04 11:00:47 -07005868 Intent getHomeIntent() {
5869 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5870 intent.setComponent(mTopComponent);
5871 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5872 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5873 intent.addCategory(Intent.CATEGORY_HOME);
5874 }
5875 return intent;
5876 }
5877
Chilun2ef71f72018-11-16 17:57:15 +08005878 /**
5879 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5880 * activities.
5881 *
Chilun939b05c2020-02-19 14:50:59 +08005882 * @param preferredPackage Specify a preferred package name, otherwise use the package name
5883 * defined in config_secondaryHomePackage.
Chilun2ef71f72018-11-16 17:57:15 +08005884 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5885 */
5886 Intent getSecondaryHomeIntent(String preferredPackage) {
5887 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005888 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5889 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5890 if (preferredPackage == null || useSystemProvidedLauncher) {
Chilun939b05c2020-02-19 14:50:59 +08005891 // Using the package name stored in config if no preferred package name or forced.
5892 final String secondaryHomePackage = mContext.getResources().getString(
5893 com.android.internal.R.string.config_secondaryHomePackage);
5894 intent.setPackage(secondaryHomePackage);
Chilun2ef71f72018-11-16 17:57:15 +08005895 } else {
5896 intent.setPackage(preferredPackage);
5897 }
5898 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5899 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5900 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5901 }
5902 return intent;
5903 }
5904
Wale Ogunwale214f3482018-10-04 11:00:47 -07005905 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5906 if (info == null) return null;
5907 ApplicationInfo newInfo = new ApplicationInfo(info);
5908 newInfo.initForUser(userId);
5909 return newInfo;
5910 }
5911
Wale Ogunwale9c103022018-10-18 07:44:54 -07005912 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005913 if (uid == SYSTEM_UID) {
5914 // The system gets to run in any process. If there are multiple processes with the same
5915 // uid, just pick the first (this should never happen).
5916 final SparseArray<WindowProcessController> procs =
5917 mProcessNames.getMap().get(processName);
5918 if (procs == null) return null;
5919 final int procCount = procs.size();
5920 for (int i = 0; i < procCount; i++) {
5921 final int procUid = procs.keyAt(i);
5922 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5923 // Don't use an app process or different user process for system component.
5924 continue;
5925 }
5926 return procs.valueAt(i);
5927 }
5928 }
5929
5930 return mProcessNames.get(processName, uid);
5931 }
5932
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005933 WindowProcessController getProcessController(IApplicationThread thread) {
5934 if (thread == null) {
5935 return null;
5936 }
5937
5938 final IBinder threadBinder = thread.asBinder();
5939 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5940 for (int i = pmap.size()-1; i >= 0; i--) {
5941 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5942 for (int j = procs.size() - 1; j >= 0; j--) {
5943 final WindowProcessController proc = procs.valueAt(j);
5944 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5945 return proc;
5946 }
5947 }
5948 }
5949
5950 return null;
5951 }
5952
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005953 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005954 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005955 if (proc == null) return null;
5956 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5957 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005958 }
5959 return null;
5960 }
5961
Riddle Hsua0536432019-02-16 00:38:59 +08005962 int getUidState(int uid) {
5963 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005964 }
5965
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005966 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005967 // A uid is considered to be foreground if it has a visible non-toast window.
5968 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005969 }
5970
Ricky Wai96f5c352019-04-10 18:40:17 +01005971 boolean isDeviceOwner(int uid) {
5972 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005973 }
5974
Ricky Wai96f5c352019-04-10 18:40:17 +01005975 void setDeviceOwnerUid(int uid) {
5976 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005977 }
5978
Wale Ogunwale9de19442018-10-18 19:05:03 -07005979 /**
5980 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5981 * the whitelist
5982 */
5983 String getPendingTempWhitelistTagForUidLocked(int uid) {
5984 return mPendingTempWhitelist.get(uid);
5985 }
5986
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005987 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5988 if (true || Build.IS_USER) {
5989 return;
5990 }
5991
5992 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5993 StrictMode.allowThreadDiskWrites();
5994 try {
5995 File tracesDir = new File("/data/anr");
5996 File tracesFile = null;
5997 try {
5998 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5999
6000 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006001 String timeString =
6002 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6003 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006004 sb.append(": ");
6005 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6006 sb.append(" since ");
6007 sb.append(msg);
6008 FileOutputStream fos = new FileOutputStream(tracesFile);
6009 fos.write(sb.toString().getBytes());
6010 if (app == null) {
6011 fos.write("\n*** No application process!".getBytes());
6012 }
6013 fos.close();
6014 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6015 } catch (IOException e) {
6016 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6017 return;
6018 }
6019
6020 if (app != null && app.getPid() > 0) {
6021 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6022 firstPids.add(app.getPid());
6023 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6024 }
6025
6026 File lastTracesFile = null;
6027 File curTracesFile = null;
6028 for (int i=9; i>=0; i--) {
6029 String name = String.format(Locale.US, "slow%02d.txt", i);
6030 curTracesFile = new File(tracesDir, name);
6031 if (curTracesFile.exists()) {
6032 if (lastTracesFile != null) {
6033 curTracesFile.renameTo(lastTracesFile);
6034 } else {
6035 curTracesFile.delete();
6036 }
6037 }
6038 lastTracesFile = curTracesFile;
6039 }
6040 tracesFile.renameTo(curTracesFile);
6041 } finally {
6042 StrictMode.setThreadPolicy(oldPolicy);
6043 }
6044 }
6045
Michal Karpinskida34cd42019-04-02 19:46:52 +01006046 boolean isAssociatedCompanionApp(int userId, int uid) {
6047 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6048 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006049 return false;
6050 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006051 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006052 }
6053
Issei Suzuki734bc942019-06-05 13:59:52 +02006054 void notifySingleTaskDisplayEmpty(int displayId) {
6055 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6056 }
6057
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006058 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006059 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006060
6061
Wale Ogunwale98875612018-10-12 07:53:02 -07006062 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6063 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006064
Riddle Hsud93a6c42018-11-29 21:50:06 +08006065 H(Looper looper) {
6066 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006067 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006068
6069 @Override
6070 public void handleMessage(Message msg) {
6071 switch (msg.what) {
6072 case REPORT_TIME_TRACKER_MSG: {
6073 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6074 tracker.deliverResult(mContext);
6075 } break;
6076 }
6077 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006078 }
6079
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006080 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006081 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006082
6083 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006084 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006085 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006086
6087 @Override
6088 public void handleMessage(Message msg) {
6089 switch (msg.what) {
6090 case DISMISS_DIALOG_UI_MSG: {
6091 final Dialog d = (Dialog) msg.obj;
6092 d.dismiss();
6093 break;
6094 }
6095 }
6096 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006097 }
6098
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006099 final class LocalService extends ActivityTaskManagerInternal {
6100 @Override
6101 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006102 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006103 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006104 }
6105
6106 @Override
6107 public ComponentName getHomeActivityForUser(int userId) {
6108 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006109 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006110 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006111 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006112 }
6113 }
6114
6115 @Override
6116 public void onLocalVoiceInteractionStarted(IBinder activity,
6117 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6118 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006119 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006120 }
6121 }
6122
6123 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006124 public void notifySingleTaskDisplayDrawn(int displayId) {
6125 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6126 }
6127
6128 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006129 public void notifyAppTransitionFinished() {
6130 synchronized (mGlobalLock) {
6131 mStackSupervisor.notifyAppTransitionDone();
6132 }
6133 }
6134
6135 @Override
6136 public void notifyAppTransitionCancelled() {
6137 synchronized (mGlobalLock) {
6138 mStackSupervisor.notifyAppTransitionDone();
6139 }
6140 }
6141
6142 @Override
6143 public List<IBinder> getTopVisibleActivities() {
6144 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006145 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006146 }
6147 }
6148
6149 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006150 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6151 int userId, Intent[] intents, Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006152 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006153 final String[] resolvedTypes = new String[intents.length];
6154
6155 // UID of the package on user userId.
6156 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6157 // packageUid may not be initialized.
6158 int packageUid = 0;
6159 final long ident = Binder.clearCallingIdentity();
6160
6161 try {
6162 for (int i = 0; i < intents.length; i++) {
6163 resolvedTypes[i] =
6164 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6165 }
6166
6167 packageUid = AppGlobals.getPackageManager().getPackageUid(
6168 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6169 } catch (RemoteException e) {
6170 // Shouldn't happen.
6171 } finally {
6172 Binder.restoreCallingIdentity(ident);
6173 }
6174
Riddle Hsu591bf612019-02-14 17:55:31 +08006175 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006176 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006177 intents, resolvedTypes, null /* resultTo */,
6178 SafeActivityOptions.fromBundle(bOptions), userId,
6179 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6180 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006181 }
6182
6183 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006184 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006185 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6186 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6187 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006188 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006189 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006190 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006191 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006192 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6193 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006194 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006195 }
6196 }
6197
6198 @Override
6199 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006200 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6201 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6202 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6203 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006204 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006205 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006206 synchronized (mGlobalLock) {
6207 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006208 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6209 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6210 reason, validateIncomingUser, originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006211 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006212 }
6213 }
6214
6215 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006216 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006217 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6218 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006219 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006220 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006221 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006222 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006223 false /*validateIncomingUser*/);
6224 }
6225
6226 @Override
lumark588a3e82018-07-20 18:53:54 +08006227 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006228 synchronized (mGlobalLock) {
6229
6230 // We might change the visibilities here, so prepare an empty app transition which
6231 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006232 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006233 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006234 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006235 return;
6236 }
Louis Chang677921f2019-12-06 16:44:24 +08006237 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006238 final boolean wasTransitionSet =
6239 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006240 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006241 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006242 }
Louis Chang149d5c82019-12-30 09:47:39 +08006243 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006244
6245 // If there was a transition set already we don't want to interfere with it as we
6246 // might be starting it too early.
6247 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006248 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006249 }
6250 }
6251 if (callback != null) {
6252 callback.run();
6253 }
6254 }
6255
6256 @Override
6257 public void notifyKeyguardTrustedChanged() {
6258 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006259 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006260 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006261 }
6262 }
6263 }
6264
6265 /**
6266 * Called after virtual display Id is updated by
6267 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6268 * {@param vrVr2dDisplayId}.
6269 */
6270 @Override
6271 public void setVr2dDisplayId(int vr2dDisplayId) {
6272 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6273 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006274 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006275 }
6276 }
6277
6278 @Override
6279 public void setFocusedActivity(IBinder token) {
6280 synchronized (mGlobalLock) {
6281 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6282 if (r == null) {
6283 throw new IllegalArgumentException(
6284 "setFocusedActivity: No activity record matching token=" + token);
6285 }
Louis Chang19443452018-10-09 12:10:21 +08006286 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006287 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006288 }
6289 }
6290 }
6291
6292 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006293 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006294 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006295 }
6296
6297 @Override
6298 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006299 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006300 }
6301
6302 @Override
6303 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006304 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006305 }
6306
6307 @Override
6308 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6309 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6310 }
6311
6312 @Override
6313 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006314 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006315 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006316
6317 @Override
6318 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6319 synchronized (mGlobalLock) {
6320 mActiveVoiceInteractionServiceComponent = component;
6321 }
6322 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006323
6324 @Override
6325 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6326 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6327 return;
6328 }
6329 synchronized (mGlobalLock) {
6330 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6331 if (types == null) {
6332 if (uid < 0) {
6333 return;
6334 }
6335 types = new ArrayMap<>();
6336 mAllowAppSwitchUids.put(userId, types);
6337 }
6338 if (uid < 0) {
6339 types.remove(type);
6340 } else {
6341 types.put(type, uid);
6342 }
6343 }
6344 }
6345
6346 @Override
6347 public void onUserStopped(int userId) {
6348 synchronized (mGlobalLock) {
6349 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6350 mAllowAppSwitchUids.remove(userId);
6351 }
6352 }
6353
6354 @Override
6355 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6356 synchronized (mGlobalLock) {
6357 return ActivityTaskManagerService.this.isGetTasksAllowed(
6358 caller, callingPid, callingUid);
6359 }
6360 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006361
Riddle Hsua0536432019-02-16 00:38:59 +08006362 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006363 @Override
6364 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006365 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006366 mProcessNames.put(proc.mName, proc.mUid, proc);
6367 }
6368 }
6369
Riddle Hsua0536432019-02-16 00:38:59 +08006370 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006371 @Override
6372 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006373 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006374 mProcessNames.remove(name, uid);
6375 }
6376 }
6377
Riddle Hsua0536432019-02-16 00:38:59 +08006378 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006379 @Override
6380 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006381 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006382 if (proc == mHomeProcess) {
6383 mHomeProcess = null;
6384 }
6385 if (proc == mPreviousProcess) {
6386 mPreviousProcess = null;
6387 }
6388 }
6389 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006390
Riddle Hsua0536432019-02-16 00:38:59 +08006391 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006392 @Override
6393 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006394 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006395 return mTopProcessState;
6396 }
6397 }
6398
Riddle Hsua0536432019-02-16 00:38:59 +08006399 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006400 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006401 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006402 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006403 return proc == mHeavyWeightProcess;
6404 }
6405 }
6406
Riddle Hsua0536432019-02-16 00:38:59 +08006407 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006408 @Override
6409 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006410 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006411 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6412 }
6413 }
6414
6415 @Override
6416 public void finishHeavyWeightApp() {
6417 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006418 if (mHeavyWeightProcess != null) {
6419 mHeavyWeightProcess.finishActivities();
6420 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006421 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6422 mHeavyWeightProcess);
6423 }
6424 }
6425
Riddle Hsua0536432019-02-16 00:38:59 +08006426 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006427 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006428 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006429 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006430 return isSleepingLocked();
6431 }
6432 }
6433
6434 @Override
6435 public boolean isShuttingDown() {
6436 synchronized (mGlobalLock) {
6437 return mShuttingDown;
6438 }
6439 }
6440
6441 @Override
6442 public boolean shuttingDown(boolean booted, int timeout) {
6443 synchronized (mGlobalLock) {
6444 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006445 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006446 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006447 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006448 return mStackSupervisor.shutdownLocked(timeout);
6449 }
6450 }
6451
6452 @Override
6453 public void enableScreenAfterBoot(boolean booted) {
6454 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006455 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006456 mWindowManager.enableScreenAfterBoot();
6457 updateEventDispatchingLocked(booted);
6458 }
6459 }
6460
6461 @Override
6462 public boolean showStrictModeViolationDialog() {
6463 synchronized (mGlobalLock) {
6464 return mShowDialogs && !mSleeping && !mShuttingDown;
6465 }
6466 }
6467
6468 @Override
6469 public void showSystemReadyErrorDialogsIfNeeded() {
6470 synchronized (mGlobalLock) {
6471 try {
6472 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6473 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6474 + " data partition or your device will be unstable.");
6475 mUiHandler.post(() -> {
6476 if (mShowDialogs) {
6477 AlertDialog d = new BaseErrorDialog(mUiContext);
6478 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6479 d.setCancelable(false);
6480 d.setTitle(mUiContext.getText(R.string.android_system_label));
6481 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6482 d.setButton(DialogInterface.BUTTON_POSITIVE,
6483 mUiContext.getText(R.string.ok),
6484 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6485 d.show();
6486 }
6487 });
6488 }
6489 } catch (RemoteException e) {
6490 }
6491
6492 if (!Build.isBuildConsistent()) {
6493 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6494 mUiHandler.post(() -> {
6495 if (mShowDialogs) {
6496 AlertDialog d = new BaseErrorDialog(mUiContext);
6497 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6498 d.setCancelable(false);
6499 d.setTitle(mUiContext.getText(R.string.android_system_label));
6500 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6501 d.setButton(DialogInterface.BUTTON_POSITIVE,
6502 mUiContext.getText(R.string.ok),
6503 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6504 d.show();
6505 }
6506 });
6507 }
6508 }
6509 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006510
6511 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006512 public void onProcessMapped(int pid, WindowProcessController proc) {
6513 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006514 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006515 }
6516 }
6517
6518 @Override
6519 public void onProcessUnMapped(int pid) {
6520 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006521 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006522 }
6523 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006524
6525 @Override
6526 public void onPackageDataCleared(String name) {
6527 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006528 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006529 mAppWarnings.onPackageDataCleared(name);
6530 }
6531 }
6532
6533 @Override
6534 public void onPackageUninstalled(String name) {
6535 synchronized (mGlobalLock) {
6536 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006537 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006538 }
6539 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006540
6541 @Override
6542 public void onPackageAdded(String name, boolean replacing) {
6543 synchronized (mGlobalLock) {
6544 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6545 }
6546 }
6547
6548 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006549 public void onPackageReplaced(ApplicationInfo aInfo) {
6550 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006551 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006552 }
6553 }
6554
6555 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006556 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6557 synchronized (mGlobalLock) {
6558 return compatibilityInfoForPackageLocked(ai);
6559 }
6560 }
6561
Yunfan Chen75157d72018-07-27 14:47:21 +09006562 /**
6563 * Set the corresponding display information for the process global configuration. To be
6564 * called when we need to show IME on a different display.
6565 *
6566 * @param pid The process id associated with the IME window.
6567 * @param displayId The ID of the display showing the IME.
6568 */
6569 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006570 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006571 // Don't update process-level configuration for Multi-Client IME process since other
6572 // IMEs on other displays will also receive this configuration change due to IME
6573 // services use the same application config/context.
6574 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006575
Yunfan Chen75157d72018-07-27 14:47:21 +09006576 if (pid == MY_PID || pid < 0) {
6577 if (DEBUG_CONFIGURATION) {
6578 Slog.w(TAG,
6579 "Trying to update display configuration for system/invalid process.");
6580 }
6581 return;
6582 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006583 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006584 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006585 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006586 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006587 // Call might come when display is not yet added or has been removed.
6588 if (DEBUG_CONFIGURATION) {
6589 Slog.w(TAG, "Trying to update display configuration for non-existing "
6590 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006591 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006592 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006593 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006594 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006595 if (process == null) {
6596 if (DEBUG_CONFIGURATION) {
6597 Slog.w(TAG, "Trying to update display configuration for invalid "
6598 + "process, pid=" + pid);
6599 }
6600 return;
6601 }
lumarkddc77fb2019-06-27 22:22:23 +08006602 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006603 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006604 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006605 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006606
6607 @Override
6608 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006609 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006610 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006611 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006612 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006613 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006614 }
6615 }
6616 }
6617
6618 @Override
6619 public void clearPendingResultForActivity(IBinder activityToken,
6620 WeakReference<PendingIntentRecord> pir) {
6621 synchronized (mGlobalLock) {
6622 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6623 if (r != null && r.pendingResults != null) {
6624 r.pendingResults.remove(pir);
6625 }
6626 }
6627 }
6628
6629 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006630 public ActivityTokens getTopActivityForTask(int taskId) {
6631 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006632 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006633 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006634 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6635 + " Requested task not found");
6636 return null;
6637 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006638 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006639 if (activity == null) {
6640 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6641 + " Requested activity not found");
6642 return null;
6643 }
6644 if (!activity.attachedToProcess()) {
6645 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6646 + activity);
6647 return null;
6648 }
6649 return new ActivityTokens(activity.appToken, activity.assistToken,
6650 activity.app.getThread());
6651 }
6652 }
6653
6654 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006655 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006656 @Nullable String featureId, int callingUid, int userId, IBinder token,
6657 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6658 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006659 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006660 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6661 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006662 }
6663 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006664
6665 @Override
6666 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6667 synchronized (mGlobalLock) {
6668 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6669 if (r == null) {
6670 return null;
6671 }
6672 if (r.mServiceConnectionsHolder == null) {
6673 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6674 ActivityTaskManagerService.this, r);
6675 }
6676
6677 return r.mServiceConnectionsHolder;
6678 }
6679 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006680
6681 @Override
6682 public Intent getHomeIntent() {
6683 synchronized (mGlobalLock) {
6684 return ActivityTaskManagerService.this.getHomeIntent();
6685 }
6686 }
6687
6688 @Override
6689 public boolean startHomeActivity(int userId, String reason) {
6690 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006691 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006692 }
6693 }
6694
6695 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006696 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006697 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006698 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006699 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006700 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006701 }
Chilun8b1f1be2019-03-13 17:14:36 +08006702 }
6703
6704 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006705 public boolean startHomeOnAllDisplays(int userId, String reason) {
6706 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006707 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006708 }
6709 }
6710
Riddle Hsua0536432019-02-16 00:38:59 +08006711 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006712 @Override
6713 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006714 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006715 if (mFactoryTest == FACTORY_TEST_OFF) {
6716 return false;
6717 }
6718 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6719 && wpc.mName.equals(mTopComponent.getPackageName())) {
6720 return true;
6721 }
6722 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6723 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6724 }
6725 }
6726
6727 @Override
6728 public void updateTopComponentForFactoryTest() {
6729 synchronized (mGlobalLock) {
6730 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6731 return;
6732 }
6733 final ResolveInfo ri = mContext.getPackageManager()
6734 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6735 final CharSequence errorMsg;
6736 if (ri != null) {
6737 final ActivityInfo ai = ri.activityInfo;
6738 final ApplicationInfo app = ai.applicationInfo;
6739 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6740 mTopAction = Intent.ACTION_FACTORY_TEST;
6741 mTopData = null;
6742 mTopComponent = new ComponentName(app.packageName, ai.name);
6743 errorMsg = null;
6744 } else {
6745 errorMsg = mContext.getResources().getText(
6746 com.android.internal.R.string.factorytest_not_system);
6747 }
6748 } else {
6749 errorMsg = mContext.getResources().getText(
6750 com.android.internal.R.string.factorytest_no_action);
6751 }
6752 if (errorMsg == null) {
6753 return;
6754 }
6755
6756 mTopAction = null;
6757 mTopData = null;
6758 mTopComponent = null;
6759 mUiHandler.post(() -> {
6760 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6761 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006762 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006763 });
6764 }
6765 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006766
Riddle Hsua0536432019-02-16 00:38:59 +08006767 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006768 @Override
6769 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6770 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006771 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006772 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006773 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006774
6775 wpc.clearRecentTasks();
6776 wpc.clearActivities();
6777
6778 if (wpc.isInstrumenting()) {
6779 finishInstrumentationCallback.run();
6780 }
6781
Jorim Jaggid0752812018-10-16 16:07:20 +02006782 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006783 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006784 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006785 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006786 // If there was nothing to resume, and we are not already restarting
6787 // this process, but there is a visible activity that is hosted by the
6788 // process...then make sure all visible activities are running, taking
6789 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006790 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006791 !PRESERVE_WINDOWS);
6792 }
6793 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006794 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006795 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006796 }
6797 }
6798 }
6799
6800 @Override
6801 public void closeSystemDialogs(String reason) {
6802 enforceNotIsolatedCaller("closeSystemDialogs");
6803
6804 final int pid = Binder.getCallingPid();
6805 final int uid = Binder.getCallingUid();
6806 final long origId = Binder.clearCallingIdentity();
6807 try {
6808 synchronized (mGlobalLock) {
6809 // Only allow this from foreground processes, so that background
6810 // applications can't abuse it to prevent system UI from being shown.
6811 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006812 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006813 if (!proc.isPerceptible()) {
6814 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6815 + " from background process " + proc);
6816 return;
6817 }
6818 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006819 mWindowManager.closeSystemDialogs(reason);
6820
Louis Chang149d5c82019-12-30 09:47:39 +08006821 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006822 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006823 // Call into AM outside the synchronized block.
6824 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006825 } finally {
6826 Binder.restoreCallingIdentity(origId);
6827 }
6828 }
6829
6830 @Override
6831 public void cleanupDisabledPackageComponents(
6832 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6833 synchronized (mGlobalLock) {
6834 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006835 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006836 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006837 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006838 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006839 }
6840
6841 // Clean-up disabled tasks
6842 getRecentTasks().cleanupDisabledPackageTasksLocked(
6843 packageName, disabledClasses, userId);
6844 }
6845 }
6846
6847 @Override
6848 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6849 int userId) {
6850 synchronized (mGlobalLock) {
6851
6852 boolean didSomething =
6853 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006854 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006855 null, doit, evenPersistent, userId);
6856 return didSomething;
6857 }
6858 }
6859
6860 @Override
6861 public void resumeTopActivities(boolean scheduleIdle) {
6862 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006863 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006864 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006865 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006866 }
6867 }
6868 }
6869
Riddle Hsua0536432019-02-16 00:38:59 +08006870 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006871 @Override
6872 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006873 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006874 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6875 }
6876 }
6877
Riddle Hsua0536432019-02-16 00:38:59 +08006878 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 @Override
6880 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006881 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006882 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6883 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6884 }
6885 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006886 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006887 } finally {
6888 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6889 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006890 }
6891 }
6892
6893 @Override
6894 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6895 try {
6896 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6897 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6898 }
6899 } catch (RemoteException ex) {
6900 throw new SecurityException("Fail to check is caller a privileged app", ex);
6901 }
6902
6903 synchronized (mGlobalLock) {
6904 final long ident = Binder.clearCallingIdentity();
6905 try {
6906 if (mAmInternal.shouldConfirmCredentials(userId)) {
6907 if (mKeyguardController.isKeyguardLocked()) {
6908 // Showing launcher to avoid user entering credential twice.
6909 startHomeActivity(currentUserId, "notifyLockedProfile");
6910 }
Louis Chang149d5c82019-12-30 09:47:39 +08006911 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006912 }
6913 } finally {
6914 Binder.restoreCallingIdentity(ident);
6915 }
6916 }
6917 }
6918
6919 @Override
6920 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6921 mAmInternal.enforceCallingPermission(
6922 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6923
6924 synchronized (mGlobalLock) {
6925 final long ident = Binder.clearCallingIdentity();
6926 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006927 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6928 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006929 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006930 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6931 UserHandle.CURRENT);
6932 } finally {
6933 Binder.restoreCallingIdentity(ident);
6934 }
6935 }
6936 }
6937
6938 @Override
6939 public void writeActivitiesToProto(ProtoOutputStream proto) {
6940 synchronized (mGlobalLock) {
6941 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006942 mRootWindowContainer.dumpDebug(
6943 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006944 }
6945 }
6946
6947 @Override
6948 public void saveANRState(String reason) {
6949 synchronized (mGlobalLock) {
6950 final StringWriter sw = new StringWriter();
6951 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6952 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6953 if (reason != null) {
6954 pw.println(" Reason: " + reason);
6955 }
6956 pw.println();
6957 getActivityStartController().dump(pw, " ", null);
6958 pw.println();
6959 pw.println("-------------------------------------------------------------------------------");
6960 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6961 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6962 "" /* header */);
6963 pw.println();
6964 pw.close();
6965
6966 mLastANRState = sw.toString();
6967 }
6968 }
6969
6970 @Override
6971 public void clearSavedANRState() {
6972 synchronized (mGlobalLock) {
6973 mLastANRState = null;
6974 }
6975 }
6976
6977 @Override
6978 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6979 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6980 synchronized (mGlobalLock) {
6981 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6982 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6983 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6984 dumpLastANRLocked(pw);
6985 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6986 dumpLastANRTracesLocked(pw);
6987 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6988 dumpActivityStarterLocked(pw, dumpPackage);
6989 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6990 dumpActivityContainersLocked(pw);
6991 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6992 if (getRecentTasks() != null) {
6993 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6994 }
6995 }
6996 }
6997 }
6998
6999 @Override
7000 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7001 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7002 int wakefulness) {
7003 synchronized (mGlobalLock) {
7004 if (mHomeProcess != null && (dumpPackage == null
7005 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7006 if (needSep) {
7007 pw.println();
7008 needSep = false;
7009 }
7010 pw.println(" mHomeProcess: " + mHomeProcess);
7011 }
7012 if (mPreviousProcess != null && (dumpPackage == null
7013 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7014 if (needSep) {
7015 pw.println();
7016 needSep = false;
7017 }
7018 pw.println(" mPreviousProcess: " + mPreviousProcess);
7019 }
7020 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7021 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7022 StringBuilder sb = new StringBuilder(128);
7023 sb.append(" mPreviousProcessVisibleTime: ");
7024 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7025 pw.println(sb);
7026 }
7027 if (mHeavyWeightProcess != null && (dumpPackage == null
7028 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7029 if (needSep) {
7030 pw.println();
7031 needSep = false;
7032 }
7033 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7034 }
7035 if (dumpPackage == null) {
7036 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007037 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007038 }
7039 if (dumpAll) {
7040 if (dumpPackage == null) {
7041 pw.println(" mConfigWillChange: "
7042 + getTopDisplayFocusedStack().mConfigWillChange);
7043 }
7044 if (mCompatModePackages.getPackages().size() > 0) {
7045 boolean printed = false;
7046 for (Map.Entry<String, Integer> entry
7047 : mCompatModePackages.getPackages().entrySet()) {
7048 String pkg = entry.getKey();
7049 int mode = entry.getValue();
7050 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7051 continue;
7052 }
7053 if (!printed) {
7054 pw.println(" mScreenCompatPackages:");
7055 printed = true;
7056 }
7057 pw.println(" " + pkg + ": " + mode);
7058 }
7059 }
7060 }
7061
7062 if (dumpPackage == null) {
7063 pw.println(" mWakefulness="
7064 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007065 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007066 if (mRunningVoice != null) {
7067 pw.println(" mRunningVoice=" + mRunningVoice);
7068 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7069 }
7070 pw.println(" mSleeping=" + mSleeping);
7071 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7072 pw.println(" mVrController=" + mVrController);
7073 }
7074 if (mCurAppTimeTracker != null) {
7075 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7076 }
7077 if (mAllowAppSwitchUids.size() > 0) {
7078 boolean printed = false;
7079 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7080 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7081 for (int j = 0; j < types.size(); j++) {
7082 if (dumpPackage == null ||
7083 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7084 if (needSep) {
7085 pw.println();
7086 needSep = false;
7087 }
7088 if (!printed) {
7089 pw.println(" mAllowAppSwitchUids:");
7090 printed = true;
7091 }
7092 pw.print(" User ");
7093 pw.print(mAllowAppSwitchUids.keyAt(i));
7094 pw.print(": Type ");
7095 pw.print(types.keyAt(j));
7096 pw.print(" = ");
7097 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7098 pw.println();
7099 }
7100 }
7101 }
7102 }
7103 if (dumpPackage == null) {
7104 if (mController != null) {
7105 pw.println(" mController=" + mController
7106 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7107 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007108 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7109 pw.println(" mLaunchingActivityWakeLock="
7110 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007111 }
7112
7113 return needSep;
7114 }
7115 }
7116
7117 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007118 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7119 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007120 synchronized (mGlobalLock) {
7121 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007122 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007123 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007124 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7125 if (mRunningVoice != null) {
7126 final long vrToken = proto.start(
7127 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7128 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7129 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007130 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007131 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7132 proto.end(vrToken);
7133 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007134 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007135 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007136 if (mController != null) {
7137 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007138 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7139 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007140 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7141 proto.end(token);
7142 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007143 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7144 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007145 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007146 }
7147
7148 if (mHomeProcess != null && (dumpPackage == null
7149 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007150 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007151 }
7152
7153 if (mPreviousProcess != null && (dumpPackage == null
7154 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007155 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007156 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7157 }
7158
7159 if (mHeavyWeightProcess != null && (dumpPackage == null
7160 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007161 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007162 }
7163
7164 for (Map.Entry<String, Integer> entry
7165 : mCompatModePackages.getPackages().entrySet()) {
7166 String pkg = entry.getKey();
7167 int mode = entry.getValue();
7168 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7169 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7170 proto.write(PACKAGE, pkg);
7171 proto.write(MODE, mode);
7172 proto.end(compatToken);
7173 }
7174 }
7175
7176 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007177 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007178 }
7179
7180 }
7181 }
7182
7183 @Override
7184 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7185 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7186 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007187 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7188 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007189 }
7190
7191 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007192 public void dumpForOom(PrintWriter pw) {
7193 synchronized (mGlobalLock) {
7194 pw.println(" mHomeProcess: " + mHomeProcess);
7195 pw.println(" mPreviousProcess: " + mPreviousProcess);
7196 if (mHeavyWeightProcess != null) {
7197 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7198 }
7199 }
7200 }
7201
7202 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007203 public boolean canGcNow() {
7204 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007205 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007206 }
7207 }
7208
Riddle Hsua0536432019-02-16 00:38:59 +08007209 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007210 @Override
7211 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007212 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007213 if (mRootWindowContainer == null) {
7214 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007215 // oomadj after AMS created.
7216 return null;
7217 }
Louis Chang149d5c82019-12-30 09:47:39 +08007218 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007219 return top != null ? top.app : null;
7220 }
7221 }
7222
Riddle Hsua0536432019-02-16 00:38:59 +08007223 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007224 @Override
7225 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007226 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007227 if (mRootWindowContainer != null) {
7228 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007229 }
7230 }
7231 }
7232
7233 @Override
7234 public void scheduleDestroyAllActivities(String reason) {
7235 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007236 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007237 }
7238 }
7239
7240 @Override
7241 public void removeUser(int userId) {
7242 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007243 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007244 }
7245 }
7246
7247 @Override
7248 public boolean switchUser(int userId, UserState userState) {
7249 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007250 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007251 }
7252 }
7253
7254 @Override
7255 public void onHandleAppCrash(WindowProcessController wpc) {
7256 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007257 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007258 }
7259 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007260
7261 @Override
7262 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7263 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007264 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007265 }
7266 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007267
Riddle Hsua0536432019-02-16 00:38:59 +08007268 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007269 @Override
7270 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007271 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007272 }
7273
Riddle Hsua0536432019-02-16 00:38:59 +08007274 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007275 @Override
7276 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007277 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007278 }
7279
Riddle Hsua0536432019-02-16 00:38:59 +08007280 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007281 @Override
7282 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007283 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007284 }
7285
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 onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007289 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007290 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007291
7292 @Override
7293 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007294 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007295 mPendingTempWhitelist.put(uid, tag);
7296 }
7297 }
7298
7299 @Override
7300 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007301 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007302 mPendingTempWhitelist.remove(uid);
7303 }
7304 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007305
7306 @Override
7307 public boolean handleAppCrashInActivityController(String processName, int pid,
7308 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7309 Runnable killCrashingAppCallback) {
7310 synchronized (mGlobalLock) {
7311 if (mController == null) {
7312 return false;
7313 }
7314
7315 try {
7316 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7317 stackTrace)) {
7318 killCrashingAppCallback.run();
7319 return true;
7320 }
7321 } catch (RemoteException e) {
7322 mController = null;
7323 Watchdog.getInstance().setActivityController(null);
7324 }
7325 return false;
7326 }
7327 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007328
7329 @Override
7330 public void removeRecentTasksByPackageName(String packageName, int userId) {
7331 synchronized (mGlobalLock) {
7332 mRecentTasks.removeTasksByPackageName(packageName, userId);
7333 }
7334 }
7335
7336 @Override
7337 public void cleanupRecentTasksForUser(int userId) {
7338 synchronized (mGlobalLock) {
7339 mRecentTasks.cleanupLocked(userId);
7340 }
7341 }
7342
7343 @Override
7344 public void loadRecentTasksForUser(int userId) {
7345 synchronized (mGlobalLock) {
7346 mRecentTasks.loadUserRecentsLocked(userId);
7347 }
7348 }
7349
7350 @Override
7351 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7352 synchronized (mGlobalLock) {
7353 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7354 }
7355 }
7356
7357 @Override
7358 public void flushRecentTasks() {
7359 mRecentTasks.flush();
7360 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007361
7362 @Override
7363 public WindowProcessController getHomeProcess() {
7364 synchronized (mGlobalLock) {
7365 return mHomeProcess;
7366 }
7367 }
7368
7369 @Override
7370 public WindowProcessController getPreviousProcess() {
7371 synchronized (mGlobalLock) {
7372 return mPreviousProcess;
7373 }
7374 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007375
7376 @Override
7377 public void clearLockedTasks(String reason) {
7378 synchronized (mGlobalLock) {
7379 getLockTaskController().clearLockedTasks(reason);
7380 }
7381 }
7382
7383 @Override
7384 public void updateUserConfiguration() {
7385 synchronized (mGlobalLock) {
7386 final Configuration configuration = new Configuration(getGlobalConfiguration());
7387 final int currentUserId = mAmInternal.getCurrentUserId();
7388 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7389 configuration, currentUserId, Settings.System.canWrite(mContext));
7390 updateConfigurationLocked(configuration, null /* starting */,
7391 false /* initLocale */, false /* persistent */, currentUserId,
7392 false /* deferResume */);
7393 }
7394 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007395
7396 @Override
7397 public boolean canShowErrorDialogs() {
7398 synchronized (mGlobalLock) {
7399 return mShowDialogs && !mSleeping && !mShuttingDown
7400 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7401 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7402 mAmInternal.getCurrentUserId())
7403 && !(UserManager.isDeviceInDemoMode(mContext)
7404 && mAmInternal.getCurrentUser().isDemo());
7405 }
7406 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007407
7408 @Override
7409 public void setProfileApp(String profileApp) {
7410 synchronized (mGlobalLock) {
7411 mProfileApp = profileApp;
7412 }
7413 }
7414
7415 @Override
7416 public void setProfileProc(WindowProcessController wpc) {
7417 synchronized (mGlobalLock) {
7418 mProfileProc = wpc;
7419 }
7420 }
7421
7422 @Override
7423 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7424 synchronized (mGlobalLock) {
7425 mProfilerInfo = profilerInfo;
7426 }
7427 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007428
7429 @Override
7430 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7431 synchronized (mGlobalLock) {
7432 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7433 }
7434 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007435
7436 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007437 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
Peter Kalauskas4dc04602020-02-12 18:49:03 -08007438 boolean isLowResolution) {
7439 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007440 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007441 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007442
7443 @Override
7444 public boolean isUidForeground(int uid) {
7445 synchronized (mGlobalLock) {
7446 return ActivityTaskManagerService.this.isUidForeground(uid);
7447 }
7448 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007449
7450 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007451 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007452 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007453 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007454 }
7455 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007456
7457 @Override
7458 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007459 // Translate package names into UIDs
7460 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007461 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007462 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7463 if (uid >= 0) {
7464 result.add(uid);
7465 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007466 }
7467 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007468 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007469 }
7470 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007471 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007472}