blob: d3ff912ea327a1d28ca34d1b0e6d38efc1a2cc58 [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
Riddle Hsu9c024d12020-03-09 16:10:07 +0800683 public void onChange(boolean selfChange, Iterable<Uri> uris, int flags,
684 @UserIdInt int userId) {
685 for (Uri uri : uris) {
686 if (mFontScaleUri.equals(uri)) {
687 updateFontScaleIfNeeded(userId);
688 } else if (mHideErrorDialogsUri.equals(uri)) {
689 synchronized (mGlobalLock) {
690 updateShouldShowDialogsLocked(getGlobalConfiguration());
691 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700692 }
693 }
694 }
695 }
696
Riddle Hsua0536432019-02-16 00:38:59 +0800697 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
698 @Target(ElementType.METHOD)
699 @Retention(RetentionPolicy.SOURCE)
700 @interface HotPath {
701 int NONE = 0;
702 int OOM_ADJUSTMENT = 1;
703 int LRU_UPDATE = 2;
704 int PROCESS_CHANGE = 3;
705 int caller() default NONE;
706 }
707
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800708 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
709 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900710 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800711 mAmInternal.updateOomAdj();
712 }
713 };
714
Charles Chen8d98dd22018-12-26 17:36:54 +0800715 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
716 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700717 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700718 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700719 mSystemThread = ActivityThread.currentActivityThread();
720 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700721 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800722 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700723 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700724 }
725
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700726 public void onSystemReady() {
727 synchronized (mGlobalLock) {
728 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
729 PackageManager.FEATURE_CANT_SAVE_STATE);
730 mAssistUtils = new AssistUtils(mContext);
731 mVrController.onSystemReady();
732 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700733 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700734 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700735 }
736
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700737 public void onInitPowerManagement() {
738 synchronized (mGlobalLock) {
739 mStackSupervisor.initPowerManagement();
740 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
741 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
742 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
743 mVoiceWakeLock.setReferenceCounted(false);
744 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700745 }
746
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700747 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700748 mFontScaleSettingObserver = new FontScaleSettingObserver();
749 }
750
Wale Ogunwale59507092018-10-29 09:00:30 -0700751 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700752 final boolean freeformWindowManagement =
753 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
754 || Settings.Global.getInt(
755 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
756
757 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
758 final boolean supportsPictureInPicture = supportsMultiWindow &&
759 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
760 final boolean supportsSplitScreenMultiWindow =
761 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
762 final boolean supportsMultiDisplay = mContext.getPackageManager()
763 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700764 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
765 final boolean forceResizable = Settings.Global.getInt(
766 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700767 final boolean sizeCompatFreeform = Settings.Global.getInt(
768 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700769
770 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900771 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700772
773 final Configuration configuration = new Configuration();
774 Settings.System.getConfiguration(resolver, configuration);
775 if (forceRtl) {
776 // This will take care of setting the correct layout direction flags
777 configuration.setLayoutDirection(configuration.locale);
778 }
779
780 synchronized (mGlobalLock) {
781 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700782 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700783 final boolean multiWindowFormEnabled = freeformWindowManagement
784 || supportsSplitScreenMultiWindow
785 || supportsPictureInPicture
786 || supportsMultiDisplay;
787 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
788 mSupportsMultiWindow = true;
789 mSupportsFreeformWindowManagement = freeformWindowManagement;
790 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
791 mSupportsPictureInPicture = supportsPictureInPicture;
792 mSupportsMultiDisplay = supportsMultiDisplay;
793 } else {
794 mSupportsMultiWindow = false;
795 mSupportsFreeformWindowManagement = false;
796 mSupportsSplitScreenMultiWindow = false;
797 mSupportsPictureInPicture = false;
798 mSupportsMultiDisplay = false;
799 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700800 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700801 // This happens before any activities are started, so we can change global configuration
802 // in-place.
803 updateConfigurationLocked(configuration, null, true);
804 final Configuration globalConfig = getGlobalConfiguration();
805 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
806
807 // Load resources only after the current configuration has been set.
808 final Resources res = mContext.getResources();
809 mThumbnailWidth = res.getDimensionPixelSize(
810 com.android.internal.R.dimen.thumbnail_width);
811 mThumbnailHeight = res.getDimensionPixelSize(
812 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700813 }
814 }
815
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800816 public WindowManagerGlobalLock getGlobalLock() {
817 return mGlobalLock;
818 }
819
Yunfan Chen585f2932019-01-29 16:04:45 +0900820 /** For test purpose only. */
821 @VisibleForTesting
822 public ActivityTaskManagerInternal getAtmInternal() {
823 return mInternal;
824 }
825
Riddle Hsud93a6c42018-11-29 21:50:06 +0800826 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
827 Looper looper) {
828 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700829 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700830 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700831 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800832 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700833 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700834 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700835 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700836
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700837 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700838 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700839 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700840 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700841 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700842 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700843 mKeyguardController = mStackSupervisor.getKeyguardController();
844 }
845
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700846 public void onActivityManagerInternalAdded() {
847 synchronized (mGlobalLock) {
848 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
849 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
850 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700851 }
852
Yunfan Chen75157d72018-07-27 14:47:21 +0900853 int increaseConfigurationSeqLocked() {
854 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
855 return mConfigurationSeq;
856 }
857
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700858 protected ActivityStackSupervisor createStackSupervisor() {
859 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
860 supervisor.initialize();
861 return supervisor;
862 }
863
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800864 protected AppWarnings createAppWarnings(
865 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
866 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
867 }
868
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700869 public void setWindowManager(WindowManagerService wm) {
870 synchronized (mGlobalLock) {
871 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800872 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800873 mTempConfig.setToDefaults();
874 mTempConfig.setLocales(LocaleList.getDefault());
875 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800876 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700877 mLockTaskController.setWindowManager(wm);
878 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800879 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700880 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700881 }
882
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700883 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
884 synchronized (mGlobalLock) {
885 mUsageStatsInternal = usageStatsManager;
886 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700887 }
888
Wale Ogunwalef6733932018-06-27 05:14:34 -0700889 UserManagerService getUserManager() {
890 if (mUserManager == null) {
891 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
892 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
893 }
894 return mUserManager;
895 }
896
Philip P. Moltmannee295092020-02-10 08:46:26 -0800897 AppOpsManager getAppOpsManager() {
898 if (mAppOpsManager == null) {
899 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Wale Ogunwalef6733932018-06-27 05:14:34 -0700900 }
Philip P. Moltmannee295092020-02-10 08:46:26 -0800901 return mAppOpsManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700902 }
903
904 boolean hasUserRestriction(String restriction, int userId) {
905 return getUserManager().hasUserRestriction(restriction, userId);
906 }
907
Michal Karpinski15486842019-04-25 17:33:42 +0100908 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
Philip P. Moltmannee295092020-02-10 08:46:26 -0800909 final int mode = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
910 callingUid, callingPackage, /* featureId */ null, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100911 if (mode == AppOpsManager.MODE_DEFAULT) {
912 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
913 == PERMISSION_GRANTED;
914 }
915 return mode == AppOpsManager.MODE_ALLOWED;
916 }
917
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700918 @VisibleForTesting
919 protected void setRecentTasks(RecentTasks recentTasks) {
920 mRecentTasks = recentTasks;
921 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700922 }
923
924 RecentTasks getRecentTasks() {
925 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700926 }
927
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700928 ClientLifecycleManager getLifecycleManager() {
929 return mLifecycleManager;
930 }
931
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700932 ActivityStartController getActivityStartController() {
933 return mActivityStartController;
934 }
935
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700936 TaskChangeNotificationController getTaskChangeNotificationController() {
937 return mTaskChangeNotificationController;
938 }
939
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700940 LockTaskController getLockTaskController() {
941 return mLockTaskController;
942 }
943
Yunfan Chen75157d72018-07-27 14:47:21 +0900944 /**
945 * Return the global configuration used by the process corresponding to the input pid. This is
946 * usually the global configuration with some overrides specific to that process.
947 */
948 Configuration getGlobalConfigurationForCallingPid() {
949 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800950 return getGlobalConfigurationForPid(pid);
951 }
952
953 /**
954 * Return the global configuration used by the process corresponding to the given pid.
955 */
956 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900957 if (pid == MY_PID || pid < 0) {
958 return getGlobalConfiguration();
959 }
960 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100961 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900962 return app != null ? app.getConfiguration() : getGlobalConfiguration();
963 }
964 }
965
966 /**
967 * Return the device configuration info used by the process corresponding to the input pid.
968 * The value is consistent with the global configuration for the process.
969 */
970 @Override
971 public ConfigurationInfo getDeviceConfigurationInfo() {
972 ConfigurationInfo config = new ConfigurationInfo();
973 synchronized (mGlobalLock) {
974 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
975 config.reqTouchScreen = globalConfig.touchscreen;
976 config.reqKeyboardType = globalConfig.keyboard;
977 config.reqNavigation = globalConfig.navigation;
978 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
979 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
980 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
981 }
982 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
983 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
984 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
985 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700986 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900987 }
988 return config;
989 }
990
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700991 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700992 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700993 }
994
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700995 public static final class Lifecycle extends SystemService {
996 private final ActivityTaskManagerService mService;
997
998 public Lifecycle(Context context) {
999 super(context);
1000 mService = new ActivityTaskManagerService(context);
1001 }
1002
1003 @Override
1004 public void onStart() {
1005 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001006 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001007 }
1008
Garfield Tan891146c2018-10-09 12:14:00 -07001009 @Override
1010 public void onUnlockUser(int userId) {
1011 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001012 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001013 }
1014 }
1015
1016 @Override
1017 public void onCleanupUser(int userId) {
1018 synchronized (mService.getGlobalLock()) {
1019 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1020 }
1021 }
1022
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001023 public ActivityTaskManagerService getService() {
1024 return mService;
1025 }
1026 }
1027
1028 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001029 public final int startActivity(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001030 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1031 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1032 Bundle bOptions) {
1033 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1034 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001035 UserHandle.getCallingUserId());
1036 }
1037
1038 @Override
1039 public final int startActivities(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001040 String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
1041 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001042 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001044 enforceNotIsolatedCaller(reason);
1045 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001046 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001047 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001048 callingFeatureId, intents, resolvedTypes, resultTo,
1049 SafeActivityOptions.fromBundle(bOptions), userId, reason,
1050 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001051 }
1052
1053 @Override
1054 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001055 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1056 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1057 Bundle bOptions, int userId) {
1058 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1059 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060 true /*validateIncomingUser*/);
1061 }
1062
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001063 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001064 @Nullable String callingFeatureId, Intent intent, String resolvedType,
1065 IBinder resultTo, String resultWho, int requestCode, int startFlags,
1066 ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001067 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001068 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001069
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001070 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001071 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1072
1073 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001074 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001075 .setCaller(caller)
1076 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001077 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001078 .setResolvedType(resolvedType)
1079 .setResultTo(resultTo)
1080 .setResultWho(resultWho)
1081 .setRequestCode(requestCode)
1082 .setStartFlags(startFlags)
1083 .setProfilerInfo(profilerInfo)
1084 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001085 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001086 .execute();
1087
1088 }
1089
1090 @Override
1091 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1092 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001093 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1094 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001095 // Refuse possible leaked file descriptors
1096 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1097 throw new IllegalArgumentException("File descriptors passed in Intent");
1098 }
1099
1100 if (!(target instanceof PendingIntentRecord)) {
1101 throw new IllegalArgumentException("Bad PendingIntent object");
1102 }
1103
1104 PendingIntentRecord pir = (PendingIntentRecord)target;
1105
1106 synchronized (mGlobalLock) {
1107 // If this is coming from the currently resumed activity, it is
1108 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001109 final ActivityStack stack = getTopDisplayFocusedStack();
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001110 if (stack != null && stack.mResumedActivity != null
1111 && stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001112 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001113 }
1114 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001115 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001116 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001117 }
1118
1119 @Override
1120 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1121 Bundle bOptions) {
1122 // Refuse possible leaked file descriptors
1123 if (intent != null && intent.hasFileDescriptors()) {
1124 throw new IllegalArgumentException("File descriptors passed in Intent");
1125 }
1126 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1127
1128 synchronized (mGlobalLock) {
1129 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1130 if (r == null) {
1131 SafeActivityOptions.abort(options);
1132 return false;
1133 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001134 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001135 // The caller is not running... d'oh!
1136 SafeActivityOptions.abort(options);
1137 return false;
1138 }
1139 intent = new Intent(intent);
1140 // The caller is not allowed to change the data.
1141 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1142 // And we are resetting to find the next component...
1143 intent.setComponent(null);
1144
1145 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1146
1147 ActivityInfo aInfo = null;
1148 try {
1149 List<ResolveInfo> resolves =
1150 AppGlobals.getPackageManager().queryIntentActivities(
1151 intent, r.resolvedType,
1152 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1153 UserHandle.getCallingUserId()).getList();
1154
1155 // Look for the original activity in the list...
1156 final int N = resolves != null ? resolves.size() : 0;
1157 for (int i=0; i<N; i++) {
1158 ResolveInfo rInfo = resolves.get(i);
1159 if (rInfo.activityInfo.packageName.equals(r.packageName)
1160 && rInfo.activityInfo.name.equals(r.info.name)) {
1161 // We found the current one... the next matching is
1162 // after it.
1163 i++;
1164 if (i<N) {
1165 aInfo = resolves.get(i).activityInfo;
1166 }
1167 if (debug) {
1168 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1169 + "/" + r.info.name);
1170 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1171 ? "null" : aInfo.packageName + "/" + aInfo.name));
1172 }
1173 break;
1174 }
1175 }
1176 } catch (RemoteException e) {
1177 }
1178
1179 if (aInfo == null) {
1180 // Nobody who is next!
1181 SafeActivityOptions.abort(options);
1182 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1183 return false;
1184 }
1185
1186 intent.setComponent(new ComponentName(
1187 aInfo.applicationInfo.packageName, aInfo.name));
1188 intent.setFlags(intent.getFlags()&~(
1189 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1190 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1191 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1192 FLAG_ACTIVITY_NEW_TASK));
1193
1194 // Okay now we need to start the new activity, replacing the currently running activity.
1195 // This is a little tricky because we want to start the new one as if the current one is
1196 // finished, but not finish the current one first so that there is no flicker.
1197 // And thus...
1198 final boolean wasFinishing = r.finishing;
1199 r.finishing = true;
1200
1201 // Propagate reply information over to the new activity.
1202 final ActivityRecord resultTo = r.resultTo;
1203 final String resultWho = r.resultWho;
1204 final int requestCode = r.requestCode;
1205 r.resultTo = null;
1206 if (resultTo != null) {
1207 resultTo.removeResultsLocked(r, resultWho, requestCode);
1208 }
1209
1210 final long origId = Binder.clearCallingIdentity();
1211 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001212 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001213 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001214 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001215 .setResolvedType(r.resolvedType)
1216 .setActivityInfo(aInfo)
1217 .setResultTo(resultTo != null ? resultTo.appToken : null)
1218 .setResultWho(resultWho)
1219 .setRequestCode(requestCode)
1220 .setCallingPid(-1)
1221 .setCallingUid(r.launchedFromUid)
1222 .setCallingPackage(r.launchedFromPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001223 .setCallingFeatureId(r.launchedFromFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001224 .setRealCallingPid(-1)
1225 .setRealCallingUid(r.launchedFromUid)
1226 .setActivityOptions(options)
1227 .execute();
1228 Binder.restoreCallingIdentity(origId);
1229
1230 r.finishing = wasFinishing;
1231 if (res != ActivityManager.START_SUCCESS) {
1232 return false;
1233 }
1234 return true;
1235 }
1236 }
1237
1238 @Override
Galia Peycheva6861e912019-08-21 10:20:23 +02001239 public boolean startDreamActivity(Intent intent) {
Galia Peycheva52e89222020-02-18 23:41:43 +01001240 final WindowProcessController process = mProcessMap.getProcess(Binder.getCallingPid());
1241 final long origId = Binder.clearCallingIdentity();
1242
1243 // The dream activity is only called for non-doze dreams.
1244 final ComponentName currentDream = LocalServices.getService(DreamManagerInternal.class)
1245 .getActiveDreamComponent(/* doze= */ false);
1246
1247 if (currentDream == null || currentDream.getPackageName() == null
1248 || !currentDream.getPackageName().equals(process.mInfo.packageName)) {
1249 Slog.e(TAG, "Calling package is not the current dream package. "
1250 + "Aborting startDreamActivity...");
1251 return false;
1252 }
1253
Galia Peycheva6861e912019-08-21 10:20:23 +02001254 final ActivityInfo a = new ActivityInfo();
1255 a.theme = com.android.internal.R.style.Theme_Dream;
1256 a.exported = true;
1257 a.name = DreamActivity.class.getName();
1258
Galia Peycheva6861e912019-08-21 10:20:23 +02001259
1260 a.packageName = process.mInfo.packageName;
1261 a.applicationInfo = process.mInfo;
1262 a.processName = process.mInfo.processName;
1263 a.uiOptions = process.mInfo.uiOptions;
1264 a.taskAffinity = "android:" + a.packageName + "/dream";
1265 a.enabled = true;
1266 a.launchMode = ActivityInfo.LAUNCH_SINGLE_INSTANCE;
1267
1268 a.persistableMode = ActivityInfo.PERSIST_NEVER;
1269 a.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1270 a.colorMode = ActivityInfo.COLOR_MODE_DEFAULT;
1271 a.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1272
Galia Peycheva6861e912019-08-21 10:20:23 +02001273 try {
1274 getActivityStartController().obtainStarter(intent, "dream")
1275 .setActivityInfo(a)
1276 .setIsDream(true)
1277 .execute();
1278 return true;
1279 } finally {
1280 Binder.restoreCallingIdentity(origId);
1281 }
1282 }
1283
1284 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001285 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001286 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1287 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1288 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001289 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001290 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001291 enforceNotIsolatedCaller("startActivityAndWait");
1292 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1293 userId, "startActivityAndWait");
1294 // TODO: Switch to user app stacks here.
1295 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1296 .setCaller(caller)
1297 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001298 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001299 .setResolvedType(resolvedType)
1300 .setResultTo(resultTo)
1301 .setResultWho(resultWho)
1302 .setRequestCode(requestCode)
1303 .setStartFlags(startFlags)
1304 .setActivityOptions(bOptions)
1305 .setUserId(userId)
1306 .setProfilerInfo(profilerInfo)
1307 .setWaitResult(res)
1308 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001309 return res;
1310 }
1311
1312 @Override
1313 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001314 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1315 String resultWho, int requestCode, int startFlags, Configuration config,
1316 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001317 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001318 enforceNotIsolatedCaller("startActivityWithConfig");
1319 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1320 "startActivityWithConfig");
1321 // TODO: Switch to user app stacks here.
1322 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1323 .setCaller(caller)
1324 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001325 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001326 .setResolvedType(resolvedType)
1327 .setResultTo(resultTo)
1328 .setResultWho(resultWho)
1329 .setRequestCode(requestCode)
1330 .setStartFlags(startFlags)
1331 .setGlobalConfiguration(config)
1332 .setActivityOptions(bOptions)
1333 .setUserId(userId)
1334 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001335 }
1336
Robert Carr8a2f9132019-11-11 15:03:15 -08001337 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001338 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1339 int callingUid = Binder.getCallingUid();
1340 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1341 throw new SecurityException("Only the system process can request a permission token, "
1342 + "received request from uid: " + callingUid);
1343 }
1344 IBinder permissionToken = new Binder();
1345 synchronized (mGlobalLock) {
1346 mStartActivitySources.put(permissionToken, delegatorToken);
1347 }
1348
1349 Message expireMsg = PooledLambda.obtainMessage(
1350 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1351 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1352
1353 Message forgetMsg = PooledLambda.obtainMessage(
1354 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1355 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1356
1357 return permissionToken;
1358 }
1359
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001360 @Override
1361 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1362 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001363 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1364 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001365 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001366 // permission grants) as any app that may launch one of your own activities. So we only
1367 // allow this in two cases:
1368 // 1) The caller is an activity that is part of the core framework, and then only when it
1369 // is running as the system.
1370 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1371 // can only be requested by a system activity, which may then delegate this call to
1372 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001373 final ActivityRecord sourceRecord;
1374 final int targetUid;
1375 final String targetPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001376 final String targetFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377 final boolean isResolver;
1378 synchronized (mGlobalLock) {
1379 if (resultTo == null) {
1380 throw new SecurityException("Must be called from an activity");
1381 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001382 final IBinder sourceToken;
1383 if (permissionToken != null) {
1384 // To even attempt to use a permissionToken, an app must also have this signature
1385 // permission.
1386 mAmInternal.enforceCallingPermission(
1387 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1388 "startActivityAsCaller");
1389 // If called with a permissionToken, we want the sourceRecord from the delegator
1390 // activity that requested this token.
1391 sourceToken = mStartActivitySources.remove(permissionToken);
1392 if (sourceToken == null) {
1393 // Invalid permissionToken, check if it recently expired.
1394 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1395 throw new SecurityException("Called with expired permission token: "
1396 + permissionToken);
1397 } else {
1398 throw new SecurityException("Called with invalid permission token: "
1399 + permissionToken);
1400 }
1401 }
1402 } else {
1403 // This method was called directly by the source.
1404 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001405 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001406
Louis Chang149d5c82019-12-30 09:47:39 +08001407 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001408 if (sourceRecord == null) {
1409 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001410 }
1411 if (sourceRecord.app == null) {
1412 throw new SecurityException("Called without a process attached to activity");
1413 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001414
1415 // Whether called directly or from a delegate, the source activity must be from the
1416 // android package.
1417 if (!sourceRecord.info.packageName.equals("android")) {
1418 throw new SecurityException("Must be called from an activity that is "
1419 + "declared in the android package");
1420 }
1421
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001422 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001423 // This is still okay, as long as this activity is running under the
1424 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001425 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001426 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001427 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001428 + " must be system uid or original calling uid "
1429 + sourceRecord.launchedFromUid);
1430 }
1431 }
1432 if (ignoreTargetSecurity) {
1433 if (intent.getComponent() == null) {
1434 throw new SecurityException(
1435 "Component must be specified with ignoreTargetSecurity");
1436 }
1437 if (intent.getSelector() != null) {
1438 throw new SecurityException(
1439 "Selector not allowed with ignoreTargetSecurity");
1440 }
1441 }
1442 targetUid = sourceRecord.launchedFromUid;
1443 targetPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001444 targetFeatureId = sourceRecord.launchedFromFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001445 isResolver = sourceRecord.isResolverOrChildActivity();
1446 }
1447
1448 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001449 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001450 }
1451
1452 // TODO: Switch to user app stacks here.
1453 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001454 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455 .setCallingUid(targetUid)
1456 .setCallingPackage(targetPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001457 .setCallingFeatureId(targetFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458 .setResolvedType(resolvedType)
1459 .setResultTo(resultTo)
1460 .setResultWho(resultWho)
1461 .setRequestCode(requestCode)
1462 .setStartFlags(startFlags)
1463 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001464 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1466 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001467 // The target may well be in the background, which would normally prevent it
1468 // from starting an activity. Here we definitely want the start to succeed.
1469 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001470 .execute();
1471 } catch (SecurityException e) {
1472 // XXX need to figure out how to propagate to original app.
1473 // A SecurityException here is generally actually a fault of the original
1474 // calling activity (such as a fairly granting permissions), so propagate it
1475 // back to them.
1476 /*
1477 StringBuilder msg = new StringBuilder();
1478 msg.append("While launching");
1479 msg.append(intent.toString());
1480 msg.append(": ");
1481 msg.append(e.getMessage());
1482 */
1483 throw e;
1484 }
1485 }
1486
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001487 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1488 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001489 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001490 }
1491
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001492 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001493 public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1494 int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001495 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1496 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001497 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001498 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001499 if (session == null || interactor == null) {
1500 throw new NullPointerException("null session or interactor");
1501 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001502 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001503 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001504 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001505 .setCallingUid(callingUid)
1506 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001507 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001508 .setResolvedType(resolvedType)
1509 .setVoiceSession(session)
1510 .setVoiceInteractor(interactor)
1511 .setStartFlags(startFlags)
1512 .setProfilerInfo(profilerInfo)
1513 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001514 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001515 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001516 .execute();
1517 }
1518
1519 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001520 public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1521 int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1522 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001523 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001524 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1525 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001526
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001527 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001528 .setCallingUid(callingUid)
1529 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001530 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001531 .setResolvedType(resolvedType)
1532 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001533 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001534 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001535 .execute();
1536 }
1537
Riddle Hsu609a8e22019-06-27 16:46:29 -06001538 /**
1539 * Start the recents activity to perform the recents animation.
1540 *
1541 * @param intent The intent to start the recents activity.
1542 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1543 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001544 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001545 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1546 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001547 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001548 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001549 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001550 final long origId = Binder.clearCallingIdentity();
1551 try {
1552 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001553 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
Philip P. Moltmannee295092020-02-10 08:46:26 -08001554 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001555 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001556 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001557
1558 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001559 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001560 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001561 recentsFeatureId, recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001562 if (recentsAnimationRunner == null) {
1563 anim.preloadRecentsActivity();
1564 } else {
1565 anim.startRecentsActivity(recentsAnimationRunner);
1566 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001567 }
1568 } finally {
1569 Binder.restoreCallingIdentity(origId);
1570 }
1571 }
1572
1573 @Override
1574 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001575 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001576 "startActivityFromRecents()");
1577
1578 final int callingPid = Binder.getCallingPid();
1579 final int callingUid = Binder.getCallingUid();
1580 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1581 final long origId = Binder.clearCallingIdentity();
1582 try {
1583 synchronized (mGlobalLock) {
1584 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1585 safeOptions);
1586 }
1587 } finally {
1588 Binder.restoreCallingIdentity(origId);
1589 }
1590 }
1591
1592 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001593 * Public API to check if the client is allowed to start an activity on specified display.
1594 *
1595 * If the target display is private or virtual, some restrictions will apply.
1596 *
1597 * @param displayId Target display id.
1598 * @param intent Intent used to launch the activity.
1599 * @param resolvedType The MIME type of the intent.
1600 * @param userId The id of the user for whom the call is made.
1601 * @return {@code true} if a call to start an activity on the target display should succeed and
1602 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1603 */
1604 @Override
1605 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1606 String resolvedType, int userId) {
1607 final int callingUid = Binder.getCallingUid();
1608 final int callingPid = Binder.getCallingPid();
1609 final long origId = Binder.clearCallingIdentity();
1610
1611 try {
1612 // Collect information about the target of the Intent.
1613 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1614 0 /* startFlags */, null /* profilerInfo */, userId,
1615 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1616 UserHandle.USER_NULL));
1617 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1618
1619 synchronized (mGlobalLock) {
1620 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1621 aInfo);
1622 }
1623 } finally {
1624 Binder.restoreCallingIdentity(origId);
1625 }
1626 }
1627
1628 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001629 * This is the internal entry point for handling Activity.finish().
1630 *
1631 * @param token The Binder token referencing the Activity we want to finish.
1632 * @param resultCode Result code, if any, from this Activity.
1633 * @param resultData Result data (Intent), if any, from this Activity.
1634 * @param finishTask Whether to finish the task associated with this Activity.
1635 *
1636 * @return Returns true if the activity successfully finished, or false if it is still running.
1637 */
1638 @Override
1639 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1640 int finishTask) {
1641 // Refuse possible leaked file descriptors
1642 if (resultData != null && resultData.hasFileDescriptors()) {
1643 throw new IllegalArgumentException("File descriptors passed in Intent");
1644 }
1645
1646 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001647 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001648 if (r == null) {
1649 return true;
1650 }
1651 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001652 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001653 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001654 if (rootR == null) {
1655 Slog.w(TAG, "Finishing task with all activities already finished");
1656 }
1657 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1658 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001659 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001660 return false;
1661 }
1662
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001663 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1664 // We should consolidate.
1665 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001666 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001667 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001668 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001669 if (next != null) {
1670 // ask watcher if this is allowed
1671 boolean resumeOK = true;
1672 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001673 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001674 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001675 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001676 Watchdog.getInstance().setActivityController(null);
1677 }
1678
1679 if (!resumeOK) {
1680 Slog.i(TAG, "Not finishing activity because controller resumed");
1681 return false;
1682 }
1683 }
1684 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001685
1686 // note down that the process has finished an activity and is in background activity
1687 // starts grace period
1688 if (r.app != null) {
1689 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1690 }
1691
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001692 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001693 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001694 try {
1695 boolean res;
1696 final boolean finishWithRootActivity =
1697 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1698 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1699 || (finishWithRootActivity && r == rootR)) {
1700 // If requested, remove the task that is associated to this activity only if it
1701 // was the root activity in the task. The result code and data is ignored
1702 // because we don't support returning them across task boundaries. Also, to
1703 // keep backwards compatibility we remove the task from recents when finishing
1704 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001705 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001706 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001707 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001708 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001709 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001710 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001711 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001712 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001713 if (!res) {
1714 Slog.i(TAG, "Failed to finish by app-request");
1715 }
1716 }
1717 return res;
1718 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001719 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001720 Binder.restoreCallingIdentity(origId);
1721 }
1722 }
1723 }
1724
1725 @Override
1726 public boolean finishActivityAffinity(IBinder token) {
1727 synchronized (mGlobalLock) {
1728 final long origId = Binder.clearCallingIdentity();
1729 try {
1730 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1731 if (r == null) {
1732 return false;
1733 }
1734
1735 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1736 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001737 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001738 return false;
1739 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001740
1741 final PooledFunction p = PooledLambda.obtainFunction(
1742 ActivityRecord::finishIfSameAffinity, r,
1743 PooledLambda.__(ActivityRecord.class));
1744 r.getTask().forAllActivities(
1745 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1746 p.recycle();
1747
Andrii Kuliande93eff2019-07-12 12:21:27 -07001748 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001749 } finally {
1750 Binder.restoreCallingIdentity(origId);
1751 }
1752 }
1753 }
1754
1755 @Override
1756 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1757 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001758 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001759 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001760 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001761 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1762 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001763 return;
1764 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001765 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1766 false /* processPausingActivities */, config);
1767 if (stopProfiling && r.hasProcess()) {
1768 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001769 }
1770 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001771 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001772 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001773 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001774 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001775 }
1776
1777 @Override
1778 public final void activityResumed(IBinder token) {
1779 final long origId = Binder.clearCallingIdentity();
1780 synchronized (mGlobalLock) {
1781 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001782 }
1783 Binder.restoreCallingIdentity(origId);
1784 }
1785
1786 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001787 public final void activityTopResumedStateLost() {
1788 final long origId = Binder.clearCallingIdentity();
1789 synchronized (mGlobalLock) {
1790 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1791 }
1792 Binder.restoreCallingIdentity(origId);
1793 }
1794
1795 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001796 public final void activityPaused(IBinder token) {
1797 final long origId = Binder.clearCallingIdentity();
1798 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001799 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001800 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1801 if (r != null) {
1802 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001803 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001804 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001805 }
1806 Binder.restoreCallingIdentity(origId);
1807 }
1808
1809 @Override
1810 public final void activityStopped(IBinder token, Bundle icicle,
1811 PersistableBundle persistentState, CharSequence description) {
1812 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1813
1814 // Refuse possible leaked file descriptors
1815 if (icicle != null && icicle.hasFileDescriptors()) {
1816 throw new IllegalArgumentException("File descriptors passed in Bundle");
1817 }
1818
1819 final long origId = Binder.clearCallingIdentity();
1820
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001821 String restartingName = null;
1822 int restartingUid = 0;
1823 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001824 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001825 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001826 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001827 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001828 if (r.attachedToProcess()
1829 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1830 // The activity was requested to restart from
1831 // {@link #restartActivityProcessIfVisible}.
1832 restartingName = r.app.mName;
1833 restartingUid = r.app.mUid;
1834 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001835 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001836 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001837 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001838 }
1839
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001840 if (restartingName != null) {
1841 // In order to let the foreground activity can be restarted with its saved state from
1842 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1843 // until the activity reports stopped with the state. And the activity record will be
1844 // kept because the record state is restarting, then the activity will be restarted
1845 // immediately if it is still the top one.
1846 mStackSupervisor.removeRestartTimeouts(r);
1847 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1848 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001849 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001850
1851 Binder.restoreCallingIdentity(origId);
1852 }
1853
1854 @Override
1855 public final void activityDestroyed(IBinder token) {
1856 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1857 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001858 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001859 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001860 try {
1861 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1862 if (activity != null) {
1863 activity.destroyed("activityDestroyed");
1864 }
1865 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001866 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001867 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001868 }
1869 }
1870 }
1871
1872 @Override
1873 public final void activityRelaunched(IBinder token) {
1874 final long origId = Binder.clearCallingIdentity();
1875 synchronized (mGlobalLock) {
1876 mStackSupervisor.activityRelaunchedLocked(token);
1877 }
1878 Binder.restoreCallingIdentity(origId);
1879 }
1880
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001881 @Override
1882 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1883 synchronized (mGlobalLock) {
1884 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1885 if (r == null) {
1886 return;
1887 }
1888 final long origId = Binder.clearCallingIdentity();
1889 try {
1890 r.setRequestedOrientation(requestedOrientation);
1891 } finally {
1892 Binder.restoreCallingIdentity(origId);
1893 }
1894 }
1895 }
1896
1897 @Override
1898 public int getRequestedOrientation(IBinder token) {
1899 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001900 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1901 return (r != null)
1902 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001903 }
1904 }
1905
1906 @Override
1907 public void setImmersive(IBinder token, boolean immersive) {
1908 synchronized (mGlobalLock) {
1909 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1910 if (r == null) {
1911 throw new IllegalArgumentException();
1912 }
1913 r.immersive = immersive;
1914
1915 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001916 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001917 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001918 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001919 }
1920 }
1921 }
1922
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001923 void applyUpdateLockStateLocked(ActivityRecord r) {
1924 // Modifications to the UpdateLock state are done on our handler, outside
1925 // the activity manager's locks. The new state is determined based on the
1926 // state *now* of the relevant activity record. The object is passed to
1927 // the handler solely for logging detail, not to be consulted/modified.
1928 final boolean nextState = r != null && r.immersive;
1929 mH.post(() -> {
1930 if (mUpdateLock.isHeld() != nextState) {
1931 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1932 "Applying new update lock state '" + nextState + "' for " + r);
1933 if (nextState) {
1934 mUpdateLock.acquire();
1935 } else {
1936 mUpdateLock.release();
1937 }
1938 }
1939 });
1940 }
1941
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001942 @Override
1943 public boolean isImmersive(IBinder token) {
1944 synchronized (mGlobalLock) {
1945 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1946 if (r == null) {
1947 throw new IllegalArgumentException();
1948 }
1949 return r.immersive;
1950 }
1951 }
1952
1953 @Override
1954 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001955 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001956 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001957 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
1958 if (topFocusedStack == null) {
1959 return false;
1960 }
1961
1962 final ActivityRecord r = topFocusedStack.topRunningActivity();
1963 return r != null && r.immersive;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001964 }
1965 }
1966
1967 @Override
1968 public void overridePendingTransition(IBinder token, String packageName,
1969 int enterAnim, int exitAnim) {
1970 synchronized (mGlobalLock) {
1971 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1972 if (self == null) {
1973 return;
1974 }
1975
1976 final long origId = Binder.clearCallingIdentity();
1977
1978 if (self.isState(
1979 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001980 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001981 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001982 }
1983
1984 Binder.restoreCallingIdentity(origId);
1985 }
1986 }
1987
1988 @Override
1989 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001990 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001991 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001992 final ActivityStack stack = getTopDisplayFocusedStack();
1993 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001994 if (r == null) {
1995 return ActivityManager.COMPAT_MODE_UNKNOWN;
1996 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001997 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001998 }
1999 }
2000
2001 @Override
2002 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002003 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002004 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002005 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002006 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002007 final ActivityStack stack = getTopDisplayFocusedStack();
2008 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002009 if (r == null) {
2010 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
2011 return;
2012 }
2013 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07002014 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002015 }
2016 }
2017
2018 @Override
2019 public int getLaunchedFromUid(IBinder activityToken) {
2020 ActivityRecord srec;
2021 synchronized (mGlobalLock) {
2022 srec = ActivityRecord.forTokenLocked(activityToken);
2023 }
2024 if (srec == null) {
2025 return -1;
2026 }
2027 return srec.launchedFromUid;
2028 }
2029
2030 @Override
2031 public String getLaunchedFromPackage(IBinder activityToken) {
2032 ActivityRecord srec;
2033 synchronized (mGlobalLock) {
2034 srec = ActivityRecord.forTokenLocked(activityToken);
2035 }
2036 if (srec == null) {
2037 return null;
2038 }
2039 return srec.launchedFromPackage;
2040 }
2041
2042 @Override
2043 public boolean convertFromTranslucent(IBinder token) {
2044 final long origId = Binder.clearCallingIdentity();
2045 try {
2046 synchronized (mGlobalLock) {
2047 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2048 if (r == null) {
2049 return false;
2050 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002051 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002052 }
2053 } finally {
2054 Binder.restoreCallingIdentity(origId);
2055 }
2056 }
2057
2058 @Override
2059 public boolean convertToTranslucent(IBinder token, Bundle options) {
2060 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2061 final long origId = Binder.clearCallingIdentity();
2062 try {
2063 synchronized (mGlobalLock) {
2064 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2065 if (r == null) {
2066 return false;
2067 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002068 final ActivityRecord under = r.getTask().getActivityBelow(r);
2069 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002070 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2071 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002072 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 }
2074 } finally {
2075 Binder.restoreCallingIdentity(origId);
2076 }
2077 }
2078
2079 @Override
2080 public void notifyActivityDrawn(IBinder token) {
2081 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2082 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002083 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002084 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002085 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002086 }
2087 }
2088 }
2089
2090 @Override
2091 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2092 synchronized (mGlobalLock) {
2093 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2094 if (r == null) {
2095 return;
2096 }
2097 r.reportFullyDrawnLocked(restoredFromBundle);
2098 }
2099 }
2100
2101 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002102 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002103 synchronized (mGlobalLock) {
2104 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002105 if (stack != null) {
2106 final int displayId = stack.getDisplayId();
2107 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002108 }
2109 return DEFAULT_DISPLAY;
2110 }
2111 }
2112
2113 @Override
2114 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002115 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002116 long ident = Binder.clearCallingIdentity();
2117 try {
2118 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002119 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002120 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002121 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002122 }
2123 return null;
2124 }
2125 } finally {
2126 Binder.restoreCallingIdentity(ident);
2127 }
2128 }
2129
2130 @Override
2131 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002132 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002133 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2134 final long callingId = Binder.clearCallingIdentity();
2135 try {
2136 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002137 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002138 if (stack == null) {
2139 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2140 return;
2141 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002142 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002143 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002144 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002145 }
2146 }
2147 } finally {
2148 Binder.restoreCallingIdentity(callingId);
2149 }
2150 }
2151
2152 @Override
2153 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002154 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002155 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2156 final long callingId = Binder.clearCallingIdentity();
2157 try {
2158 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002159 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002160 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002161 if (task == null) {
2162 return;
2163 }
2164 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002165 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002166 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002167 }
2168 }
2169 } finally {
2170 Binder.restoreCallingIdentity(callingId);
2171 }
2172 }
2173
2174 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002175 public void restartActivityProcessIfVisible(IBinder activityToken) {
2176 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2177 final long callingId = Binder.clearCallingIdentity();
2178 try {
2179 synchronized (mGlobalLock) {
2180 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2181 if (r == null) {
2182 return;
2183 }
2184 r.restartProcessIfVisible();
2185 }
2186 } finally {
2187 Binder.restoreCallingIdentity(callingId);
2188 }
2189 }
2190
2191 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002192 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002193 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002194 synchronized (mGlobalLock) {
2195 final long ident = Binder.clearCallingIdentity();
2196 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002197 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002198 "remove-task");
2199 } finally {
2200 Binder.restoreCallingIdentity(ident);
2201 }
2202 }
2203 }
2204
2205 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002206 public void removeAllVisibleRecentTasks() {
2207 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2208 synchronized (mGlobalLock) {
2209 final long ident = Binder.clearCallingIdentity();
2210 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002211 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002212 } finally {
2213 Binder.restoreCallingIdentity(ident);
2214 }
2215 }
2216 }
2217
2218 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002219 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2220 synchronized (mGlobalLock) {
2221 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2222 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002223 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002224 }
2225 }
2226 return false;
2227 }
2228
2229 @Override
2230 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2231 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002232
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002233 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002234 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2235 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002236 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002237 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002238 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002239 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002240 }
2241 }
2242
2243 /**
2244 * Attempts to move a task backwards in z-order (the order of activities within the task is
2245 * unchanged).
2246 *
2247 * There are several possible results of this call:
2248 * - if the task is locked, then we will show the lock toast
2249 * - if there is a task behind the provided task, then that task is made visible and resumed as
2250 * this task is moved to the back
2251 * - otherwise, if there are no other tasks in the stack:
2252 * - if this task is in the pinned stack, then we remove the stack completely, which will
2253 * have the effect of moving the task to the top or bottom of the fullscreen stack
2254 * (depending on whether it is visible)
2255 * - otherwise, we simply return home and hide this task
2256 *
2257 * @param token A reference to the activity we wish to move
2258 * @param nonRoot If false then this only works if the activity is the root
2259 * of a task; if true it will work for any activity in a task.
2260 * @return Returns true if the move completed, false if not.
2261 */
2262 @Override
2263 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002264 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002265 synchronized (mGlobalLock) {
2266 final long origId = Binder.clearCallingIdentity();
2267 try {
2268 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002269 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002270 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002271 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002272 }
2273 } finally {
2274 Binder.restoreCallingIdentity(origId);
2275 }
2276 }
2277 return false;
2278 }
2279
2280 @Override
2281 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002282 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002283 long ident = Binder.clearCallingIdentity();
2284 Rect rect = new Rect();
2285 try {
2286 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002287 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002288 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2289 if (task == null) {
2290 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2291 return rect;
2292 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002293 if (task.getParent() != null) {
2294 rect.set(task.getBounds());
2295 } else if (task.mLastNonFullscreenBounds != null) {
2296 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002297 }
2298 }
2299 } finally {
2300 Binder.restoreCallingIdentity(ident);
2301 }
2302 return rect;
2303 }
2304
2305 @Override
2306 public ActivityManager.TaskDescription getTaskDescription(int id) {
2307 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002308 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002309 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002310 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002311 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2312 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002313 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002314 }
2315 }
2316 return null;
2317 }
2318
2319 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002320 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002321 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08002322 return setTaskWindowingModeSplitScreenPrimary(taskId, toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002323 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002324 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002325 synchronized (mGlobalLock) {
2326 final long ident = Binder.clearCallingIdentity();
2327 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002328 if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2329 return setTaskWindowingModeSplitScreen(taskId, windowingMode, toTop);
2330 }
Louis Chang149d5c82019-12-30 09:47:39 +08002331 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002332 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002333 if (task == null) {
2334 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002335 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002336 }
2337
2338 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2339 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2340
2341 if (!task.isActivityTypeStandardOrUndefined()) {
2342 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2343 + " non-standard task " + taskId + " to windowing mode="
2344 + windowingMode);
2345 }
2346
2347 final ActivityStack stack = task.getStack();
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002348 // Convert some windowing-mode changes into root-task reparents for split-screen.
2349 if (stack.getTile() != null) {
2350 stack.getDisplay().onSplitScreenModeDismissed();
2351 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002352 if (toTop) {
2353 stack.moveToFront("setTaskWindowingMode", task);
2354 }
2355 stack.setWindowingMode(windowingMode);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002356 stack.getDisplay().ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2357 true /* notifyClients */);
Winson Chung7ccc6812020-01-23 16:15:10 -08002358 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002359 } finally {
2360 Binder.restoreCallingIdentity(ident);
2361 }
2362 }
2363 }
2364
2365 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002366 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002367 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368 ActivityRecord r = getCallingRecordLocked(token);
2369 return r != null ? r.info.packageName : null;
2370 }
2371 }
2372
2373 @Override
2374 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002375 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002376 ActivityRecord r = getCallingRecordLocked(token);
2377 return r != null ? r.intent.getComponent() : null;
2378 }
2379 }
2380
2381 private ActivityRecord getCallingRecordLocked(IBinder token) {
2382 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2383 if (r == null) {
2384 return null;
2385 }
2386 return r.resultTo;
2387 }
2388
2389 @Override
2390 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002391 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002392
2393 synchronized (mGlobalLock) {
2394 final long origId = Binder.clearCallingIdentity();
2395 try {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002396 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
2397 if (topFocusedStack != null) {
2398 topFocusedStack.unhandledBackLocked();
2399 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002400 } finally {
2401 Binder.restoreCallingIdentity(origId);
2402 }
2403 }
2404 }
2405
Mark Renouf446251d2019-04-26 10:22:41 -04002406 @Override
2407 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2408 synchronized (mGlobalLock) {
2409 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2410 if (r == null) {
2411 return;
2412 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002413 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002414 if (stack != null && stack.isSingleTaskInstance()) {
2415 // Single-task stacks are used for activities which are presented in floating
2416 // windows above full screen activities. Instead of directly finishing the
2417 // task, a task change listener is used to notify SystemUI so the action can be
2418 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002419 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002420 mTaskChangeNotificationController
2421 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2422 } else {
2423 try {
2424 callback.requestFinish();
2425 } catch (RemoteException e) {
2426 Slog.e(TAG, "Failed to invoke request finish callback", e);
2427 }
2428 }
2429 }
2430 }
2431
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002432 /**
2433 * TODO: Add mController hook
2434 */
2435 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002436 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2437 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002438 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002439
2440 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2441 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002442 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2443 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002444 }
2445 }
2446
Ricky Waiaca8a772019-04-04 16:01:06 +01002447 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2448 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002449 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002450 final int callingPid = Binder.getCallingPid();
2451 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002452 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002453 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002454 SafeActivityOptions.abort(options);
2455 return;
2456 }
2457 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002458 WindowProcessController callerApp = null;
2459 if (appThread != null) {
2460 callerApp = getProcessController(appThread);
2461 }
2462 final ActivityStarter starter = getActivityStartController().obtainStarter(
2463 null /* intent */, "moveTaskToFront");
2464 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
Galia Peycheva6861e912019-08-21 10:20:23 +02002465 -1, callerApp, null, false, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002466 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002467 return;
2468 }
2469 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002470 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002471 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002472 if (task == null) {
2473 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002474 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002475 return;
2476 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002477 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002478 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002479 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002480 return;
2481 }
2482 ActivityOptions realOptions = options != null
2483 ? options.getOptions(mStackSupervisor)
2484 : null;
2485 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2486 false /* forceNonResizable */);
2487
Wale Ogunwale21e06482019-11-18 05:14:15 -08002488 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002489 if (topActivity != null) {
2490
2491 // We are reshowing a task, use a starting window to hide the initial draw delay
2492 // so the transition can start earlier.
2493 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2494 true /* taskSwitch */, fromRecents);
2495 }
2496 } finally {
2497 Binder.restoreCallingIdentity(origId);
2498 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002499 }
2500
Ricky Waiaca8a772019-04-04 16:01:06 +01002501 /**
2502 * Return true if callingUid is system, or packageName belongs to that callingUid.
2503 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002504 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002505 try {
2506 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2507 if (packageName == null) {
2508 return false;
2509 }
2510 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2511 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2512 UserHandle.getUserId(callingUid));
2513 return UserHandle.isSameApp(callingUid, uid);
2514 }
2515 } catch (RemoteException e) {
2516 // Should not happen
2517 }
2518 return true;
2519 }
2520
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002521 /**
2522 * Checks that the provided package name matches the current calling UID, throws a security
2523 * exception if it doesn't.
2524 */
2525 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2526 final int callingUid = Binder.getCallingUid();
2527 if (isSameApp(callingUid, packageName)) {
2528 return;
2529 }
2530 final String msg = "Permission Denial: package=" + packageName
2531 + " does not belong to uid=" + callingUid;
2532 Slog.w(TAG, msg);
2533 throw new SecurityException(msg);
2534 }
2535
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002536 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2537 int callingPid, int callingUid, String name) {
2538 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2539 return true;
2540 }
2541
2542 if (getRecentTasks().isCallerRecents(sourceUid)) {
2543 return true;
2544 }
2545
2546 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2547 if (perm == PackageManager.PERMISSION_GRANTED) {
2548 return true;
2549 }
2550 if (checkAllowAppSwitchUid(sourceUid)) {
2551 return true;
2552 }
2553
2554 // If the actual IPC caller is different from the logical source, then
2555 // also see if they are allowed to control app switches.
2556 if (callingUid != -1 && callingUid != sourceUid) {
2557 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2558 if (perm == PackageManager.PERMISSION_GRANTED) {
2559 return true;
2560 }
2561 if (checkAllowAppSwitchUid(callingUid)) {
2562 return true;
2563 }
2564 }
2565
2566 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2567 return false;
2568 }
2569
2570 private boolean checkAllowAppSwitchUid(int uid) {
2571 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2572 if (types != null) {
2573 for (int i = types.size() - 1; i >= 0; i--) {
2574 if (types.valueAt(i).intValue() == uid) {
2575 return true;
2576 }
2577 }
2578 }
2579 return false;
2580 }
2581
2582 @Override
2583 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2584 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2585 "setActivityController()");
2586 synchronized (mGlobalLock) {
2587 mController = controller;
2588 mControllerIsAMonkey = imAMonkey;
2589 Watchdog.getInstance().setActivityController(controller);
2590 }
2591 }
2592
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002593 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002594 synchronized (mGlobalLock) {
2595 return mController != null && mControllerIsAMonkey;
2596 }
2597 }
2598
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002599 @Override
2600 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2601 synchronized (mGlobalLock) {
2602 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2603 }
2604 }
2605
2606 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002607 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2608 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2609 }
2610
2611 @Override
2612 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2613 @WindowConfiguration.ActivityType int ignoreActivityType,
2614 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2615 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002616 final int callingPid = Binder.getCallingPid();
2617 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002618 final int[] profileIds = getUserManager().getProfileIds(
2619 UserHandle.getUserId(callingUid), true);
2620 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2621 for (int i = 0; i < profileIds.length; i++) {
2622 callingProfileIds.add(profileIds[i]);
2623 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002624 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2625
2626 synchronized (mGlobalLock) {
2627 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2628
Nicholas Sauer0259e532019-08-30 08:24:55 -07002629 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002630 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002631 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002632 }
2633
2634 return list;
2635 }
2636
2637 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002638 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2639 synchronized (mGlobalLock) {
2640 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002641 try {
2642 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2643 if (r == null) return;
2644
2645 final PooledConsumer c = PooledLambda.obtainConsumer(
2646 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2647 r, resultWho, requestCode);
2648 // TODO: This should probably only loop over the task since you need to be in the
2649 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002650 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002651 c.recycle();
2652
2653 updateOomAdj();
2654 } finally {
2655 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002656 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002657 }
2658 }
2659
2660 @Override
2661 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002662 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002663 ActivityStack stack = ActivityRecord.getStackLocked(token);
2664 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002665 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002666 }
2667 return false;
2668 }
2669 }
2670
2671 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002672 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002673 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002674 synchronized (mGlobalLock) {
2675 final long ident = Binder.clearCallingIdentity();
2676 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002677 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002678 if (task == null) {
2679 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2680 return;
2681 }
2682
2683 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2684 + " to stackId=" + stackId + " toTop=" + toTop);
2685
Louis Chang149d5c82019-12-30 09:47:39 +08002686 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002687 if (stack == null) {
2688 throw new IllegalStateException(
2689 "moveTaskToStack: No stack for stackId=" + stackId);
2690 }
2691 if (!stack.isActivityTypeStandardOrUndefined()) {
2692 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2693 + taskId + " to stack " + stackId);
2694 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002695 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2696 "moveTaskToStack");
2697 } finally {
2698 Binder.restoreCallingIdentity(ident);
2699 }
2700 }
2701 }
2702
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002703 /**
2704 * Moves the specified task to the primary-split-screen stack.
2705 *
2706 * @param taskId Id of task to move.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002707 * @param toTop If the task and stack should be moved to the top.
Winson Chung7ccc6812020-01-23 16:15:10 -08002708 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002709 */
2710 @Override
Evan Rosky73a7fe92019-11-18 18:28:01 -08002711 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002712 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002713 "setTaskWindowingModeSplitScreenPrimary()");
2714 synchronized (mGlobalLock) {
2715 final long ident = Binder.clearCallingIdentity();
2716 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002717 return setTaskWindowingModeSplitScreen(taskId, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY,
2718 toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002719 } finally {
2720 Binder.restoreCallingIdentity(ident);
2721 }
2722 }
2723 }
2724
2725 /**
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002726 * Moves the specified task into a split-screen tile.
2727 */
2728 private boolean setTaskWindowingModeSplitScreen(int taskId, int windowingMode, boolean toTop) {
2729 if (!WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2730 throw new IllegalArgumentException("Calling setTaskWindowingModeSplitScreen with non"
2731 + "split-screen mode: " + windowingMode);
2732 }
2733 if (isInLockTaskMode()) {
2734 Slog.w(TAG, "setTaskWindowingModeSplitScreen: Is in lock task mode="
2735 + getLockTaskModeState());
2736 return false;
2737 }
2738
2739 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2740 MATCH_TASK_IN_STACKS_ONLY);
2741 if (task == null) {
2742 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2743 return false;
2744 }
2745 if (!task.isActivityTypeStandardOrUndefined()) {
2746 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2747 + " non-standard task " + taskId + " to split-screen windowing mode");
2748 }
Wale Ogunwale0d465192020-01-23 19:14:44 -08002749 if (!task.supportsSplitScreenWindowingMode()) {
2750 return false;
2751 }
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002752
2753 final int prevMode = task.getWindowingMode();
Wale Ogunwale0d465192020-01-23 19:14:44 -08002754 moveTaskToSplitScreenPrimaryTile(task, toTop);
2755 return prevMode != task.getWindowingMode();
2756 }
2757
2758 void moveTaskToSplitScreenPrimaryTile(Task task, boolean toTop) {
2759 ActivityStack stack = task.getStack();
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002760 TaskTile tile = null;
2761 for (int i = stack.getDisplay().getStackCount() - 1; i >= 0; --i) {
2762 tile = stack.getDisplay().getStackAt(i).asTile();
2763 if (tile != null && tile.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2764 break;
2765 }
2766 }
2767 if (tile == null) {
2768 throw new IllegalStateException("Can't enter split without associated tile");
2769 }
2770 WindowContainerTransaction wct = new WindowContainerTransaction();
2771 wct.reparent(stack.mRemoteToken, tile.mRemoteToken, toTop);
2772 mTaskOrganizerController.applyContainerTransaction(wct, null);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002773 }
2774
2775 /**
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002776 * Removes stacks in the input windowing modes from the system if they are of activity type
2777 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2778 */
2779 @Override
2780 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002781 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002782 "removeStacksInWindowingModes()");
2783
2784 synchronized (mGlobalLock) {
2785 final long ident = Binder.clearCallingIdentity();
2786 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002787 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002788 } finally {
2789 Binder.restoreCallingIdentity(ident);
2790 }
2791 }
2792 }
2793
2794 @Override
2795 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002796 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002797 "removeStacksWithActivityTypes()");
2798
2799 synchronized (mGlobalLock) {
2800 final long ident = Binder.clearCallingIdentity();
2801 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002802 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002803 } finally {
2804 Binder.restoreCallingIdentity(ident);
2805 }
2806 }
2807 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002808
2809 @Override
2810 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2811 int userId) {
2812 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002813 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2814 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002815 callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002816 synchronized (mGlobalLock) {
Winson Chung66b08f02020-03-03 14:32:35 -08002817 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, userId, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002818 }
2819 }
2820
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002821 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002822 @Override
2823 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002824 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
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.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002829 }
2830 } finally {
2831 Binder.restoreCallingIdentity(ident);
2832 }
2833 }
2834
2835 @Override
2836 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002837 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002838 long ident = Binder.clearCallingIdentity();
2839 try {
2840 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002841 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002842 }
2843 } finally {
2844 Binder.restoreCallingIdentity(ident);
2845 }
2846 }
2847
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002848 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002849 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002850 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2851 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2852 long ident = Binder.clearCallingIdentity();
2853 try {
2854 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002855 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002856 }
2857 } finally {
2858 Binder.restoreCallingIdentity(ident);
2859 }
2860 }
2861
2862 @Override
2863 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2864 int displayId) {
2865 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2866 long ident = Binder.clearCallingIdentity();
2867 try {
2868 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002869 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002870 }
2871 } finally {
2872 Binder.restoreCallingIdentity(ident);
2873 }
2874 }
2875
2876 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002877 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002878 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002879 final long callingUid = Binder.getCallingUid();
2880 final long origId = Binder.clearCallingIdentity();
2881 try {
2882 synchronized (mGlobalLock) {
2883 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002884 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002885 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2886 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2887 }
2888 } finally {
2889 Binder.restoreCallingIdentity(origId);
2890 }
2891 }
2892
2893 @Override
2894 public void startLockTaskModeByToken(IBinder token) {
2895 synchronized (mGlobalLock) {
2896 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2897 if (r == null) {
2898 return;
2899 }
Louis Changcdec0802019-11-11 11:45:07 +08002900 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002901 }
2902 }
2903
2904 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002905 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002906 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002907 // This makes inner call to look as if it was initiated by system.
2908 long ident = Binder.clearCallingIdentity();
2909 try {
2910 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002911 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002912 MATCH_TASK_IN_STACKS_ONLY);
2913 if (task == null) {
2914 return;
2915 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002916
2917 // When starting lock task mode the stack must be in front and focused
2918 task.getStack().moveToFront("startSystemLockTaskMode");
2919 startLockTaskModeLocked(task, true /* isSystemCaller */);
2920 }
2921 } finally {
2922 Binder.restoreCallingIdentity(ident);
2923 }
2924 }
2925
2926 @Override
2927 public void stopLockTaskModeByToken(IBinder token) {
2928 synchronized (mGlobalLock) {
2929 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2930 if (r == null) {
2931 return;
2932 }
Louis Changcdec0802019-11-11 11:45:07 +08002933 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002934 }
2935 }
2936
2937 /**
2938 * This API should be called by SystemUI only when user perform certain action to dismiss
2939 * lock task mode. We should only dismiss pinned lock task mode in this case.
2940 */
2941 @Override
2942 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002943 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002944 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2945 }
2946
Louis Changcdec0802019-11-11 11:45:07 +08002947 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002948 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2949 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2950 return;
2951 }
2952
Louis Chang149d5c82019-12-30 09:47:39 +08002953 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002954 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002955 throw new IllegalArgumentException("Invalid task, not in foreground");
2956 }
2957
2958 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2959 // system or a specific app.
2960 // * System-initiated requests will only start the pinned mode (screen pinning)
2961 // * App-initiated requests
2962 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2963 // - will start the pinned mode, otherwise
2964 final int callingUid = Binder.getCallingUid();
2965 long ident = Binder.clearCallingIdentity();
2966 try {
2967 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002968 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002969
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002970 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002971 } finally {
2972 Binder.restoreCallingIdentity(ident);
2973 }
2974 }
2975
Louis Changcdec0802019-11-11 11:45:07 +08002976 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002977 final int callingUid = Binder.getCallingUid();
2978 long ident = Binder.clearCallingIdentity();
2979 try {
2980 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002981 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982 }
2983 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2984 // task and jumping straight into a call in the case of emergency call back.
2985 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2986 if (tm != null) {
2987 tm.showInCallScreen(false);
2988 }
2989 } finally {
2990 Binder.restoreCallingIdentity(ident);
2991 }
2992 }
2993
2994 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002995 public void updateLockTaskPackages(int userId, String[] packages) {
2996 final int callingUid = Binder.getCallingUid();
2997 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2998 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2999 "updateLockTaskPackages()");
3000 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08003001 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003002 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
3003 + Arrays.toString(packages));
3004 getLockTaskController().updateLockTaskPackages(userId, packages);
3005 }
3006 }
3007
3008 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003009 public boolean isInLockTaskMode() {
3010 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3011 }
3012
3013 @Override
3014 public int getLockTaskModeState() {
3015 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003016 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003017 }
3018 }
3019
3020 @Override
3021 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3022 synchronized (mGlobalLock) {
3023 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3024 if (r != null) {
3025 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003026 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003027 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003028 }
3029 }
3030 }
3031
3032 @Override
3033 public Bundle getActivityOptions(IBinder token) {
3034 final long origId = Binder.clearCallingIdentity();
3035 try {
3036 synchronized (mGlobalLock) {
3037 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3038 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003039 final ActivityOptions activityOptions = r.takeOptionsLocked(
3040 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003041 return activityOptions == null ? null : activityOptions.toBundle();
3042 }
3043 return null;
3044 }
3045 } finally {
3046 Binder.restoreCallingIdentity(origId);
3047 }
3048 }
3049
3050 @Override
3051 public List<IBinder> getAppTasks(String callingPackage) {
3052 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003053 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003054 long ident = Binder.clearCallingIdentity();
3055 try {
3056 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003057 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003058 }
3059 } finally {
3060 Binder.restoreCallingIdentity(ident);
3061 }
3062 }
3063
3064 @Override
3065 public void finishVoiceTask(IVoiceInteractionSession session) {
3066 synchronized (mGlobalLock) {
3067 final long origId = Binder.clearCallingIdentity();
3068 try {
3069 // TODO: VI Consider treating local voice interactions and voice tasks
3070 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003071 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003072 } finally {
3073 Binder.restoreCallingIdentity(origId);
3074 }
3075 }
3076
3077 }
3078
3079 @Override
3080 public boolean isTopOfTask(IBinder token) {
3081 synchronized (mGlobalLock) {
3082 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003083 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003084 }
3085 }
3086
3087 @Override
3088 public void notifyLaunchTaskBehindComplete(IBinder token) {
3089 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3090 }
3091
3092 @Override
3093 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003094 mH.post(() -> {
3095 synchronized (mGlobalLock) {
3096 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003097 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003098 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003099 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003100 } catch (RemoteException e) {
3101 }
3102 }
3103 }
3104
3105 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003106 }
3107
3108 /** Called from an app when assist data is ready. */
3109 @Override
3110 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3111 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003112 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003113 synchronized (pae) {
3114 pae.result = extras;
3115 pae.structure = structure;
3116 pae.content = content;
3117 if (referrer != null) {
3118 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3119 }
3120 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003121 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003122 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003123 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003124 structure.setHomeActivity(pae.isHome);
3125 }
3126 pae.haveResult = true;
3127 pae.notifyAll();
3128 if (pae.intent == null && pae.receiver == null) {
3129 // Caller is just waiting for the result.
3130 return;
3131 }
3132 }
3133 // We are now ready to launch the assist activity.
3134 IAssistDataReceiver sendReceiver = null;
3135 Bundle sendBundle = null;
3136 synchronized (mGlobalLock) {
3137 buildAssistBundleLocked(pae, extras);
3138 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003139 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003140 if (!exists) {
3141 // Timed out.
3142 return;
3143 }
3144
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003145 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003146 // Caller wants result sent back to them.
3147 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003148 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003149 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003150 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3151 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003152 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3153 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3154 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3155 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3156 }
3157 }
3158 if (sendReceiver != null) {
3159 try {
3160 sendReceiver.onHandleAssistData(sendBundle);
3161 } catch (RemoteException e) {
3162 }
3163 return;
3164 }
3165
3166 final long ident = Binder.clearCallingIdentity();
3167 try {
3168 if (TextUtils.equals(pae.intent.getAction(),
3169 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003170 // Start voice interaction through VoiceInteractionManagerService.
3171 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3172 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003173 } else {
3174 pae.intent.replaceExtras(pae.extras);
3175 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3176 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3177 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003178 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003179
3180 try {
3181 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3182 } catch (ActivityNotFoundException e) {
3183 Slog.w(TAG, "No activity to handle assist action.", e);
3184 }
3185 }
3186 } finally {
3187 Binder.restoreCallingIdentity(ident);
3188 }
3189 }
3190
3191 @Override
3192 public int addAppTask(IBinder activityToken, Intent intent,
3193 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3194 final int callingUid = Binder.getCallingUid();
3195 final long callingIdent = Binder.clearCallingIdentity();
3196
3197 try {
3198 synchronized (mGlobalLock) {
3199 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3200 if (r == null) {
3201 throw new IllegalArgumentException("Activity does not exist; token="
3202 + activityToken);
3203 }
3204 ComponentName comp = intent.getComponent();
3205 if (comp == null) {
3206 throw new IllegalArgumentException("Intent " + intent
3207 + " must specify explicit component");
3208 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003209 if (thumbnail.getWidth() != mThumbnailWidth
3210 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003211 throw new IllegalArgumentException("Bad thumbnail size: got "
3212 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003213 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003214 }
3215 if (intent.getSelector() != null) {
3216 intent.setSelector(null);
3217 }
3218 if (intent.getSourceBounds() != null) {
3219 intent.setSourceBounds(null);
3220 }
3221 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3222 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3223 // The caller has added this as an auto-remove task... that makes no
3224 // sense, so turn off auto-remove.
3225 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3226 }
3227 }
3228 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3229 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3230 if (ainfo.applicationInfo.uid != callingUid) {
3231 throw new SecurityException(
3232 "Can't add task for another application: target uid="
3233 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3234 }
3235
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003236 final ActivityStack stack = r.getRootTask();
Wale Ogunwale0d465192020-01-23 19:14:44 -08003237 final Task task = stack.getDisplay().createStack(stack.getWindowingMode(),
3238 stack.getActivityType(), !ON_TOP, ainfo, intent);
3239
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003240 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003241 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003242 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003243 return INVALID_TASK_ID;
3244 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003245 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003246
3247 // TODO: Send the thumbnail to WM to store it.
3248
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003249 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003250 }
3251 } finally {
3252 Binder.restoreCallingIdentity(callingIdent);
3253 }
3254 }
3255
3256 @Override
3257 public Point getAppTaskThumbnailSize() {
3258 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003259 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003260 }
3261 }
3262
3263 @Override
3264 public void setTaskResizeable(int taskId, int resizeableMode) {
3265 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003266 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003267 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3268 if (task == null) {
3269 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3270 return;
3271 }
3272 task.setResizeMode(resizeableMode);
3273 }
3274 }
3275
3276 @Override
3277 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003278 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003279 long ident = Binder.clearCallingIdentity();
3280 try {
3281 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003282 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003283 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003284 if (task == null) {
3285 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3286 return;
3287 }
3288 // Place the task in the right stack if it isn't there already based on
3289 // the requested bounds.
3290 // The stack transition logic is:
3291 // - a null bounds on a freeform task moves that task to fullscreen
3292 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3293 // that task to freeform
3294 // - otherwise the task is not moved
3295 ActivityStack stack = task.getStack();
3296 if (!task.getWindowConfiguration().canResizeTask()) {
3297 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3298 }
3299 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3300 stack = stack.getDisplay().getOrCreateStack(
3301 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3302 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3303 stack = stack.getDisplay().getOrCreateStack(
3304 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3305 }
3306
3307 // Reparent the task to the right stack if necessary
3308 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3309 if (stack != task.getStack()) {
3310 // Defer resume until the task is resized below
3311 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3312 DEFER_RESUME, "resizeTask");
3313 preserveWindow = false;
3314 }
3315
3316 // After reparenting (which only resizes the task to the stack bounds), resize the
3317 // task to the actual bounds provided
3318 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3319 }
3320 } finally {
3321 Binder.restoreCallingIdentity(ident);
3322 }
3323 }
3324
3325 @Override
3326 public boolean releaseActivityInstance(IBinder token) {
3327 synchronized (mGlobalLock) {
3328 final long origId = Binder.clearCallingIdentity();
3329 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003330 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3331 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003332 return false;
3333 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003334 r.destroyImmediately(true /* removeFromApp */, "app-req");
3335 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003336 } finally {
3337 Binder.restoreCallingIdentity(origId);
3338 }
3339 }
3340 }
3341
3342 @Override
3343 public void releaseSomeActivities(IApplicationThread appInt) {
3344 synchronized (mGlobalLock) {
3345 final long origId = Binder.clearCallingIdentity();
3346 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003347 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003348 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003349 } finally {
3350 Binder.restoreCallingIdentity(origId);
3351 }
3352 }
3353 }
3354
3355 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003356 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003357 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003358 != PackageManager.PERMISSION_GRANTED) {
3359 throw new SecurityException("Requires permission "
3360 + android.Manifest.permission.DEVICE_POWER);
3361 }
3362
3363 synchronized (mGlobalLock) {
3364 long ident = Binder.clearCallingIdentity();
3365 if (mKeyguardShown != keyguardShowing) {
3366 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003367 final Message msg = PooledLambda.obtainMessage(
3368 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3369 keyguardShowing);
3370 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003371 }
3372 try {
wilsonshih177261f2019-02-22 12:02:18 +08003373 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003374 } finally {
3375 Binder.restoreCallingIdentity(ident);
3376 }
3377 }
3378
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003379 mH.post(() -> {
3380 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3381 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3382 }
3383 });
3384 }
3385
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003386 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003387 mH.post(() -> {
3388 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3389 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3390 }
3391 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003392 }
3393
3394 @Override
3395 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003396 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3397 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003398
3399 final File passedIconFile = new File(filePath);
3400 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3401 passedIconFile.getName());
3402 if (!legitIconFile.getPath().equals(filePath)
3403 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3404 throw new IllegalArgumentException("Bad file path: " + filePath
3405 + " passed for userId " + userId);
3406 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003407 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003408 }
3409
3410 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003411 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003412 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003413 synchronized (mGlobalLock) {
3414 final long ident = Binder.clearCallingIdentity();
3415 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003416 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003417 if (stack == null) {
3418 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3419 return;
3420 }
3421 if (!stack.isActivityTypeStandardOrUndefined()) {
3422 throw new IllegalArgumentException(
3423 "Removing non-standard stack is not allowed.");
3424 }
3425 mStackSupervisor.removeStack(stack);
3426 } finally {
3427 Binder.restoreCallingIdentity(ident);
3428 }
3429 }
3430 }
3431
3432 @Override
3433 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003434 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003435
3436 synchronized (mGlobalLock) {
3437 final long ident = Binder.clearCallingIdentity();
3438 try {
3439 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3440 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003441 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003442 } finally {
3443 Binder.restoreCallingIdentity(ident);
3444 }
3445 }
3446 }
3447
3448 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003449 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003450 synchronized (mGlobalLock) {
3451 long ident = Binder.clearCallingIdentity();
3452 try {
3453 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3454 if (r == null) {
3455 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003456 "toggleFreeformWindowingMode: No activity record matching token="
3457 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003458 }
3459
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003460 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003461 if (stack == null) {
3462 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3463 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003464 }
3465
Yunfan Chend967af82019-01-17 18:30:18 +09003466 if (!stack.inFreeformWindowingMode()
3467 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3468 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3469 + "toggle between fullscreen and freeform.");
3470 }
3471
3472 if (stack.inFreeformWindowingMode()) {
3473 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003474 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003475 throw new IllegalStateException("Size-compat windows are currently not"
3476 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003477 } else if (stack.getParent().inFreeformWindowingMode()) {
3478 // If the window is on a freeform display, set it to undefined. It will be
3479 // resolved to freeform and it can adjust windowing mode when the display mode
3480 // changes in runtime.
3481 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003482 } else {
3483 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3484 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003485 } finally {
3486 Binder.restoreCallingIdentity(ident);
3487 }
3488 }
3489 }
3490
3491 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3492 @Override
3493 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003494 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003495 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003496 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003497 }
3498
3499 /** Unregister a task stack listener so that it stops receiving callbacks. */
3500 @Override
3501 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003502 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003503 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003504 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003505 }
3506
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003507 @Override
3508 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3509 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3510 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3511 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3512 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3513 }
3514
3515 @Override
3516 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3517 IBinder activityToken, int flags) {
3518 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3519 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3520 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3521 }
3522
3523 @Override
3524 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3525 Bundle args) {
3526 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3527 true /* focused */, true /* newSessionId */, userHandle, args,
3528 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3529 }
3530
3531 @Override
3532 public Bundle getAssistContextExtras(int requestType) {
3533 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3534 null, null, true /* focused */, true /* newSessionId */,
3535 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3536 if (pae == null) {
3537 return null;
3538 }
3539 synchronized (pae) {
3540 while (!pae.haveResult) {
3541 try {
3542 pae.wait();
3543 } catch (InterruptedException e) {
3544 }
3545 }
3546 }
3547 synchronized (mGlobalLock) {
3548 buildAssistBundleLocked(pae, pae.result);
3549 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003550 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003551 }
3552 return pae.extras;
3553 }
3554
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003555 /**
3556 * Binder IPC calls go through the public entry point.
3557 * This can be called with or without the global lock held.
3558 */
3559 private static int checkCallingPermission(String permission) {
3560 return checkPermission(
3561 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3562 }
3563
3564 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003565 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003566 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3567 mAmInternal.enforceCallingPermission(permission, func);
3568 }
3569 }
3570
3571 @VisibleForTesting
3572 int checkGetTasksPermission(String permission, int pid, int uid) {
3573 return checkPermission(permission, pid, uid);
3574 }
3575
3576 static int checkPermission(String permission, int pid, int uid) {
3577 if (permission == null) {
3578 return PackageManager.PERMISSION_DENIED;
3579 }
3580 return checkComponentPermission(permission, pid, uid, -1, true);
3581 }
3582
Wale Ogunwale214f3482018-10-04 11:00:47 -07003583 public static int checkComponentPermission(String permission, int pid, int uid,
3584 int owningUid, boolean exported) {
3585 return ActivityManagerService.checkComponentPermission(
3586 permission, pid, uid, owningUid, exported);
3587 }
3588
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003589 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3590 if (getRecentTasks().isCallerRecents(callingUid)) {
3591 // Always allow the recents component to get tasks
3592 return true;
3593 }
3594
3595 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3596 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3597 if (!allowed) {
3598 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3599 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3600 // Temporary compatibility: some existing apps on the system image may
3601 // still be requesting the old permission and not switched to the new
3602 // one; if so, we'll still allow them full access. This means we need
3603 // to see if they are holding the old permission and are a system app.
3604 try {
3605 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3606 allowed = true;
3607 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3608 + " is using old GET_TASKS but privileged; allowing");
3609 }
3610 } catch (RemoteException e) {
3611 }
3612 }
3613 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3614 + " does not hold REAL_GET_TASKS; limiting output");
3615 }
3616 return allowed;
3617 }
3618
Nicholas Sauer0259e532019-08-30 08:24:55 -07003619 boolean isCrossUserAllowed(int pid, int uid) {
3620 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3621 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3622 }
3623
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003624 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3625 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3626 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3627 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003628 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003629 "enqueueAssistContext()");
3630
3631 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08003632 final ActivityStack stack = getTopDisplayFocusedStack();
3633 ActivityRecord activity = stack != null ? stack.getTopNonFinishingActivity() : null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003634 if (activity == null) {
3635 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3636 return null;
3637 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003638 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003639 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3640 return null;
3641 }
3642 if (focused) {
3643 if (activityToken != null) {
3644 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3645 if (activity != caller) {
3646 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3647 + " is not current top " + activity);
3648 return null;
3649 }
3650 }
3651 } else {
3652 activity = ActivityRecord.forTokenLocked(activityToken);
3653 if (activity == null) {
3654 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3655 + " couldn't be found");
3656 return null;
3657 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003658 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003659 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3660 return null;
3661 }
3662 }
3663
3664 PendingAssistExtras pae;
3665 Bundle extras = new Bundle();
3666 if (args != null) {
3667 extras.putAll(args);
3668 }
3669 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003670 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003671
3672 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3673 userHandle);
3674 pae.isHome = activity.isActivityTypeHome();
3675
3676 // Increment the sessionId if necessary
3677 if (newSessionId) {
3678 mViSessionId++;
3679 }
3680 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003681 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3682 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003683 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003684 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003685 } catch (RemoteException e) {
3686 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3687 return null;
3688 }
3689 return pae;
3690 }
3691 }
3692
3693 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3694 if (result != null) {
3695 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3696 }
3697 if (pae.hint != null) {
3698 pae.extras.putBoolean(pae.hint, true);
3699 }
3700 }
3701
3702 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3703 IAssistDataReceiver receiver;
3704 synchronized (mGlobalLock) {
3705 mPendingAssistExtras.remove(pae);
3706 receiver = pae.receiver;
3707 }
3708 if (receiver != null) {
3709 // Caller wants result sent back to them.
3710 Bundle sendBundle = new Bundle();
3711 // At least return the receiver extras
3712 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3713 try {
3714 pae.receiver.onHandleAssistData(sendBundle);
3715 } catch (RemoteException e) {
3716 }
3717 }
3718 }
3719
3720 public class PendingAssistExtras extends Binder implements Runnable {
3721 public final ActivityRecord activity;
3722 public boolean isHome;
3723 public final Bundle extras;
3724 public final Intent intent;
3725 public final String hint;
3726 public final IAssistDataReceiver receiver;
3727 public final int userHandle;
3728 public boolean haveResult = false;
3729 public Bundle result = null;
3730 public AssistStructure structure = null;
3731 public AssistContent content = null;
3732 public Bundle receiverExtras;
3733
3734 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3735 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3736 int _userHandle) {
3737 activity = _activity;
3738 extras = _extras;
3739 intent = _intent;
3740 hint = _hint;
3741 receiver = _receiver;
3742 receiverExtras = _receiverExtras;
3743 userHandle = _userHandle;
3744 }
3745
3746 @Override
3747 public void run() {
3748 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3749 synchronized (this) {
3750 haveResult = true;
3751 notifyAll();
3752 }
3753 pendingAssistExtrasTimedOut(this);
3754 }
3755 }
3756
3757 @Override
3758 public boolean isAssistDataAllowedOnCurrentActivity() {
3759 int userId;
3760 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003761 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003762 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3763 return false;
3764 }
3765
Wale Ogunwale21e06482019-11-18 05:14:15 -08003766 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003767 if (activity == null) {
3768 return false;
3769 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003770 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003771 }
3772 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3773 }
3774
3775 @Override
3776 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3777 long ident = Binder.clearCallingIdentity();
3778 try {
3779 synchronized (mGlobalLock) {
3780 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003781 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003782 if (top != caller) {
3783 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3784 + " is not current top " + top);
3785 return false;
3786 }
3787 if (!top.nowVisible) {
3788 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3789 + " is not visible");
3790 return false;
3791 }
3792 }
3793 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3794 token);
3795 } finally {
3796 Binder.restoreCallingIdentity(ident);
3797 }
3798 }
3799
3800 @Override
3801 public boolean isRootVoiceInteraction(IBinder token) {
3802 synchronized (mGlobalLock) {
3803 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3804 if (r == null) {
3805 return false;
3806 }
3807 return r.rootVoiceInteraction;
3808 }
3809 }
3810
Wale Ogunwalef6733932018-06-27 05:14:34 -07003811 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3812 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3813 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3814 if (activityToCallback == null) return;
3815 activityToCallback.setVoiceSessionLocked(voiceSession);
3816
3817 // Inform the activity
3818 try {
3819 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3820 voiceInteractor);
3821 long token = Binder.clearCallingIdentity();
3822 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003823 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003824 } finally {
3825 Binder.restoreCallingIdentity(token);
3826 }
3827 // TODO: VI Should we cache the activity so that it's easier to find later
3828 // rather than scan through all the stacks and activities?
3829 } catch (RemoteException re) {
3830 activityToCallback.clearVoiceSessionLocked();
3831 // TODO: VI Should this terminate the voice session?
3832 }
3833 }
3834
3835 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3836 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3837 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3838 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3839 boolean wasRunningVoice = mRunningVoice != null;
3840 mRunningVoice = session;
3841 if (!wasRunningVoice) {
3842 mVoiceWakeLock.acquire();
3843 updateSleepIfNeededLocked();
3844 }
3845 }
3846 }
3847
3848 void finishRunningVoiceLocked() {
3849 if (mRunningVoice != null) {
3850 mRunningVoice = null;
3851 mVoiceWakeLock.release();
3852 updateSleepIfNeededLocked();
3853 }
3854 }
3855
3856 @Override
3857 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3858 synchronized (mGlobalLock) {
3859 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3860 if (keepAwake) {
3861 mVoiceWakeLock.acquire();
3862 } else {
3863 mVoiceWakeLock.release();
3864 }
3865 }
3866 }
3867 }
3868
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003869 @Override
3870 public ComponentName getActivityClassForToken(IBinder token) {
3871 synchronized (mGlobalLock) {
3872 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3873 if (r == null) {
3874 return null;
3875 }
3876 return r.intent.getComponent();
3877 }
3878 }
3879
3880 @Override
3881 public String getPackageForToken(IBinder token) {
3882 synchronized (mGlobalLock) {
3883 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3884 if (r == null) {
3885 return null;
3886 }
3887 return r.packageName;
3888 }
3889 }
3890
3891 @Override
3892 public void showLockTaskEscapeMessage(IBinder token) {
3893 synchronized (mGlobalLock) {
3894 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3895 if (r == null) {
3896 return;
3897 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003898 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003899 }
3900 }
3901
3902 @Override
3903 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003904 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003905 final long token = Binder.clearCallingIdentity();
3906 try {
3907 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003908 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003909 }
3910 } finally {
3911 Binder.restoreCallingIdentity(token);
3912 }
3913 }
3914
3915 /**
3916 * Try to place task to provided position. The final position might be different depending on
3917 * current user and stacks state. The task will be moved to target stack if it's currently in
3918 * different stack.
3919 */
3920 @Override
3921 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003922 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003923 synchronized (mGlobalLock) {
3924 long ident = Binder.clearCallingIdentity();
3925 try {
3926 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3927 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003928 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003929 if (task == null) {
3930 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3931 + taskId);
3932 }
3933
Louis Chang149d5c82019-12-30 09:47:39 +08003934 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003935
3936 if (stack == null) {
3937 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3938 + stackId);
3939 }
3940 if (!stack.isActivityTypeStandardOrUndefined()) {
3941 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3942 + " the position of task " + taskId + " in/to non-standard stack");
3943 }
3944
3945 // TODO: Have the callers of this API call a separate reparent method if that is
3946 // what they intended to do vs. having this method also do reparenting.
3947 if (task.getStack() == stack) {
3948 // Change position in current stack.
3949 stack.positionChildAt(task, position);
3950 } else {
3951 // Reparent to new stack.
3952 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3953 !DEFER_RESUME, "positionTaskInStack");
3954 }
3955 } finally {
3956 Binder.restoreCallingIdentity(ident);
3957 }
3958 }
3959 }
3960
3961 @Override
3962 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3963 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3964 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003965 + Arrays.toString(horizontalSizeConfiguration) + " "
3966 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003967 synchronized (mGlobalLock) {
3968 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3969 if (record == null) {
3970 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3971 + "found for: " + token);
3972 }
3973 record.setSizeConfigurations(horizontalSizeConfiguration,
3974 verticalSizeConfigurations, smallestSizeConfigurations);
3975 }
3976 }
3977
3978 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003979 * Dismisses Pip
3980 * @param animate True if the dismissal should be animated.
3981 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3982 * default animation duration should be used.
3983 */
3984 @Override
3985 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003986 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003987 final long ident = Binder.clearCallingIdentity();
3988 try {
3989 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003990 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08003991 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003992 if (stack == null) {
3993 Slog.w(TAG, "dismissPip: pinned stack not found.");
3994 return;
3995 }
3996 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3997 throw new IllegalArgumentException("Stack: " + stack
3998 + " doesn't support animated resize.");
3999 }
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004000 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004001 }
4002 } finally {
4003 Binder.restoreCallingIdentity(ident);
4004 }
4005 }
4006
4007 @Override
4008 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004009 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004010 synchronized (mGlobalLock) {
4011 mSuppressResizeConfigChanges = suppress;
4012 }
4013 }
4014
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004015 @Override
4016 // TODO: API should just be about changing windowing modes...
4017 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004018 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004019 "moveTasksToFullscreenStack()");
4020 synchronized (mGlobalLock) {
4021 final long origId = Binder.clearCallingIdentity();
4022 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004023 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004024 if (stack != null){
4025 if (!stack.isActivityTypeStandardOrUndefined()) {
4026 throw new IllegalArgumentException(
4027 "You can't move tasks from non-standard stacks.");
4028 }
4029 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4030 }
4031 } finally {
4032 Binder.restoreCallingIdentity(origId);
4033 }
4034 }
4035 }
4036
4037 /**
4038 * Moves the top activity in the input stackId to the pinned stack.
4039 *
4040 * @param stackId Id of stack to move the top activity to pinned stack.
4041 * @param bounds Bounds to use for pinned stack.
4042 *
4043 * @return True if the top activity of the input stack was successfully moved to the pinned
4044 * stack.
4045 */
4046 @Override
4047 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004048 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004049 "moveTopActivityToPinnedStack()");
4050 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004051 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004052 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4053 + "Device doesn't support picture-in-picture mode");
4054 }
4055
4056 long ident = Binder.clearCallingIdentity();
4057 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004058 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004059 } finally {
4060 Binder.restoreCallingIdentity(ident);
4061 }
4062 }
4063 }
4064
4065 @Override
4066 public boolean isInMultiWindowMode(IBinder token) {
4067 final long origId = Binder.clearCallingIdentity();
4068 try {
4069 synchronized (mGlobalLock) {
4070 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4071 if (r == null) {
4072 return false;
4073 }
4074 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4075 return r.inMultiWindowMode();
4076 }
4077 } finally {
4078 Binder.restoreCallingIdentity(origId);
4079 }
4080 }
4081
4082 @Override
4083 public boolean isInPictureInPictureMode(IBinder token) {
4084 final long origId = Binder.clearCallingIdentity();
4085 try {
4086 synchronized (mGlobalLock) {
4087 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4088 }
4089 } finally {
4090 Binder.restoreCallingIdentity(origId);
4091 }
4092 }
4093
4094 private boolean isInPictureInPictureMode(ActivityRecord r) {
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004095 return r != null
4096 && r.getRootTask() != null
4097 && r.inPinnedWindowingMode()
4098 && r.getRootTask().isInStackLocked(r) != null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004099 }
4100
4101 @Override
4102 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4103 final long origId = Binder.clearCallingIdentity();
4104 try {
4105 synchronized (mGlobalLock) {
4106 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4107 "enterPictureInPictureMode", token, params);
4108
4109 // If the activity is already in picture in picture mode, then just return early
4110 if (isInPictureInPictureMode(r)) {
4111 return true;
4112 }
4113
4114 // Activity supports picture-in-picture, now check that we can enter PiP at this
4115 // point, if it is
4116 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4117 false /* beforeStopping */)) {
4118 return false;
4119 }
4120
4121 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004122 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004123 if (r.getParent() == null) {
4124 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4125 return;
4126 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004127 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004128 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004129 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4130 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4131 // Adjust the source bounds by the insets for the transition down
4132 final Rect sourceBounds = new Rect(
4133 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004134 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004135 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004136 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004137 stack.setPictureInPictureAspectRatio(aspectRatio);
4138 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004139 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4140 r.info.applicationInfo.uid, r.shortComponentName,
4141 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004142 logPictureInPictureArgs(params);
4143 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004144 };
4145
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004146 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004147 // If the keyguard is showing or occluded, then try and dismiss it before
4148 // entering picture-in-picture (this will prompt the user to authenticate if the
4149 // device is currently locked).
4150 dismissKeyguard(token, new KeyguardDismissCallback() {
4151 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004152 public void onDismissSucceeded() {
4153 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004154 }
4155 }, null /* message */);
4156 } else {
4157 // Enter picture in picture immediately otherwise
4158 enterPipRunnable.run();
4159 }
4160 return true;
4161 }
4162 } finally {
4163 Binder.restoreCallingIdentity(origId);
4164 }
4165 }
4166
4167 @Override
4168 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4169 final long origId = Binder.clearCallingIdentity();
4170 try {
4171 synchronized (mGlobalLock) {
4172 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4173 "setPictureInPictureParams", token, params);
4174
4175 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004176 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004177 if (r.inPinnedWindowingMode()) {
4178 // If the activity is already in picture-in-picture, update the pinned stack now
4179 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4180 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004181 final ActivityStack stack = r.getRootTask();
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004182 stack.setPictureInPictureAspectRatio(
4183 r.pictureInPictureArgs.getAspectRatio());
4184 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004185 }
4186 logPictureInPictureArgs(params);
4187 }
4188 } finally {
4189 Binder.restoreCallingIdentity(origId);
4190 }
4191 }
4192
4193 @Override
4194 public int getMaxNumPictureInPictureActions(IBinder token) {
4195 // Currently, this is a static constant, but later, we may change this to be dependent on
4196 // the context of the activity
4197 return 3;
4198 }
4199
4200 private void logPictureInPictureArgs(PictureInPictureParams params) {
4201 if (params.hasSetActions()) {
4202 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4203 params.getActions().size());
4204 }
4205 if (params.hasSetAspectRatio()) {
4206 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4207 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4208 MetricsLogger.action(lm);
4209 }
4210 }
4211
4212 /**
4213 * Checks the state of the system and the activity associated with the given {@param token} to
4214 * verify that picture-in-picture is supported for that activity.
4215 *
4216 * @return the activity record for the given {@param token} if all the checks pass.
4217 */
4218 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4219 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004220 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004221 throw new IllegalStateException(caller
4222 + ": Device doesn't support picture-in-picture mode.");
4223 }
4224
4225 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4226 if (r == null) {
4227 throw new IllegalStateException(caller
4228 + ": Can't find activity for token=" + token);
4229 }
4230
4231 if (!r.supportsPictureInPicture()) {
4232 throw new IllegalStateException(caller
4233 + ": Current activity does not support picture-in-picture.");
4234 }
4235
4236 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004237 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004238 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004239 final float minAspectRatio = mContext.getResources().getFloat(
4240 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4241 final float maxAspectRatio = mContext.getResources().getFloat(
4242 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4243 throw new IllegalArgumentException(String.format(caller
4244 + ": Aspect ratio is too extreme (must be between %f and %f).",
4245 minAspectRatio, maxAspectRatio));
4246 }
4247
4248 // Truncate the number of actions if necessary
4249 params.truncateActions(getMaxNumPictureInPictureActions(token));
4250
4251 return r;
4252 }
4253
4254 @Override
4255 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004256 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004257 synchronized (mGlobalLock) {
4258 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4259 if (r == null) {
4260 throw new IllegalArgumentException("Activity does not exist; token="
4261 + activityToken);
4262 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004263 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004264 }
4265 }
4266
Evan Rosky73a7fe92019-11-18 18:28:01 -08004267 // TODO(b/149338177): remove when CTS no-longer requires it
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004268 @Override
4269 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4270 Rect tempDockedTaskInsetBounds,
4271 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004272 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004273 long ident = Binder.clearCallingIdentity();
4274 try {
4275 synchronized (mGlobalLock) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08004276 final DisplayContent dc = mRootWindowContainer.getDefaultDisplay();
4277 TaskTile primary = null;
4278 TaskTile secondary = null;
4279 for (int i = dc.getStackCount() - 1; i >= 0; --i) {
4280 final TaskTile t = dc.getStackAt(i).asTile();
4281 if (t == null) {
4282 continue;
4283 }
4284 if (t.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
4285 primary = t;
4286 } else if (t.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY) {
4287 secondary = t;
4288 }
4289 }
4290 if (primary == null || secondary == null) {
4291 return;
4292 }
4293 final WindowContainerTransaction wct = new WindowContainerTransaction();
4294 final Rect primaryRect =
4295 tempDockedTaskInsetBounds != null ? tempDockedTaskInsetBounds
4296 : (tempDockedTaskBounds != null ? tempDockedTaskBounds
4297 : dockedBounds);
4298 wct.setBounds(primary.mRemoteToken, primaryRect);
4299 Rect otherRect = tempOtherTaskInsetBounds != null ? tempOtherTaskInsetBounds
4300 : tempOtherTaskBounds;
4301 if (otherRect == null) {
4302 // Temporary estimation... again this is just for tests.
4303 otherRect = new Rect(secondary.getBounds());
4304 if (dc.getBounds().width() > dc.getBounds().height()) {
4305 otherRect.left = primaryRect.right + 6;
4306 } else {
4307 otherRect.top = primaryRect.bottom + 6;
4308 }
4309 }
4310 wct.setBounds(secondary.mRemoteToken, otherRect);
4311 mTaskOrganizerController.applyContainerTransaction(wct, null /* organizer */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004312 }
4313 } finally {
4314 Binder.restoreCallingIdentity(ident);
4315 }
4316 }
4317
4318 @Override
4319 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004320 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004321 final long ident = Binder.clearCallingIdentity();
4322 try {
4323 synchronized (mGlobalLock) {
4324 mStackSupervisor.setSplitScreenResizing(resizing);
4325 }
4326 } finally {
4327 Binder.restoreCallingIdentity(ident);
4328 }
4329 }
4330
Evan Rosky0037e5f2019-11-05 10:26:24 -08004331 @Override
4332 public ITaskOrganizerController getTaskOrganizerController() {
4333 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
4334 "getTaskOrganizerController()");
4335 return mTaskOrganizerController;
4336 }
4337
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004338 /**
4339 * Check that we have the features required for VR-related API calls, and throw an exception if
4340 * not.
4341 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004342 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004343 if (!mContext.getPackageManager().hasSystemFeature(
4344 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4345 throw new UnsupportedOperationException("VR mode not supported on this device!");
4346 }
4347 }
4348
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004349 @Override
4350 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004351 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004352
4353 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4354
4355 ActivityRecord r;
4356 synchronized (mGlobalLock) {
4357 r = ActivityRecord.isInStackLocked(token);
4358 }
4359
4360 if (r == null) {
4361 throw new IllegalArgumentException();
4362 }
4363
4364 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004365 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004366 VrManagerInternal.NO_ERROR) {
4367 return err;
4368 }
4369
4370 // Clear the binder calling uid since this path may call moveToTask().
4371 final long callingId = Binder.clearCallingIdentity();
4372 try {
4373 synchronized (mGlobalLock) {
4374 r.requestedVrComponent = (enabled) ? packageName : null;
4375
4376 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004377 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004378 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004379 }
4380 return 0;
4381 }
4382 } finally {
4383 Binder.restoreCallingIdentity(callingId);
4384 }
4385 }
4386
4387 @Override
4388 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4389 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4390 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004391 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004392 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4393 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4394 }
Louis Changcdec0802019-11-11 11:45:07 +08004395 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004396 || activity.voiceSession != null) {
4397 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4398 return;
4399 }
4400 if (activity.pendingVoiceInteractionStart) {
4401 Slog.w(TAG, "Pending start of voice interaction already.");
4402 return;
4403 }
4404 activity.pendingVoiceInteractionStart = true;
4405 }
4406 LocalServices.getService(VoiceInteractionManagerInternal.class)
4407 .startLocalVoiceInteraction(callingActivity, options);
4408 }
4409
4410 @Override
4411 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4412 LocalServices.getService(VoiceInteractionManagerInternal.class)
4413 .stopLocalVoiceInteraction(callingActivity);
4414 }
4415
4416 @Override
4417 public boolean supportsLocalVoiceInteraction() {
4418 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4419 .supportsLocalVoiceInteraction();
4420 }
4421
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004422 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004423 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004424 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004425
4426 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004427 if (mWindowManager == null) {
4428 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4429 return false;
4430 }
4431
4432 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004433 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004434 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004435 }
4436
Riddle Hsua0022cd2019-09-09 21:12:41 +08004437 mH.sendMessage(PooledLambda.obtainMessage(
4438 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4439 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004440
4441 final long origId = Binder.clearCallingIdentity();
4442 try {
4443 if (values != null) {
4444 Settings.System.clearConfiguration(values);
4445 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004446 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004447 UserHandle.USER_NULL, false /* deferResume */,
4448 mTmpUpdateConfigurationResult);
4449 return mTmpUpdateConfigurationResult.changes != 0;
4450 } finally {
4451 Binder.restoreCallingIdentity(origId);
4452 }
4453 }
4454 }
4455
4456 @Override
4457 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4458 CharSequence message) {
4459 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004460 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004461 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4462 }
4463 final long callingId = Binder.clearCallingIdentity();
4464 try {
4465 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004466 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004467 }
4468 } finally {
4469 Binder.restoreCallingIdentity(callingId);
4470 }
4471 }
4472
4473 @Override
4474 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004475 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004476 "cancelTaskWindowTransition()");
4477 final long ident = Binder.clearCallingIdentity();
4478 try {
4479 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004480 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004481 MATCH_TASK_IN_STACKS_ONLY);
4482 if (task == null) {
4483 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4484 return;
4485 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004486 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004487 }
4488 } finally {
4489 Binder.restoreCallingIdentity(ident);
4490 }
4491 }
4492
4493 @Override
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004494 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004495 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004496 final long ident = Binder.clearCallingIdentity();
4497 try {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004498 return getTaskSnapshot(taskId, isLowResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004499 } finally {
4500 Binder.restoreCallingIdentity(ident);
4501 }
4502 }
4503
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004504 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004505 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004506 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004507 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004508 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004509 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4510 if (task == null) {
4511 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4512 return null;
4513 }
4514 }
4515 // Don't call this while holding the lock as this operation might hit the disk.
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004516 return task.getSnapshot(isLowResolution, restoreFromDisk);
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004517 }
4518
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004519 @Override
4520 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4521 synchronized (mGlobalLock) {
4522 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4523 if (r == null) {
4524 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4525 + token);
4526 return;
4527 }
4528 final long origId = Binder.clearCallingIdentity();
4529 try {
4530 r.setDisablePreviewScreenshots(disable);
4531 } finally {
4532 Binder.restoreCallingIdentity(origId);
4533 }
4534 }
4535 }
4536
Riddle Hsu440f88b2019-11-06 22:17:35 +08004537 @Override
4538 public void invalidateHomeTaskSnapshot(IBinder token) {
4539 synchronized (mGlobalLock) {
4540 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4541 if (r == null || !r.isActivityTypeHome()) {
4542 return;
4543 }
4544 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4545 }
4546 }
4547
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004548 /** Return the user id of the last resumed activity. */
4549 @Override
4550 public @UserIdInt
4551 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004552 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004553 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4554 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004555 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004556 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004557 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004558 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004559 }
4560 }
4561
4562 @Override
4563 public void updateLockTaskFeatures(int userId, int flags) {
4564 final int callingUid = Binder.getCallingUid();
4565 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004566 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004567 "updateLockTaskFeatures()");
4568 }
4569 synchronized (mGlobalLock) {
4570 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4571 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004572 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004573 }
4574 }
4575
4576 @Override
4577 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4578 synchronized (mGlobalLock) {
4579 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4580 if (r == null) {
4581 return;
4582 }
4583 final long origId = Binder.clearCallingIdentity();
4584 try {
4585 r.setShowWhenLocked(showWhenLocked);
4586 } finally {
4587 Binder.restoreCallingIdentity(origId);
4588 }
4589 }
4590 }
4591
4592 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004593 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4594 synchronized (mGlobalLock) {
4595 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4596 if (r == null) {
4597 return;
4598 }
4599 final long origId = Binder.clearCallingIdentity();
4600 try {
4601 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4602 } finally {
4603 Binder.restoreCallingIdentity(origId);
4604 }
4605 }
4606 }
4607
4608 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004609 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4610 synchronized (mGlobalLock) {
4611 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4612 if (r == null) {
4613 return;
4614 }
4615 final long origId = Binder.clearCallingIdentity();
4616 try {
4617 r.setTurnScreenOn(turnScreenOn);
4618 } finally {
4619 Binder.restoreCallingIdentity(origId);
4620 }
4621 }
4622 }
4623
4624 @Override
4625 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004626 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004627 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004628 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004629 synchronized (mGlobalLock) {
4630 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4631 if (r == null) {
4632 return;
4633 }
4634 final long origId = Binder.clearCallingIdentity();
4635 try {
4636 r.registerRemoteAnimations(definition);
4637 } finally {
4638 Binder.restoreCallingIdentity(origId);
4639 }
4640 }
4641 }
4642
4643 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004644 public void unregisterRemoteAnimations(IBinder token) {
4645 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4646 "unregisterRemoteAnimations");
4647 synchronized (mGlobalLock) {
4648 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4649 if (r == null) {
4650 return;
4651 }
4652 final long origId = Binder.clearCallingIdentity();
4653 try {
4654 r.unregisterRemoteAnimations();
4655 } finally {
4656 Binder.restoreCallingIdentity(origId);
4657 }
4658 }
4659 }
4660
4661 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004662 public void registerRemoteAnimationForNextActivityStart(String packageName,
4663 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004664 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004665 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004666 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004667 synchronized (mGlobalLock) {
4668 final long origId = Binder.clearCallingIdentity();
4669 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004670 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004671 packageName, adapter);
4672 } finally {
4673 Binder.restoreCallingIdentity(origId);
4674 }
4675 }
4676 }
4677
Evan Rosky966759f2019-01-15 10:33:58 -08004678 @Override
4679 public void registerRemoteAnimationsForDisplay(int displayId,
4680 RemoteAnimationDefinition definition) {
4681 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4682 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004683 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004684 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004685 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004686 if (display == null) {
4687 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4688 return;
4689 }
4690 final long origId = Binder.clearCallingIdentity();
4691 try {
4692 display.mDisplayContent.registerRemoteAnimations(definition);
4693 } finally {
4694 Binder.restoreCallingIdentity(origId);
4695 }
4696 }
4697 }
4698
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004699 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4700 @Override
4701 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4702 synchronized (mGlobalLock) {
4703 final long origId = Binder.clearCallingIdentity();
4704 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004705 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004706 } finally {
4707 Binder.restoreCallingIdentity(origId);
4708 }
4709 }
4710 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004711
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004712 @Override
4713 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004714 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004715 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004716 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004717 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004718 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004719 }
4720 }
4721
4722 @Override
4723 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004724 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004725 != PERMISSION_GRANTED) {
4726 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4727 + Binder.getCallingPid()
4728 + ", uid=" + Binder.getCallingUid()
4729 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4730 Slog.w(TAG, msg);
4731 throw new SecurityException(msg);
4732 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004733 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004734 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004735 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004736 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004737 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004738 }
4739 }
4740
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004741 @Override
4742 public void stopAppSwitches() {
4743 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4744 synchronized (mGlobalLock) {
4745 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004746 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004747 mDidAppSwitch = false;
4748 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4749 }
4750 }
4751
4752 @Override
4753 public void resumeAppSwitches() {
4754 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4755 synchronized (mGlobalLock) {
4756 // Note that we don't execute any pending app switches... we will
4757 // let those wait until either the timeout, or the next start
4758 // activity request.
4759 mAppSwitchesAllowedTime = 0;
4760 }
4761 }
4762
Ricky Wai906af482019-06-03 17:25:28 +01004763 long getLastStopAppSwitchesTime() {
4764 return mLastStopAppSwitchesTime;
4765 }
4766
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004767 void onStartActivitySetDidAppSwitch() {
4768 if (mDidAppSwitch) {
4769 // This is the second allowed switch since we stopped switches, so now just generally
4770 // allow switches. Use case:
4771 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4772 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4773 // anyone to switch again).
4774 mAppSwitchesAllowedTime = 0;
4775 } else {
4776 mDidAppSwitch = true;
4777 }
4778 }
4779
4780 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004781 boolean shouldDisableNonVrUiLocked() {
4782 return mVrController.shouldDisableNonVrUiLocked();
4783 }
4784
Wale Ogunwale53783742018-09-16 10:21:51 -07004785 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004786 // 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 +00004787 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004788 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004789 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4790 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004791 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004792 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004793 }
4794 mH.post(() -> {
4795 if (!mVrController.onVrModeChanged(r)) {
4796 return;
4797 }
4798 synchronized (mGlobalLock) {
4799 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4800 mWindowManager.disableNonVrUi(disableNonVrUi);
4801 if (disableNonVrUi) {
4802 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4803 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004804 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004805 }
4806 }
4807 });
4808 }
4809
Wale Ogunwale53783742018-09-16 10:21:51 -07004810 @Override
4811 public int getPackageScreenCompatMode(String packageName) {
4812 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4813 synchronized (mGlobalLock) {
4814 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4815 }
4816 }
4817
4818 @Override
4819 public void setPackageScreenCompatMode(String packageName, int mode) {
4820 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4821 "setPackageScreenCompatMode");
4822 synchronized (mGlobalLock) {
4823 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4824 }
4825 }
4826
4827 @Override
4828 public boolean getPackageAskScreenCompat(String packageName) {
4829 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4830 synchronized (mGlobalLock) {
4831 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4832 }
4833 }
4834
4835 @Override
4836 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4837 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4838 "setPackageAskScreenCompat");
4839 synchronized (mGlobalLock) {
4840 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4841 }
4842 }
4843
Wale Ogunwale64258362018-10-16 15:13:37 -07004844 public static String relaunchReasonToString(int relaunchReason) {
4845 switch (relaunchReason) {
4846 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4847 return "window_resize";
4848 case RELAUNCH_REASON_FREE_RESIZE:
4849 return "free_resize";
4850 default:
4851 return null;
4852 }
4853 }
4854
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004855 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004856 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004857 }
4858
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004859 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004860 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004861 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4862 }
4863
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004864 boolean isKeyguardLocked() {
4865 return mKeyguardController.isKeyguardLocked();
4866 }
4867
Garfield Tan01548632018-11-27 10:15:48 -08004868 /**
4869 * Clears launch params for the given package.
4870 * @param packageNames the names of the packages of which the launch params are to be cleared
4871 */
4872 @Override
4873 public void clearLaunchParamsForPackages(List<String> packageNames) {
4874 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4875 "clearLaunchParamsForPackages");
4876 synchronized (mGlobalLock) {
4877 for (int i = 0; i < packageNames.size(); ++i) {
4878 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4879 }
4880 }
4881 }
4882
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004883 /**
4884 * Makes the display with the given id a single task instance display. I.e the display can only
4885 * contain one task.
4886 */
4887 @Override
4888 public void setDisplayToSingleTaskInstance(int displayId) {
4889 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4890 "setDisplayToSingleTaskInstance");
4891 final long origId = Binder.clearCallingIdentity();
4892 try {
Louis Chang677921f2019-12-06 16:44:24 +08004893 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004894 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004895 if (display != null) {
4896 display.setDisplayToSingleTaskInstance();
4897 }
4898 } finally {
4899 Binder.restoreCallingIdentity(origId);
4900 }
4901 }
4902
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004903 /**
4904 * Requests that an activity should enter picture-in-picture mode if possible.
4905 */
4906 @Override
4907 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4908 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4909 "requestPictureInPictureMode");
4910 final long origId = Binder.clearCallingIdentity();
4911 try {
4912 synchronized (mGlobalLock) {
4913 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4914 if (activity == null) {
4915 return;
4916 }
4917
4918 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4919 "requestPictureInPictureMode", /* beforeStopping */ false);
4920 if (!canEnterPictureInPicture) {
4921 throw new IllegalStateException(
4922 "Requested PIP on an activity that doesn't support it");
4923 }
4924
4925 try {
4926 final ClientTransaction transaction = ClientTransaction.obtain(
4927 activity.app.getThread(),
4928 activity.token);
4929 transaction.addCallback(EnterPipRequestedItem.obtain());
4930 getLifecycleManager().scheduleTransaction(transaction);
4931 } catch (Exception e) {
4932 Slog.w(TAG, "Failed to send enter pip requested item: "
4933 + activity.intent.getComponent(), e);
4934 }
4935 }
4936 } finally {
4937 Binder.restoreCallingIdentity(origId);
4938 }
4939 }
4940
Wale Ogunwale31913b52018-10-13 08:29:31 -07004941 void dumpLastANRLocked(PrintWriter pw) {
4942 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4943 if (mLastANRState == null) {
4944 pw.println(" <no ANR has occurred since boot>");
4945 } else {
4946 pw.println(mLastANRState);
4947 }
4948 }
4949
4950 void dumpLastANRTracesLocked(PrintWriter pw) {
4951 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4952
4953 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4954 if (ArrayUtils.isEmpty(files)) {
4955 pw.println(" <no ANR has occurred since boot>");
4956 return;
4957 }
4958 // Find the latest file.
4959 File latest = null;
4960 for (File f : files) {
4961 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4962 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004963 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004964 }
4965 pw.print("File: ");
4966 pw.print(latest.getName());
4967 pw.println();
4968 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4969 String line;
4970 while ((line = in.readLine()) != null) {
4971 pw.println(line);
4972 }
4973 } catch (IOException e) {
4974 pw.print("Unable to read: ");
4975 pw.print(e);
4976 pw.println();
4977 }
4978 }
4979
4980 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4981 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4982 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4983 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4984 }
4985
4986 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4987 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4988 pw.println(header);
4989
Louis Chang149d5c82019-12-30 09:47:39 +08004990 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004991 dumpPackage);
4992 boolean needSep = printedAnything;
4993
4994 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08004995 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004996 " ResumedActivity: ");
4997 if (printed) {
4998 printedAnything = true;
4999 needSep = false;
5000 }
5001
5002 if (dumpPackage == null) {
5003 if (needSep) {
5004 pw.println();
5005 }
5006 printedAnything = true;
5007 mStackSupervisor.dump(pw, " ");
5008 }
5009
5010 if (!printedAnything) {
5011 pw.println(" (nothing)");
5012 }
5013 }
5014
5015 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005016 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005017 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005018 pw.println(" ");
5019 }
5020
5021 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5022 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5023 getActivityStartController().dump(pw, "", dumpPackage);
5024 }
5025
5026 /**
5027 * There are three things that cmd can be:
5028 * - a flattened component name that matches an existing activity
5029 * - the cmd arg isn't the flattened component name of an existing activity:
5030 * dump all activity whose component contains the cmd as a substring
5031 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005032 * <p>
5033 * The caller should not hold lock when calling this method because it will wait for the
5034 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005035 *
5036 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5037 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5038 */
5039 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5040 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5041 ArrayList<ActivityRecord> activities;
5042
5043 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005044 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005045 dumpFocusedStackOnly);
5046 }
5047
5048 if (activities.size() <= 0) {
5049 return false;
5050 }
5051
5052 String[] newArgs = new String[args.length - opti];
5053 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5054
Louis Changcdec0802019-11-11 11:45:07 +08005055 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005056 boolean needSep = false;
5057 for (int i = activities.size() - 1; i >= 0; i--) {
5058 ActivityRecord r = activities.get(i);
5059 if (needSep) {
5060 pw.println();
5061 }
5062 needSep = true;
5063 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005064 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005065 if (lastTask != task) {
5066 lastTask = task;
5067 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005068 pw.print(" id="); pw.print(lastTask.mTaskId);
5069 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005070 if (dumpAll) {
5071 lastTask.dump(pw, " ");
5072 }
5073 }
5074 }
5075 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5076 }
5077 return true;
5078 }
5079
5080 /**
5081 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5082 * there is a thread associated with the activity.
5083 */
5084 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5085 final ActivityRecord r, String[] args, boolean dumpAll) {
5086 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005087 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005088 synchronized (mGlobalLock) {
5089 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5090 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5091 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005092 if (r.hasProcess()) {
5093 pw.println(r.app.getPid());
5094 appThread = r.app.getThread();
5095 } else {
5096 pw.println("(not running)");
5097 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005098 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005099 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005100 }
5101 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005102 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005103 // flush anything that is already in the PrintWriter since the thread is going
5104 // to write to the file descriptor directly
5105 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005106 try (TransferPipe tp = new TransferPipe()) {
5107 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5108 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005109 } catch (IOException e) {
5110 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5111 } catch (RemoteException e) {
5112 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5113 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005114 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005115 }
5116
sanryhuang498e77e2018-12-06 14:57:01 +08005117 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5118 boolean testPssMode) {
5119 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5120 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5121 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005122 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005123 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5124 st.toString());
5125 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005126 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5127 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5128 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005129 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5130 testPssMode);
5131 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005132 }
5133
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005134 int getCurrentUserId() {
5135 return mAmInternal.getCurrentUserId();
5136 }
5137
5138 private void enforceNotIsolatedCaller(String caller) {
5139 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5140 throw new SecurityException("Isolated process not allowed to call " + caller);
5141 }
5142 }
5143
Wale Ogunwalef6733932018-06-27 05:14:34 -07005144 public Configuration getConfiguration() {
5145 Configuration ci;
5146 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005147 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005148 ci.userSetLocale = false;
5149 }
5150 return ci;
5151 }
5152
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005153 /**
5154 * Current global configuration information. Contains general settings for the entire system,
5155 * also corresponds to the merged configuration of the default display.
5156 */
5157 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005158 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005159 // while initializing process record for system, see {@link
5160 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005161 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005162 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005163 }
5164
5165 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5166 boolean initLocale) {
5167 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5168 }
5169
5170 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5171 boolean initLocale, boolean deferResume) {
5172 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5173 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5174 UserHandle.USER_NULL, deferResume);
5175 }
5176
Wale Ogunwale59507092018-10-29 09:00:30 -07005177 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005178 final long origId = Binder.clearCallingIdentity();
5179 try {
5180 synchronized (mGlobalLock) {
5181 updateConfigurationLocked(values, null, false, true, userId,
5182 false /* deferResume */);
5183 }
5184 } finally {
5185 Binder.restoreCallingIdentity(origId);
5186 }
5187 }
5188
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005189 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5190 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5191 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5192 deferResume, null /* result */);
5193 }
5194
5195 /**
5196 * Do either or both things: (1) change the current configuration, and (2)
5197 * make sure the given activity is running with the (now) current
5198 * configuration. Returns true if the activity has been left running, or
5199 * false if <var>starting</var> is being destroyed to match the new
5200 * configuration.
5201 *
5202 * @param userId is only used when persistent parameter is set to true to persist configuration
5203 * for that particular user
5204 */
5205 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5206 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5207 ActivityTaskManagerService.UpdateConfigurationResult result) {
5208 int changes = 0;
5209 boolean kept = true;
5210
Riddle Hsua0022cd2019-09-09 21:12:41 +08005211 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005212 try {
5213 if (values != null) {
5214 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5215 deferResume);
5216 }
5217
5218 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5219 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005220 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005221 }
5222
5223 if (result != null) {
5224 result.changes = changes;
5225 result.activityRelaunched = !kept;
5226 }
5227 return kept;
5228 }
5229
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005230 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005231 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005232 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005233
Louis Chang677921f2019-12-06 16:44:24 +08005234 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005235 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005236
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005237 mTempConfig.setTo(getGlobalConfiguration());
5238 final int changes = mTempConfig.updateFrom(values);
5239 if (changes == 0) {
5240 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5241 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5242 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5243 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005244 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005245 return 0;
5246 }
5247
5248 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5249 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005250 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005251 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005252 values.colorMode,
5253 values.densityDpi,
5254 values.fontScale,
5255 values.hardKeyboardHidden,
5256 values.keyboard,
5257 values.keyboardHidden,
5258 values.mcc,
5259 values.mnc,
5260 values.navigation,
5261 values.navigationHidden,
5262 values.orientation,
5263 values.screenHeightDp,
5264 values.screenLayout,
5265 values.screenWidthDp,
5266 values.smallestScreenWidthDp,
5267 values.touchscreen,
5268 values.uiMode);
5269
5270
5271 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5272 final LocaleList locales = values.getLocales();
5273 int bestLocaleIndex = 0;
5274 if (locales.size() > 1) {
5275 if (mSupportedSystemLocales == null) {
5276 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5277 }
5278 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5279 }
5280 SystemProperties.set("persist.sys.locale",
5281 locales.get(bestLocaleIndex).toLanguageTag());
5282 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005283
5284 final Message m = PooledLambda.obtainMessage(
5285 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5286 locales.get(bestLocaleIndex));
5287 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005288 }
5289
Yunfan Chen75157d72018-07-27 14:47:21 +09005290 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005291
5292 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005293 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005294
5295 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5296 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005297 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005298
5299 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005300 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005301
5302 AttributeCache ac = AttributeCache.instance();
5303 if (ac != null) {
5304 ac.updateConfiguration(mTempConfig);
5305 }
5306
5307 // Make sure all resources in our process are updated right now, so that anyone who is going
5308 // to retrieve resource values after we return will be sure to get the new ones. This is
5309 // especially important during boot, where the first config change needs to guarantee all
5310 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005311 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005312
5313 // We need another copy of global config because we're scheduling some calls instead of
5314 // running them in place. We need to be sure that object we send will be handled unchanged.
5315 final Configuration configCopy = new Configuration(mTempConfig);
5316 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005317 final Message msg = PooledLambda.obtainMessage(
5318 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5319 this, userId, configCopy);
5320 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005321 }
5322
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005323 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5324 for (int i = pidMap.size() - 1; i >= 0; i--) {
5325 final int pid = pidMap.keyAt(i);
5326 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005327 if (DEBUG_CONFIGURATION) {
5328 Slog.v(TAG_CONFIGURATION, "Update process config of "
5329 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005330 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005331 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005332 }
5333
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005334 final Message msg = PooledLambda.obtainMessage(
5335 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5336 mAmInternal, changes, initLocale);
5337 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005338
5339 // Override configuration of the default display duplicates global config, so we need to
5340 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005341 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005342 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005343
5344 return changes;
5345 }
5346
Riddle Hsua0022cd2019-09-09 21:12:41 +08005347 /** @see WindowSurfacePlacer#deferLayout */
5348 void deferWindowLayout() {
5349 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5350 // Reset the reasons at the first entrance because we only care about the changes in the
5351 // deferred scope.
5352 mLayoutReasons = 0;
5353 }
5354
5355 mWindowManager.mWindowPlacerLocked.deferLayout();
5356 }
5357
5358 /** @see WindowSurfacePlacer#continueLayout */
5359 void continueWindowLayout() {
5360 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5361 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5362 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5363 }
5364 }
5365
5366 /**
5367 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5368 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5369 * defer count is gone.
5370 */
5371 void addWindowLayoutReasons(@LayoutReason int reasons) {
5372 mLayoutReasons |= reasons;
5373 }
5374
Wale Ogunwalef6733932018-06-27 05:14:34 -07005375 private void updateEventDispatchingLocked(boolean booted) {
5376 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5377 }
5378
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005379 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5380 final ContentResolver resolver = mContext.getContentResolver();
5381 Settings.System.putConfigurationForUser(resolver, config, userId);
5382 }
5383
5384 private void sendLocaleToMountDaemonMsg(Locale l) {
5385 try {
5386 IBinder service = ServiceManager.getService("mount");
5387 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5388 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5389 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5390 } catch (RemoteException e) {
5391 Log.e(TAG, "Error storing locale for decryption UI", e);
5392 }
5393 }
5394
Alison Cichowlas3e340502018-08-07 17:15:01 -04005395 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5396 mStartActivitySources.remove(permissionToken);
5397 mExpiredStartAsCallerTokens.add(permissionToken);
5398 }
5399
5400 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5401 mExpiredStartAsCallerTokens.remove(permissionToken);
5402 }
5403
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005404 boolean isActivityStartsLoggingEnabled() {
5405 return mAmInternal.isActivityStartsLoggingEnabled();
5406 }
5407
Michal Karpinski8596ded2018-11-14 14:43:48 +00005408 boolean isBackgroundActivityStartsEnabled() {
5409 return mAmInternal.isBackgroundActivityStartsEnabled();
5410 }
5411
Wale Ogunwalef6733932018-06-27 05:14:34 -07005412 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005413 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005414 mWindowManager.enableScreenAfterBoot();
5415
5416 synchronized (mGlobalLock) {
5417 updateEventDispatchingLocked(booted);
5418 }
5419 }
5420
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005421 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5422 if (r == null || !r.hasProcess()) {
5423 return KEY_DISPATCHING_TIMEOUT_MS;
5424 }
5425 return getInputDispatchingTimeoutLocked(r.app);
5426 }
5427
5428 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005429 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005430 }
5431
Wale Ogunwalef6733932018-06-27 05:14:34 -07005432 /**
5433 * Decide based on the configuration whether we should show the ANR,
5434 * crash, etc dialogs. The idea is that if there is no affordance to
5435 * press the on-screen buttons, or the user experience would be more
5436 * greatly impacted than the crash itself, we shouldn't show the dialog.
5437 *
5438 * A thought: SystemUI might also want to get told about this, the Power
5439 * dialog / global actions also might want different behaviors.
5440 */
5441 private void updateShouldShowDialogsLocked(Configuration config) {
5442 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5443 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5444 && config.navigation == Configuration.NAVIGATION_NONAV);
5445 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5446 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5447 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5448 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5449 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5450 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5451 HIDE_ERROR_DIALOGS, 0) != 0;
5452 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5453 }
5454
5455 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5456 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5457 FONT_SCALE, 1.0f, userId);
5458
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005459 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005460 if (getGlobalConfiguration().fontScale == scaleFactor) {
5461 return;
5462 }
5463
5464 final Configuration configuration
5465 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5466 configuration.fontScale = scaleFactor;
5467 updatePersistentConfiguration(configuration, userId);
5468 }
5469 }
5470
5471 // Actually is sleeping or shutting down or whatever else in the future
5472 // is an inactive state.
5473 boolean isSleepingOrShuttingDownLocked() {
5474 return isSleepingLocked() || mShuttingDown;
5475 }
5476
5477 boolean isSleepingLocked() {
5478 return mSleeping;
5479 }
5480
Riddle Hsu16567132018-08-16 21:37:47 +08005481 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005482 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005483 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005484 if (task.isActivityTypeStandard()) {
5485 if (mCurAppTimeTracker != r.appTimeTracker) {
5486 // We are switching app tracking. Complete the current one.
5487 if (mCurAppTimeTracker != null) {
5488 mCurAppTimeTracker.stop();
5489 mH.obtainMessage(
5490 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005491 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005492 mCurAppTimeTracker = null;
5493 }
5494 if (r.appTimeTracker != null) {
5495 mCurAppTimeTracker = r.appTimeTracker;
5496 startTimeTrackingFocusedActivityLocked();
5497 }
5498 } else {
5499 startTimeTrackingFocusedActivityLocked();
5500 }
5501 } else {
5502 r.appTimeTracker = null;
5503 }
5504 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5505 // TODO: Probably not, because we don't want to resume voice on switching
5506 // back to this activity
5507 if (task.voiceInteractor != null) {
5508 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5509 } else {
5510 finishRunningVoiceLocked();
5511
5512 if (mLastResumedActivity != null) {
5513 final IVoiceInteractionSession session;
5514
Louis Changcdec0802019-11-11 11:45:07 +08005515 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005516 if (lastResumedActivityTask != null
5517 && lastResumedActivityTask.voiceSession != null) {
5518 session = lastResumedActivityTask.voiceSession;
5519 } else {
5520 session = mLastResumedActivity.voiceSession;
5521 }
5522
5523 if (session != null) {
5524 // We had been in a voice interaction session, but now focused has
5525 // move to something different. Just finish the session, we can't
5526 // return to it and retain the proper state and synchronization with
5527 // the voice interaction service.
5528 finishVoiceTask(session);
5529 }
5530 }
5531 }
5532
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005533 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5534 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005535 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005536 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5537
Wale Ogunwalef6733932018-06-27 05:14:34 -07005538 updateResumedAppTrace(r);
5539 mLastResumedActivity = r;
5540
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005541 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005542
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005543 if (prevTask == null || task != prevTask) {
5544 if (prevTask != null) {
5545 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5546 }
5547 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5548 }
5549
Wale Ogunwalef6733932018-06-27 05:14:34 -07005550 applyUpdateLockStateLocked(r);
5551 applyUpdateVrModeLocked(r);
5552
Jeff Changd136e772019-11-05 20:33:52 +08005553 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005554 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005555 r == null ? "NULL" : r.shortComponentName,
5556 reason);
5557 }
5558
5559 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5560 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005561 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005562 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005563 updateSleepIfNeededLocked();
5564 return token;
5565 }
5566 }
5567
5568 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005569 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005570 final boolean wasSleeping = mSleeping;
5571 boolean updateOomAdj = false;
5572
5573 if (!shouldSleep) {
5574 // If wasSleeping is true, we need to wake up activity manager state from when
5575 // we started sleeping. In either case, we need to apply the sleep tokens, which
5576 // will wake up stacks or put them to sleep as appropriate.
5577 if (wasSleeping) {
5578 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005579 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5580 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005581 startTimeTrackingFocusedActivityLocked();
5582 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005583 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005584 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5585 }
Louis Chang149d5c82019-12-30 09:47:39 +08005586 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005587 if (wasSleeping) {
5588 updateOomAdj = true;
5589 }
5590 } else if (!mSleeping && shouldSleep) {
5591 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005592 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5593 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005594 if (mCurAppTimeTracker != null) {
5595 mCurAppTimeTracker.stop();
5596 }
5597 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005598 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005599 mStackSupervisor.goingToSleepLocked();
5600 updateResumedAppTrace(null /* resumed */);
5601 updateOomAdj = true;
5602 }
5603 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005604 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005605 }
5606 }
5607
5608 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005609 mH.removeCallbacks(mUpdateOomAdjRunnable);
5610 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005611 }
5612
Wale Ogunwale53783742018-09-16 10:21:51 -07005613 void updateCpuStats() {
5614 mH.post(mAmInternal::updateCpuStats);
5615 }
5616
Hui Yu03d12402018-12-06 18:00:37 -08005617 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5618 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005619 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5620 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005621 mH.sendMessage(m);
5622 }
5623
Hui Yu03d12402018-12-06 18:00:37 -08005624 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005625 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005626 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005627 if (task != null) {
5628 final ActivityRecord rootActivity = task.getRootActivity();
5629 if (rootActivity != null) {
5630 taskRoot = rootActivity.mActivityComponent;
5631 }
5632 }
5633
Hui Yu03d12402018-12-06 18:00:37 -08005634 final Message m = PooledLambda.obtainMessage(
5635 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005636 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005637 mH.sendMessage(m);
5638 }
5639
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005640 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5641 String hostingType) {
5642 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005643 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5644 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005645 + activity.processName);
5646 }
5647 // Post message to start process to avoid possible deadlock of calling into AMS with the
5648 // ATMS lock held.
5649 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5650 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5651 isTop, hostingType, activity.intent.getComponent());
5652 mH.sendMessage(m);
5653 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005654 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005655 }
5656 }
5657
Wale Ogunwale53783742018-09-16 10:21:51 -07005658 void setBooting(boolean booting) {
5659 mAmInternal.setBooting(booting);
5660 }
5661
5662 boolean isBooting() {
5663 return mAmInternal.isBooting();
5664 }
5665
5666 void setBooted(boolean booted) {
5667 mAmInternal.setBooted(booted);
5668 }
5669
5670 boolean isBooted() {
5671 return mAmInternal.isBooted();
5672 }
5673
5674 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5675 mH.post(() -> {
5676 if (finishBooting) {
5677 mAmInternal.finishBooting();
5678 }
5679 if (enableScreen) {
5680 mInternal.enableScreenAfterBoot(isBooted());
5681 }
5682 });
5683 }
5684
5685 void setHeavyWeightProcess(ActivityRecord root) {
5686 mHeavyWeightProcess = root.app;
5687 final Message m = PooledLambda.obtainMessage(
5688 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005689 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005690 mH.sendMessage(m);
5691 }
5692
5693 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5694 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5695 return;
5696 }
5697
5698 mHeavyWeightProcess = null;
5699 final Message m = PooledLambda.obtainMessage(
5700 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5701 proc.mUserId);
5702 mH.sendMessage(m);
5703 }
5704
5705 private void cancelHeavyWeightProcessNotification(int userId) {
5706 final INotificationManager inm = NotificationManager.getService();
5707 if (inm == null) {
5708 return;
5709 }
5710 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005711 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005712 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5713 } catch (RuntimeException e) {
5714 Slog.w(TAG, "Error canceling notification for service", e);
5715 } catch (RemoteException e) {
5716 }
5717
5718 }
5719
5720 private void postHeavyWeightProcessNotification(
5721 WindowProcessController proc, Intent intent, int userId) {
5722 if (proc == null) {
5723 return;
5724 }
5725
5726 final INotificationManager inm = NotificationManager.getService();
5727 if (inm == null) {
5728 return;
5729 }
5730
5731 try {
5732 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5733 String text = mContext.getString(R.string.heavy_weight_notification,
5734 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5735 Notification notification =
5736 new Notification.Builder(context,
5737 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5738 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5739 .setWhen(0)
5740 .setOngoing(true)
5741 .setTicker(text)
5742 .setColor(mContext.getColor(
5743 com.android.internal.R.color.system_notification_accent_color))
5744 .setContentTitle(text)
5745 .setContentText(
5746 mContext.getText(R.string.heavy_weight_notification_detail))
5747 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5748 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5749 new UserHandle(userId)))
5750 .build();
5751 try {
5752 inm.enqueueNotificationWithTag("android", "android", null,
5753 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5754 } catch (RuntimeException e) {
5755 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5756 } catch (RemoteException e) {
5757 }
5758 } catch (PackageManager.NameNotFoundException e) {
5759 Slog.w(TAG, "Unable to create context for heavy notification", e);
5760 }
5761
5762 }
5763
Philip P. Moltmannee295092020-02-10 08:46:26 -08005764 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5765 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5766 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005767
5768 ActivityRecord activity = null;
5769 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5770 activity = ActivityRecord.isInStackLocked(token);
5771 if (activity == null) {
5772 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5773 return null;
5774 }
5775 if (activity.finishing) {
5776 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5777 return null;
5778 }
5779 }
5780
5781 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005782 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5783 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005784 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5785 if (noCreate) {
5786 return rec;
5787 }
5788 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5789 if (activity.pendingResults == null) {
5790 activity.pendingResults = new HashSet<>();
5791 }
5792 activity.pendingResults.add(rec.ref);
5793 }
5794 return rec;
5795 }
5796
Andrii Kulian52d255c2018-07-13 11:32:19 -07005797 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005798 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005799 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005800 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5801 mCurAppTimeTracker.start(resumedActivity.packageName);
5802 }
5803 }
5804
5805 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5806 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005807 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005808 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5809 }
5810 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005811 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005812 constructResumedTraceName(resumed.packageName), 0);
5813 }
5814 mTracedResumedActivity = resumed;
5815 }
5816
5817 private String constructResumedTraceName(String packageName) {
5818 return "focused app: " + packageName;
5819 }
5820
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005821 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005822 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005823 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005824 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005825 // mainStack is null during startup.
5826 if (mainStack != null) {
5827 if (changes != 0 && starting == null) {
5828 // If the configuration changed, and the caller is not already
5829 // in the process of starting an activity, then find the top
5830 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005831 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005832 }
5833
5834 if (starting != null) {
5835 kept = starting.ensureActivityConfiguration(changes,
5836 false /* preserveWindow */);
5837 // And we need to make sure at this point that all other activities
5838 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005839 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005840 !PRESERVE_WINDOWS);
5841 }
5842 }
5843
5844 return kept;
5845 }
5846
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005847 void scheduleAppGcsLocked() {
5848 mH.post(() -> mAmInternal.scheduleAppGcs());
5849 }
5850
Wale Ogunwale53783742018-09-16 10:21:51 -07005851 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5852 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5853 }
5854
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005855 /**
5856 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5857 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5858 * on demand.
5859 */
5860 IPackageManager getPackageManager() {
5861 return AppGlobals.getPackageManager();
5862 }
5863
5864 PackageManagerInternal getPackageManagerInternalLocked() {
5865 if (mPmInternal == null) {
5866 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5867 }
5868 return mPmInternal;
5869 }
5870
Hai Zhangf4da9be2019-05-01 13:46:06 +08005871 PermissionPolicyInternal getPermissionPolicyInternal() {
5872 if (mPermissionPolicyInternal == null) {
5873 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5874 }
5875 return mPermissionPolicyInternal;
5876 }
5877
Wale Ogunwale008163e2018-07-23 23:11:08 -07005878 AppWarnings getAppWarningsLocked() {
5879 return mAppWarnings;
5880 }
5881
Wale Ogunwale214f3482018-10-04 11:00:47 -07005882 Intent getHomeIntent() {
5883 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5884 intent.setComponent(mTopComponent);
5885 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5886 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5887 intent.addCategory(Intent.CATEGORY_HOME);
5888 }
5889 return intent;
5890 }
5891
Chilun2ef71f72018-11-16 17:57:15 +08005892 /**
5893 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5894 * activities.
5895 *
Chilun939b05c2020-02-19 14:50:59 +08005896 * @param preferredPackage Specify a preferred package name, otherwise use the package name
5897 * defined in config_secondaryHomePackage.
Chilun2ef71f72018-11-16 17:57:15 +08005898 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5899 */
5900 Intent getSecondaryHomeIntent(String preferredPackage) {
5901 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005902 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5903 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5904 if (preferredPackage == null || useSystemProvidedLauncher) {
Chilun939b05c2020-02-19 14:50:59 +08005905 // Using the package name stored in config if no preferred package name or forced.
5906 final String secondaryHomePackage = mContext.getResources().getString(
5907 com.android.internal.R.string.config_secondaryHomePackage);
5908 intent.setPackage(secondaryHomePackage);
Chilun2ef71f72018-11-16 17:57:15 +08005909 } else {
5910 intent.setPackage(preferredPackage);
5911 }
5912 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5913 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5914 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5915 }
5916 return intent;
5917 }
5918
Wale Ogunwale214f3482018-10-04 11:00:47 -07005919 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5920 if (info == null) return null;
5921 ApplicationInfo newInfo = new ApplicationInfo(info);
5922 newInfo.initForUser(userId);
5923 return newInfo;
5924 }
5925
Wale Ogunwale9c103022018-10-18 07:44:54 -07005926 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005927 if (uid == SYSTEM_UID) {
5928 // The system gets to run in any process. If there are multiple processes with the same
5929 // uid, just pick the first (this should never happen).
5930 final SparseArray<WindowProcessController> procs =
5931 mProcessNames.getMap().get(processName);
5932 if (procs == null) return null;
5933 final int procCount = procs.size();
5934 for (int i = 0; i < procCount; i++) {
5935 final int procUid = procs.keyAt(i);
5936 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5937 // Don't use an app process or different user process for system component.
5938 continue;
5939 }
5940 return procs.valueAt(i);
5941 }
5942 }
5943
5944 return mProcessNames.get(processName, uid);
5945 }
5946
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005947 WindowProcessController getProcessController(IApplicationThread thread) {
5948 if (thread == null) {
5949 return null;
5950 }
5951
5952 final IBinder threadBinder = thread.asBinder();
5953 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5954 for (int i = pmap.size()-1; i >= 0; i--) {
5955 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5956 for (int j = procs.size() - 1; j >= 0; j--) {
5957 final WindowProcessController proc = procs.valueAt(j);
5958 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5959 return proc;
5960 }
5961 }
5962 }
5963
5964 return null;
5965 }
5966
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005967 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005968 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005969 if (proc == null) return null;
5970 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5971 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005972 }
5973 return null;
5974 }
5975
Riddle Hsua0536432019-02-16 00:38:59 +08005976 int getUidState(int uid) {
5977 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005978 }
5979
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005980 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005981 // A uid is considered to be foreground if it has a visible non-toast window.
5982 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005983 }
5984
Ricky Wai96f5c352019-04-10 18:40:17 +01005985 boolean isDeviceOwner(int uid) {
5986 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005987 }
5988
Ricky Wai96f5c352019-04-10 18:40:17 +01005989 void setDeviceOwnerUid(int uid) {
5990 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005991 }
5992
Wale Ogunwale9de19442018-10-18 19:05:03 -07005993 /**
5994 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5995 * the whitelist
5996 */
5997 String getPendingTempWhitelistTagForUidLocked(int uid) {
5998 return mPendingTempWhitelist.get(uid);
5999 }
6000
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006001 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6002 if (true || Build.IS_USER) {
6003 return;
6004 }
6005
6006 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6007 StrictMode.allowThreadDiskWrites();
6008 try {
6009 File tracesDir = new File("/data/anr");
6010 File tracesFile = null;
6011 try {
6012 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6013
6014 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006015 String timeString =
6016 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6017 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006018 sb.append(": ");
6019 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6020 sb.append(" since ");
6021 sb.append(msg);
6022 FileOutputStream fos = new FileOutputStream(tracesFile);
6023 fos.write(sb.toString().getBytes());
6024 if (app == null) {
6025 fos.write("\n*** No application process!".getBytes());
6026 }
6027 fos.close();
6028 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6029 } catch (IOException e) {
6030 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6031 return;
6032 }
6033
6034 if (app != null && app.getPid() > 0) {
6035 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6036 firstPids.add(app.getPid());
6037 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6038 }
6039
6040 File lastTracesFile = null;
6041 File curTracesFile = null;
6042 for (int i=9; i>=0; i--) {
6043 String name = String.format(Locale.US, "slow%02d.txt", i);
6044 curTracesFile = new File(tracesDir, name);
6045 if (curTracesFile.exists()) {
6046 if (lastTracesFile != null) {
6047 curTracesFile.renameTo(lastTracesFile);
6048 } else {
6049 curTracesFile.delete();
6050 }
6051 }
6052 lastTracesFile = curTracesFile;
6053 }
6054 tracesFile.renameTo(curTracesFile);
6055 } finally {
6056 StrictMode.setThreadPolicy(oldPolicy);
6057 }
6058 }
6059
Michal Karpinskida34cd42019-04-02 19:46:52 +01006060 boolean isAssociatedCompanionApp(int userId, int uid) {
6061 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6062 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006063 return false;
6064 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006065 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006066 }
6067
Issei Suzuki734bc942019-06-05 13:59:52 +02006068 void notifySingleTaskDisplayEmpty(int displayId) {
6069 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6070 }
6071
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006072 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006073 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006074
6075
Wale Ogunwale98875612018-10-12 07:53:02 -07006076 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6077 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006078
Riddle Hsud93a6c42018-11-29 21:50:06 +08006079 H(Looper looper) {
6080 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006081 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006082
6083 @Override
6084 public void handleMessage(Message msg) {
6085 switch (msg.what) {
6086 case REPORT_TIME_TRACKER_MSG: {
6087 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6088 tracker.deliverResult(mContext);
6089 } break;
6090 }
6091 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006092 }
6093
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006094 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006095 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006096
6097 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006098 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006099 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006100
6101 @Override
6102 public void handleMessage(Message msg) {
6103 switch (msg.what) {
6104 case DISMISS_DIALOG_UI_MSG: {
6105 final Dialog d = (Dialog) msg.obj;
6106 d.dismiss();
6107 break;
6108 }
6109 }
6110 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006111 }
6112
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006113 final class LocalService extends ActivityTaskManagerInternal {
6114 @Override
6115 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006116 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006117 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006118 }
6119
6120 @Override
6121 public ComponentName getHomeActivityForUser(int userId) {
6122 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006123 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006124 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006125 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006126 }
6127 }
6128
6129 @Override
6130 public void onLocalVoiceInteractionStarted(IBinder activity,
6131 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6132 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006133 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006134 }
6135 }
6136
6137 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006138 public void notifySingleTaskDisplayDrawn(int displayId) {
6139 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6140 }
6141
6142 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006143 public void notifyAppTransitionFinished() {
6144 synchronized (mGlobalLock) {
6145 mStackSupervisor.notifyAppTransitionDone();
6146 }
6147 }
6148
6149 @Override
6150 public void notifyAppTransitionCancelled() {
6151 synchronized (mGlobalLock) {
6152 mStackSupervisor.notifyAppTransitionDone();
6153 }
6154 }
6155
6156 @Override
6157 public List<IBinder> getTopVisibleActivities() {
6158 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006159 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006160 }
6161 }
6162
6163 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006164 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6165 int userId, Intent[] intents, Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006166 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006167 final String[] resolvedTypes = new String[intents.length];
6168
6169 // UID of the package on user userId.
6170 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6171 // packageUid may not be initialized.
6172 int packageUid = 0;
6173 final long ident = Binder.clearCallingIdentity();
6174
6175 try {
6176 for (int i = 0; i < intents.length; i++) {
6177 resolvedTypes[i] =
6178 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6179 }
6180
6181 packageUid = AppGlobals.getPackageManager().getPackageUid(
6182 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6183 } catch (RemoteException e) {
6184 // Shouldn't happen.
6185 } finally {
6186 Binder.restoreCallingIdentity(ident);
6187 }
6188
Riddle Hsu591bf612019-02-14 17:55:31 +08006189 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006190 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006191 intents, resolvedTypes, null /* resultTo */,
6192 SafeActivityOptions.fromBundle(bOptions), userId,
6193 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6194 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006195 }
6196
6197 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006198 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006199 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6200 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6201 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006202 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006203 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006204 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006205 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006206 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6207 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006208 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006209 }
6210 }
6211
6212 @Override
6213 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006214 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6215 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6216 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6217 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006218 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006219 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006220 synchronized (mGlobalLock) {
6221 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006222 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6223 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6224 reason, validateIncomingUser, originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006225 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006226 }
6227 }
6228
6229 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006230 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006231 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6232 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006233 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006234 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006235 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006236 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006237 false /*validateIncomingUser*/);
6238 }
6239
6240 @Override
lumark588a3e82018-07-20 18:53:54 +08006241 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006242 synchronized (mGlobalLock) {
6243
6244 // We might change the visibilities here, so prepare an empty app transition which
6245 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006246 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006247 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006248 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006249 return;
6250 }
Louis Chang677921f2019-12-06 16:44:24 +08006251 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006252 final boolean wasTransitionSet =
6253 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006254 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006255 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006256 }
Louis Chang149d5c82019-12-30 09:47:39 +08006257 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006258
6259 // If there was a transition set already we don't want to interfere with it as we
6260 // might be starting it too early.
6261 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006262 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006263 }
6264 }
6265 if (callback != null) {
6266 callback.run();
6267 }
6268 }
6269
6270 @Override
6271 public void notifyKeyguardTrustedChanged() {
6272 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006273 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006274 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006275 }
6276 }
6277 }
6278
6279 /**
6280 * Called after virtual display Id is updated by
6281 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6282 * {@param vrVr2dDisplayId}.
6283 */
6284 @Override
6285 public void setVr2dDisplayId(int vr2dDisplayId) {
6286 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6287 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006288 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006289 }
6290 }
6291
6292 @Override
6293 public void setFocusedActivity(IBinder token) {
6294 synchronized (mGlobalLock) {
6295 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6296 if (r == null) {
6297 throw new IllegalArgumentException(
6298 "setFocusedActivity: No activity record matching token=" + token);
6299 }
Louis Chang19443452018-10-09 12:10:21 +08006300 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006301 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006302 }
6303 }
6304 }
6305
6306 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006307 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006308 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006309 }
6310
6311 @Override
6312 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006313 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006314 }
6315
6316 @Override
6317 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006318 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006319 }
6320
6321 @Override
6322 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6323 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6324 }
6325
6326 @Override
6327 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006328 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006329 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006330
6331 @Override
6332 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6333 synchronized (mGlobalLock) {
6334 mActiveVoiceInteractionServiceComponent = component;
6335 }
6336 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006337
6338 @Override
6339 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6340 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6341 return;
6342 }
6343 synchronized (mGlobalLock) {
6344 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6345 if (types == null) {
6346 if (uid < 0) {
6347 return;
6348 }
6349 types = new ArrayMap<>();
6350 mAllowAppSwitchUids.put(userId, types);
6351 }
6352 if (uid < 0) {
6353 types.remove(type);
6354 } else {
6355 types.put(type, uid);
6356 }
6357 }
6358 }
6359
6360 @Override
6361 public void onUserStopped(int userId) {
6362 synchronized (mGlobalLock) {
6363 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6364 mAllowAppSwitchUids.remove(userId);
6365 }
6366 }
6367
6368 @Override
6369 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6370 synchronized (mGlobalLock) {
6371 return ActivityTaskManagerService.this.isGetTasksAllowed(
6372 caller, callingPid, callingUid);
6373 }
6374 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006375
Riddle Hsua0536432019-02-16 00:38:59 +08006376 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006377 @Override
6378 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006379 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006380 mProcessNames.put(proc.mName, proc.mUid, proc);
6381 }
6382 }
6383
Riddle Hsua0536432019-02-16 00:38:59 +08006384 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006385 @Override
6386 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006387 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006388 mProcessNames.remove(name, uid);
6389 }
6390 }
6391
Riddle Hsua0536432019-02-16 00:38:59 +08006392 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006393 @Override
6394 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006395 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006396 if (proc == mHomeProcess) {
6397 mHomeProcess = null;
6398 }
6399 if (proc == mPreviousProcess) {
6400 mPreviousProcess = null;
6401 }
6402 }
6403 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006404
Riddle Hsua0536432019-02-16 00:38:59 +08006405 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006406 @Override
6407 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006408 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006409 return mTopProcessState;
6410 }
6411 }
6412
Riddle Hsua0536432019-02-16 00:38:59 +08006413 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006414 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006415 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006416 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006417 return proc == mHeavyWeightProcess;
6418 }
6419 }
6420
Riddle Hsua0536432019-02-16 00:38:59 +08006421 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006422 @Override
6423 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006424 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006425 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6426 }
6427 }
6428
6429 @Override
6430 public void finishHeavyWeightApp() {
6431 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006432 if (mHeavyWeightProcess != null) {
6433 mHeavyWeightProcess.finishActivities();
6434 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006435 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6436 mHeavyWeightProcess);
6437 }
6438 }
6439
Riddle Hsua0536432019-02-16 00:38:59 +08006440 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006441 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006442 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006443 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006444 return isSleepingLocked();
6445 }
6446 }
6447
6448 @Override
6449 public boolean isShuttingDown() {
6450 synchronized (mGlobalLock) {
6451 return mShuttingDown;
6452 }
6453 }
6454
6455 @Override
6456 public boolean shuttingDown(boolean booted, int timeout) {
6457 synchronized (mGlobalLock) {
6458 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006459 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006460 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006461 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006462 return mStackSupervisor.shutdownLocked(timeout);
6463 }
6464 }
6465
6466 @Override
6467 public void enableScreenAfterBoot(boolean booted) {
6468 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006469 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006470 mWindowManager.enableScreenAfterBoot();
6471 updateEventDispatchingLocked(booted);
6472 }
6473 }
6474
6475 @Override
6476 public boolean showStrictModeViolationDialog() {
6477 synchronized (mGlobalLock) {
6478 return mShowDialogs && !mSleeping && !mShuttingDown;
6479 }
6480 }
6481
6482 @Override
6483 public void showSystemReadyErrorDialogsIfNeeded() {
6484 synchronized (mGlobalLock) {
6485 try {
6486 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6487 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6488 + " data partition or your device will be unstable.");
6489 mUiHandler.post(() -> {
6490 if (mShowDialogs) {
6491 AlertDialog d = new BaseErrorDialog(mUiContext);
6492 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6493 d.setCancelable(false);
6494 d.setTitle(mUiContext.getText(R.string.android_system_label));
6495 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6496 d.setButton(DialogInterface.BUTTON_POSITIVE,
6497 mUiContext.getText(R.string.ok),
6498 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6499 d.show();
6500 }
6501 });
6502 }
6503 } catch (RemoteException e) {
6504 }
6505
6506 if (!Build.isBuildConsistent()) {
6507 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6508 mUiHandler.post(() -> {
6509 if (mShowDialogs) {
6510 AlertDialog d = new BaseErrorDialog(mUiContext);
6511 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6512 d.setCancelable(false);
6513 d.setTitle(mUiContext.getText(R.string.android_system_label));
6514 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6515 d.setButton(DialogInterface.BUTTON_POSITIVE,
6516 mUiContext.getText(R.string.ok),
6517 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6518 d.show();
6519 }
6520 });
6521 }
6522 }
6523 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006524
6525 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006526 public void onProcessMapped(int pid, WindowProcessController proc) {
6527 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006528 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006529 }
6530 }
6531
6532 @Override
6533 public void onProcessUnMapped(int pid) {
6534 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006535 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006536 }
6537 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006538
6539 @Override
6540 public void onPackageDataCleared(String name) {
6541 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006542 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006543 mAppWarnings.onPackageDataCleared(name);
6544 }
6545 }
6546
6547 @Override
6548 public void onPackageUninstalled(String name) {
6549 synchronized (mGlobalLock) {
6550 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006551 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006552 }
6553 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006554
6555 @Override
6556 public void onPackageAdded(String name, boolean replacing) {
6557 synchronized (mGlobalLock) {
6558 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6559 }
6560 }
6561
6562 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006563 public void onPackageReplaced(ApplicationInfo aInfo) {
6564 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006565 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006566 }
6567 }
6568
6569 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006570 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6571 synchronized (mGlobalLock) {
6572 return compatibilityInfoForPackageLocked(ai);
6573 }
6574 }
6575
Yunfan Chen75157d72018-07-27 14:47:21 +09006576 /**
6577 * Set the corresponding display information for the process global configuration. To be
6578 * called when we need to show IME on a different display.
6579 *
6580 * @param pid The process id associated with the IME window.
6581 * @param displayId The ID of the display showing the IME.
6582 */
6583 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006584 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006585 // Don't update process-level configuration for Multi-Client IME process since other
6586 // IMEs on other displays will also receive this configuration change due to IME
6587 // services use the same application config/context.
6588 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006589
Yunfan Chen75157d72018-07-27 14:47:21 +09006590 if (pid == MY_PID || pid < 0) {
6591 if (DEBUG_CONFIGURATION) {
6592 Slog.w(TAG,
6593 "Trying to update display configuration for system/invalid process.");
6594 }
6595 return;
6596 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006597 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006598 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006599 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006600 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006601 // Call might come when display is not yet added or has been removed.
6602 if (DEBUG_CONFIGURATION) {
6603 Slog.w(TAG, "Trying to update display configuration for non-existing "
6604 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006605 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006606 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006607 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006608 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006609 if (process == null) {
6610 if (DEBUG_CONFIGURATION) {
6611 Slog.w(TAG, "Trying to update display configuration for invalid "
6612 + "process, pid=" + pid);
6613 }
6614 return;
6615 }
lumarkddc77fb2019-06-27 22:22:23 +08006616 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006617 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006618 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006619 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006620
6621 @Override
6622 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006623 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006624 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006625 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006626 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006627 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006628 }
6629 }
6630 }
6631
6632 @Override
6633 public void clearPendingResultForActivity(IBinder activityToken,
6634 WeakReference<PendingIntentRecord> pir) {
6635 synchronized (mGlobalLock) {
6636 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6637 if (r != null && r.pendingResults != null) {
6638 r.pendingResults.remove(pir);
6639 }
6640 }
6641 }
6642
6643 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006644 public ActivityTokens getTopActivityForTask(int taskId) {
6645 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006646 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006647 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006648 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6649 + " Requested task not found");
6650 return null;
6651 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006652 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006653 if (activity == null) {
6654 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6655 + " Requested activity not found");
6656 return null;
6657 }
6658 if (!activity.attachedToProcess()) {
6659 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6660 + activity);
6661 return null;
6662 }
6663 return new ActivityTokens(activity.appToken, activity.assistToken,
6664 activity.app.getThread());
6665 }
6666 }
6667
6668 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006669 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006670 @Nullable String featureId, int callingUid, int userId, IBinder token,
6671 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6672 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006673 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006674 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6675 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006676 }
6677 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006678
6679 @Override
6680 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6681 synchronized (mGlobalLock) {
6682 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6683 if (r == null) {
6684 return null;
6685 }
6686 if (r.mServiceConnectionsHolder == null) {
6687 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6688 ActivityTaskManagerService.this, r);
6689 }
6690
6691 return r.mServiceConnectionsHolder;
6692 }
6693 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006694
6695 @Override
6696 public Intent getHomeIntent() {
6697 synchronized (mGlobalLock) {
6698 return ActivityTaskManagerService.this.getHomeIntent();
6699 }
6700 }
6701
6702 @Override
6703 public boolean startHomeActivity(int userId, String reason) {
6704 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006705 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006706 }
6707 }
6708
6709 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006710 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006711 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006712 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006713 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006714 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006715 }
Chilun8b1f1be2019-03-13 17:14:36 +08006716 }
6717
6718 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006719 public boolean startHomeOnAllDisplays(int userId, String reason) {
6720 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006721 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006722 }
6723 }
6724
Riddle Hsua0536432019-02-16 00:38:59 +08006725 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006726 @Override
6727 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006728 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006729 if (mFactoryTest == FACTORY_TEST_OFF) {
6730 return false;
6731 }
6732 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6733 && wpc.mName.equals(mTopComponent.getPackageName())) {
6734 return true;
6735 }
6736 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6737 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6738 }
6739 }
6740
6741 @Override
6742 public void updateTopComponentForFactoryTest() {
6743 synchronized (mGlobalLock) {
6744 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6745 return;
6746 }
6747 final ResolveInfo ri = mContext.getPackageManager()
6748 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6749 final CharSequence errorMsg;
6750 if (ri != null) {
6751 final ActivityInfo ai = ri.activityInfo;
6752 final ApplicationInfo app = ai.applicationInfo;
6753 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6754 mTopAction = Intent.ACTION_FACTORY_TEST;
6755 mTopData = null;
6756 mTopComponent = new ComponentName(app.packageName, ai.name);
6757 errorMsg = null;
6758 } else {
6759 errorMsg = mContext.getResources().getText(
6760 com.android.internal.R.string.factorytest_not_system);
6761 }
6762 } else {
6763 errorMsg = mContext.getResources().getText(
6764 com.android.internal.R.string.factorytest_no_action);
6765 }
6766 if (errorMsg == null) {
6767 return;
6768 }
6769
6770 mTopAction = null;
6771 mTopData = null;
6772 mTopComponent = null;
6773 mUiHandler.post(() -> {
6774 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6775 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006776 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006777 });
6778 }
6779 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006780
Riddle Hsua0536432019-02-16 00:38:59 +08006781 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006782 @Override
6783 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6784 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006785 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006786 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006787 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006788
6789 wpc.clearRecentTasks();
6790 wpc.clearActivities();
6791
6792 if (wpc.isInstrumenting()) {
6793 finishInstrumentationCallback.run();
6794 }
6795
Jorim Jaggid0752812018-10-16 16:07:20 +02006796 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006797 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006798 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006799 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006800 // If there was nothing to resume, and we are not already restarting
6801 // this process, but there is a visible activity that is hosted by the
6802 // process...then make sure all visible activities are running, taking
6803 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006804 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006805 !PRESERVE_WINDOWS);
6806 }
6807 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006808 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006809 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006810 }
6811 }
6812 }
6813
6814 @Override
6815 public void closeSystemDialogs(String reason) {
6816 enforceNotIsolatedCaller("closeSystemDialogs");
6817
6818 final int pid = Binder.getCallingPid();
6819 final int uid = Binder.getCallingUid();
6820 final long origId = Binder.clearCallingIdentity();
6821 try {
6822 synchronized (mGlobalLock) {
6823 // Only allow this from foreground processes, so that background
6824 // applications can't abuse it to prevent system UI from being shown.
6825 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006826 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006827 if (!proc.isPerceptible()) {
6828 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6829 + " from background process " + proc);
6830 return;
6831 }
6832 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006833 mWindowManager.closeSystemDialogs(reason);
6834
Louis Chang149d5c82019-12-30 09:47:39 +08006835 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006836 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006837 // Call into AM outside the synchronized block.
6838 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006839 } finally {
6840 Binder.restoreCallingIdentity(origId);
6841 }
6842 }
6843
6844 @Override
6845 public void cleanupDisabledPackageComponents(
6846 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6847 synchronized (mGlobalLock) {
6848 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006849 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006850 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006851 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006852 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006853 }
6854
6855 // Clean-up disabled tasks
6856 getRecentTasks().cleanupDisabledPackageTasksLocked(
6857 packageName, disabledClasses, userId);
6858 }
6859 }
6860
6861 @Override
6862 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6863 int userId) {
6864 synchronized (mGlobalLock) {
6865
6866 boolean didSomething =
6867 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006868 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006869 null, doit, evenPersistent, userId);
6870 return didSomething;
6871 }
6872 }
6873
6874 @Override
6875 public void resumeTopActivities(boolean scheduleIdle) {
6876 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006877 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006878 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006879 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006880 }
6881 }
6882 }
6883
Riddle Hsua0536432019-02-16 00:38:59 +08006884 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006885 @Override
6886 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006887 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006888 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6889 }
6890 }
6891
Riddle Hsua0536432019-02-16 00:38:59 +08006892 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006893 @Override
6894 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006895 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006896 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6897 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6898 }
6899 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006900 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006901 } finally {
6902 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6903 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006904 }
6905 }
6906
6907 @Override
6908 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6909 try {
6910 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6911 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6912 }
6913 } catch (RemoteException ex) {
6914 throw new SecurityException("Fail to check is caller a privileged app", ex);
6915 }
6916
6917 synchronized (mGlobalLock) {
6918 final long ident = Binder.clearCallingIdentity();
6919 try {
6920 if (mAmInternal.shouldConfirmCredentials(userId)) {
6921 if (mKeyguardController.isKeyguardLocked()) {
6922 // Showing launcher to avoid user entering credential twice.
6923 startHomeActivity(currentUserId, "notifyLockedProfile");
6924 }
Louis Chang149d5c82019-12-30 09:47:39 +08006925 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006926 }
6927 } finally {
6928 Binder.restoreCallingIdentity(ident);
6929 }
6930 }
6931 }
6932
6933 @Override
6934 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6935 mAmInternal.enforceCallingPermission(
6936 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6937
6938 synchronized (mGlobalLock) {
6939 final long ident = Binder.clearCallingIdentity();
6940 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006941 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6942 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006943 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006944 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6945 UserHandle.CURRENT);
6946 } finally {
6947 Binder.restoreCallingIdentity(ident);
6948 }
6949 }
6950 }
6951
6952 @Override
6953 public void writeActivitiesToProto(ProtoOutputStream proto) {
6954 synchronized (mGlobalLock) {
6955 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006956 mRootWindowContainer.dumpDebug(
6957 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006958 }
6959 }
6960
6961 @Override
6962 public void saveANRState(String reason) {
6963 synchronized (mGlobalLock) {
6964 final StringWriter sw = new StringWriter();
6965 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6966 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6967 if (reason != null) {
6968 pw.println(" Reason: " + reason);
6969 }
6970 pw.println();
6971 getActivityStartController().dump(pw, " ", null);
6972 pw.println();
6973 pw.println("-------------------------------------------------------------------------------");
6974 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6975 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6976 "" /* header */);
6977 pw.println();
6978 pw.close();
6979
6980 mLastANRState = sw.toString();
6981 }
6982 }
6983
6984 @Override
6985 public void clearSavedANRState() {
6986 synchronized (mGlobalLock) {
6987 mLastANRState = null;
6988 }
6989 }
6990
6991 @Override
6992 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6993 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6994 synchronized (mGlobalLock) {
6995 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6996 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6997 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6998 dumpLastANRLocked(pw);
6999 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7000 dumpLastANRTracesLocked(pw);
7001 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7002 dumpActivityStarterLocked(pw, dumpPackage);
7003 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7004 dumpActivityContainersLocked(pw);
7005 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7006 if (getRecentTasks() != null) {
7007 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7008 }
7009 }
7010 }
7011 }
7012
7013 @Override
7014 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7015 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7016 int wakefulness) {
7017 synchronized (mGlobalLock) {
7018 if (mHomeProcess != null && (dumpPackage == null
7019 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7020 if (needSep) {
7021 pw.println();
7022 needSep = false;
7023 }
7024 pw.println(" mHomeProcess: " + mHomeProcess);
7025 }
7026 if (mPreviousProcess != null && (dumpPackage == null
7027 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7028 if (needSep) {
7029 pw.println();
7030 needSep = false;
7031 }
7032 pw.println(" mPreviousProcess: " + mPreviousProcess);
7033 }
7034 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7035 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7036 StringBuilder sb = new StringBuilder(128);
7037 sb.append(" mPreviousProcessVisibleTime: ");
7038 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7039 pw.println(sb);
7040 }
7041 if (mHeavyWeightProcess != null && (dumpPackage == null
7042 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7043 if (needSep) {
7044 pw.println();
7045 needSep = false;
7046 }
7047 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7048 }
7049 if (dumpPackage == null) {
7050 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007051 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007052 }
7053 if (dumpAll) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007054 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7055 if (dumpPackage == null && topFocusedStack != null) {
7056 pw.println(" mConfigWillChange: " + topFocusedStack.mConfigWillChange);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007057 }
7058 if (mCompatModePackages.getPackages().size() > 0) {
7059 boolean printed = false;
7060 for (Map.Entry<String, Integer> entry
7061 : mCompatModePackages.getPackages().entrySet()) {
7062 String pkg = entry.getKey();
7063 int mode = entry.getValue();
7064 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7065 continue;
7066 }
7067 if (!printed) {
7068 pw.println(" mScreenCompatPackages:");
7069 printed = true;
7070 }
7071 pw.println(" " + pkg + ": " + mode);
7072 }
7073 }
7074 }
7075
7076 if (dumpPackage == null) {
7077 pw.println(" mWakefulness="
7078 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007079 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007080 if (mRunningVoice != null) {
7081 pw.println(" mRunningVoice=" + mRunningVoice);
7082 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7083 }
7084 pw.println(" mSleeping=" + mSleeping);
7085 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7086 pw.println(" mVrController=" + mVrController);
7087 }
7088 if (mCurAppTimeTracker != null) {
7089 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7090 }
7091 if (mAllowAppSwitchUids.size() > 0) {
7092 boolean printed = false;
7093 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7094 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7095 for (int j = 0; j < types.size(); j++) {
7096 if (dumpPackage == null ||
7097 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7098 if (needSep) {
7099 pw.println();
7100 needSep = false;
7101 }
7102 if (!printed) {
7103 pw.println(" mAllowAppSwitchUids:");
7104 printed = true;
7105 }
7106 pw.print(" User ");
7107 pw.print(mAllowAppSwitchUids.keyAt(i));
7108 pw.print(": Type ");
7109 pw.print(types.keyAt(j));
7110 pw.print(" = ");
7111 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7112 pw.println();
7113 }
7114 }
7115 }
7116 }
7117 if (dumpPackage == null) {
7118 if (mController != null) {
7119 pw.println(" mController=" + mController
7120 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7121 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007122 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7123 pw.println(" mLaunchingActivityWakeLock="
7124 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007125 }
7126
7127 return needSep;
7128 }
7129 }
7130
7131 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007132 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7133 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007134 synchronized (mGlobalLock) {
7135 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007136 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007137 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7138 if (topFocusedStack != null) {
7139 proto.write(CONFIG_WILL_CHANGE, topFocusedStack.mConfigWillChange);
7140 }
sanryhuang498e77e2018-12-06 14:57:01 +08007141 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7142 if (mRunningVoice != null) {
7143 final long vrToken = proto.start(
7144 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7145 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7146 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007147 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007148 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7149 proto.end(vrToken);
7150 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007151 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007152 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007153 if (mController != null) {
7154 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007155 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7156 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007157 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7158 proto.end(token);
7159 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007160 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7161 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007162 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007163 }
7164
7165 if (mHomeProcess != null && (dumpPackage == null
7166 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007167 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007168 }
7169
7170 if (mPreviousProcess != null && (dumpPackage == null
7171 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007172 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007173 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7174 }
7175
7176 if (mHeavyWeightProcess != null && (dumpPackage == null
7177 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007178 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007179 }
7180
7181 for (Map.Entry<String, Integer> entry
7182 : mCompatModePackages.getPackages().entrySet()) {
7183 String pkg = entry.getKey();
7184 int mode = entry.getValue();
7185 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7186 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7187 proto.write(PACKAGE, pkg);
7188 proto.write(MODE, mode);
7189 proto.end(compatToken);
7190 }
7191 }
7192
7193 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007194 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007195 }
7196
7197 }
7198 }
7199
7200 @Override
7201 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7202 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7203 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007204 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7205 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007206 }
7207
7208 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007209 public void dumpForOom(PrintWriter pw) {
7210 synchronized (mGlobalLock) {
7211 pw.println(" mHomeProcess: " + mHomeProcess);
7212 pw.println(" mPreviousProcess: " + mPreviousProcess);
7213 if (mHeavyWeightProcess != null) {
7214 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7215 }
7216 }
7217 }
7218
7219 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007220 public boolean canGcNow() {
7221 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007222 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007223 }
7224 }
7225
Riddle Hsua0536432019-02-16 00:38:59 +08007226 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007227 @Override
7228 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007229 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007230 if (mRootWindowContainer == null) {
7231 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007232 // oomadj after AMS created.
7233 return null;
7234 }
Louis Chang149d5c82019-12-30 09:47:39 +08007235 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007236 return top != null ? top.app : null;
7237 }
7238 }
7239
Riddle Hsua0536432019-02-16 00:38:59 +08007240 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007241 @Override
7242 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007243 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007244 if (mRootWindowContainer != null) {
7245 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007246 }
7247 }
7248 }
7249
7250 @Override
7251 public void scheduleDestroyAllActivities(String reason) {
7252 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007253 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007254 }
7255 }
7256
7257 @Override
7258 public void removeUser(int userId) {
7259 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007260 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007261 }
7262 }
7263
7264 @Override
7265 public boolean switchUser(int userId, UserState userState) {
7266 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007267 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007268 }
7269 }
7270
7271 @Override
7272 public void onHandleAppCrash(WindowProcessController wpc) {
7273 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007274 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007275 }
7276 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007277
7278 @Override
7279 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7280 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007281 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007282 }
7283 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007284
Riddle Hsua0536432019-02-16 00:38:59 +08007285 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007286 @Override
7287 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007288 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007289 }
7290
Riddle Hsua0536432019-02-16 00:38:59 +08007291 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007292 @Override
7293 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007294 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007295 }
7296
Riddle Hsua0536432019-02-16 00:38:59 +08007297 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007298 @Override
7299 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007300 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007301 }
7302
Riddle Hsua0536432019-02-16 00:38:59 +08007303 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007304 @Override
7305 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007306 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007307 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007308
7309 @Override
7310 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007311 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007312 mPendingTempWhitelist.put(uid, tag);
7313 }
7314 }
7315
7316 @Override
7317 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007318 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007319 mPendingTempWhitelist.remove(uid);
7320 }
7321 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007322
7323 @Override
7324 public boolean handleAppCrashInActivityController(String processName, int pid,
7325 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7326 Runnable killCrashingAppCallback) {
7327 synchronized (mGlobalLock) {
7328 if (mController == null) {
7329 return false;
7330 }
7331
7332 try {
7333 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7334 stackTrace)) {
7335 killCrashingAppCallback.run();
7336 return true;
7337 }
7338 } catch (RemoteException e) {
7339 mController = null;
7340 Watchdog.getInstance().setActivityController(null);
7341 }
7342 return false;
7343 }
7344 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007345
7346 @Override
7347 public void removeRecentTasksByPackageName(String packageName, int userId) {
7348 synchronized (mGlobalLock) {
7349 mRecentTasks.removeTasksByPackageName(packageName, userId);
7350 }
7351 }
7352
7353 @Override
7354 public void cleanupRecentTasksForUser(int userId) {
7355 synchronized (mGlobalLock) {
7356 mRecentTasks.cleanupLocked(userId);
7357 }
7358 }
7359
7360 @Override
7361 public void loadRecentTasksForUser(int userId) {
7362 synchronized (mGlobalLock) {
7363 mRecentTasks.loadUserRecentsLocked(userId);
7364 }
7365 }
7366
7367 @Override
7368 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7369 synchronized (mGlobalLock) {
7370 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7371 }
7372 }
7373
7374 @Override
7375 public void flushRecentTasks() {
7376 mRecentTasks.flush();
7377 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007378
7379 @Override
7380 public WindowProcessController getHomeProcess() {
7381 synchronized (mGlobalLock) {
7382 return mHomeProcess;
7383 }
7384 }
7385
7386 @Override
7387 public WindowProcessController getPreviousProcess() {
7388 synchronized (mGlobalLock) {
7389 return mPreviousProcess;
7390 }
7391 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007392
7393 @Override
7394 public void clearLockedTasks(String reason) {
7395 synchronized (mGlobalLock) {
7396 getLockTaskController().clearLockedTasks(reason);
7397 }
7398 }
7399
7400 @Override
7401 public void updateUserConfiguration() {
7402 synchronized (mGlobalLock) {
7403 final Configuration configuration = new Configuration(getGlobalConfiguration());
7404 final int currentUserId = mAmInternal.getCurrentUserId();
7405 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7406 configuration, currentUserId, Settings.System.canWrite(mContext));
7407 updateConfigurationLocked(configuration, null /* starting */,
7408 false /* initLocale */, false /* persistent */, currentUserId,
7409 false /* deferResume */);
7410 }
7411 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007412
7413 @Override
7414 public boolean canShowErrorDialogs() {
7415 synchronized (mGlobalLock) {
7416 return mShowDialogs && !mSleeping && !mShuttingDown
7417 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7418 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7419 mAmInternal.getCurrentUserId())
7420 && !(UserManager.isDeviceInDemoMode(mContext)
7421 && mAmInternal.getCurrentUser().isDemo());
7422 }
7423 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007424
7425 @Override
7426 public void setProfileApp(String profileApp) {
7427 synchronized (mGlobalLock) {
7428 mProfileApp = profileApp;
7429 }
7430 }
7431
7432 @Override
7433 public void setProfileProc(WindowProcessController wpc) {
7434 synchronized (mGlobalLock) {
7435 mProfileProc = wpc;
7436 }
7437 }
7438
7439 @Override
7440 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7441 synchronized (mGlobalLock) {
7442 mProfilerInfo = profilerInfo;
7443 }
7444 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007445
7446 @Override
7447 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7448 synchronized (mGlobalLock) {
7449 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7450 }
7451 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007452
7453 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007454 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
Peter Kalauskas4dc04602020-02-12 18:49:03 -08007455 boolean isLowResolution) {
7456 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007457 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007458 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007459
7460 @Override
7461 public boolean isUidForeground(int uid) {
7462 synchronized (mGlobalLock) {
7463 return ActivityTaskManagerService.this.isUidForeground(uid);
7464 }
7465 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007466
7467 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007468 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007469 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007470 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007471 }
7472 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007473
7474 @Override
7475 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007476 // Translate package names into UIDs
7477 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007478 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007479 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7480 if (uid >= 0) {
7481 result.add(uid);
7482 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007483 }
7484 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007485 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007486 }
7487 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007488 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007489}