blob: 60ab5567f0259564ebec55685cc87bba6cf85192 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Jonathan Scott92335342019-12-17 14:46:26 +000031import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Galia Peycheva45f48d32020-02-20 15:39:10 +010034import static android.app.WindowConfiguration.ACTIVITY_TYPE_DREAM;
Wale 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;
39import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070042import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070043import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070044import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
45import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070047import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070048import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
49import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
50import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070051import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070052import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080053import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070054import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070055import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
57import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070058import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
59import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070060import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040061import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.view.Display.DEFAULT_DISPLAY;
63import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070064import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070065
Yunfan Chen79b96062018-10-17 12:45:23 -070066import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
67import static com.android.server.am.ActivityManagerService.MY_PID;
68import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
69import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwalef342f062020-01-27 07:34:13 -080070import static com.android.server.am.ActivityManagerServiceDumpActivitiesProto.ROOT_WINDOW_CONTAINER;
Wale Ogunwale31913b52018-10-13 08:29:31 -070071import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
72import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080081import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Jeff Changd136e772019-11-05 20:33:52 +080085import static com.android.server.am.EventLogTags.writeBootProgressEnableScreen;
86import static com.android.server.am.EventLogTags.writeConfigurationChanged;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070087import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
88import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
91import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Louis Chang149d5c82019-12-30 09:47:39 +0800119import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
Louis Changcdec0802019-11-11 11:45:07 +0800121import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
Louis Changa009c762020-02-26 11:21:31 +0800124import static com.android.server.wm.WindowContainer.POSITION_TOP;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800127import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700128import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.annotation.Nullable;
130import android.annotation.UserIdInt;
131import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700132import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700133import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.ActivityOptions;
135import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700136import android.app.ActivityThread;
137import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700138import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100139import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700140import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700141import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700142import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.IApplicationThread;
144import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400146import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700148import android.app.Notification;
149import android.app.NotificationManager;
150import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700151import android.app.PictureInPictureParams;
152import android.app.ProfilerInfo;
153import android.app.RemoteAction;
154import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700155import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.app.admin.DevicePolicyCache;
157import android.app.assist.AssistContent;
158import android.app.assist.AssistStructure;
jorgegil@google.com06bc3232019-10-31 14:51:22 -0700159import android.app.servertransaction.ClientTransaction;
160import android.app.servertransaction.EnterPipRequestedItem;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700161import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.ActivityNotFoundException;
163import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700164import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700165import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700166import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700167import android.content.IIntentSender;
168import android.content.Intent;
169import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700170import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900171import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700172import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700174import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.content.pm.ParceledListSlice;
176import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700177import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700179import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700180import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700181import android.graphics.Bitmap;
182import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700183import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700184import android.metrics.LogMaker;
185import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700186import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700187import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700188import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700189import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700190import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700194import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800195import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700196import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700197import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700198import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700199import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100200import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700201import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700203import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.SystemClock;
205import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700207import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700209import android.os.UserManager;
210import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700211import android.os.storage.IStorageManager;
212import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700213import android.provider.Settings;
Galia Peycheva6861e912019-08-21 10:20:23 +0200214import android.service.dreams.DreamActivity;
Galia Peycheva52e89222020-02-18 23:41:43 +0100215import android.service.dreams.DreamManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700216import android.service.voice.IVoiceInteractionSession;
217import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900218import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700219import android.telecom.TelecomManager;
220import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100221import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700223import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700224import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700225import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700226import android.util.SparseArray;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700227import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700228import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700229import android.view.IRecentsAnimationRunner;
230import android.view.RemoteAnimationAdapter;
231import android.view.RemoteAnimationDefinition;
Louis Changa009c762020-02-26 11:21:31 +0800232import android.view.WindowManager;
Wale Ogunwale568f9f412020-03-21 22:27:35 -0700233import android.window.IWindowOrganizerController;
Wale Ogunwale57946582020-03-21 14:29:07 -0700234import android.window.WindowContainerTransaction;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700235
Evan Rosky4505b352018-09-06 11:20:40 -0700236import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700237import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.app.AssistUtils;
239import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700240import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700243import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
244import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700245import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700246import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700247import com.android.internal.policy.IKeyguardDismissCallback;
248import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700249import com.android.internal.util.ArrayUtils;
250import com.android.internal.util.FastPrintWriter;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800251import com.android.internal.util.FrameworkStatsLog;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800252import com.android.internal.util.function.pooled.PooledConsumer;
253import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700254import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700255import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700256import com.android.server.LocalServices;
257import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700258import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800259import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700260import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700261import com.android.server.am.ActivityManagerService;
Wale Ogunwale59507092018-10-29 09:00:30 -0700262import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
263import com.android.server.am.AppTimeTracker;
264import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700265import com.android.server.am.PendingIntentController;
266import com.android.server.am.PendingIntentRecord;
267import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700268import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700269import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700270import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800271import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700272import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700276import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700278import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700280import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700281import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700282import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800283import java.lang.annotation.ElementType;
284import java.lang.annotation.Retention;
285import java.lang.annotation.RetentionPolicy;
286import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700287import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700288import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700290import java.util.Arrays;
Jeff Sharkey8b0cff72020-03-09 15:49:01 -0600291import java.util.Collection;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700292import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400293import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700294import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700295import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700296import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700297import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000298import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700299import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700300
301/**
302 * System service for managing activities and their containers (task, stacks, displays,... ).
303 *
304 * {@hide}
305 */
306public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700307 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800308 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000309 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700310 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
311 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
312 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
313 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700314 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700315
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700316 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700317 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700318 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700319 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100320 // How long we permit background activity starts after an activity in the process
321 // started or finished.
322 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700323
Wale Ogunwale98875612018-10-12 07:53:02 -0700324 /** Used to indicate that an app transition should be animated. */
325 static final boolean ANIMATE = true;
326
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700327 /** Hardware-reported OpenGLES version. */
328 final int GL_ES_VERSION;
329
Wale Ogunwale31913b52018-10-13 08:29:31 -0700330 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
331 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
332 public static final String DUMP_LASTANR_CMD = "lastanr" ;
333 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
334 public static final String DUMP_STARTER_CMD = "starter" ;
335 public static final String DUMP_CONTAINERS_CMD = "containers" ;
336 public static final String DUMP_RECENTS_CMD = "recents" ;
337 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
338
Wale Ogunwale64258362018-10-16 15:13:37 -0700339 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
340 public static final int RELAUNCH_REASON_NONE = 0;
341 /** This activity is being relaunched due to windowing mode change. */
342 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
343 /** This activity is being relaunched due to a free-resize operation. */
344 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
345
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700346 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700347
Wale Ogunwalef6733932018-06-27 05:14:34 -0700348 /**
349 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
350 * change at runtime. Use mContext for non-UI purposes.
351 */
352 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700353 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700354 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700355 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700356 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700357 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700358 private PackageManagerInternal mPmInternal;
Darryl L Johnsona0982222020-02-18 18:21:51 -0800359 /** The cached sys ui service component name from package manager. */
360 private ComponentName mSysUiServiceComponent;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800361 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800362 @VisibleForTesting
363 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700364 PowerManagerInternal mPowerManagerInternal;
365 private UsageStatsManagerInternal mUsageStatsInternal;
366
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700367 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700368 IntentFirewall mIntentFirewall;
369
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700370 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800371 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800372 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700373 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800374 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
375 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
376 *
377 * @see WindowManagerThreadPriorityBooster
378 */
379 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700380 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800381 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700382 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700383 private UserManagerService mUserManager;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800384 private AppOpsManager mAppOpsManager;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700385 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800386 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700387 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700388 /** All processes currently running that might have a window organized by name. */
389 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100390 /** All processes we currently have running mapped by pid and uid */
391 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700392 /** This is the process holding what we currently consider to be the "home" activity. */
393 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700394 /** The currently running heavy-weight process, if any. */
395 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700396 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700397 /**
398 * This is the process holding the activity the user last visited that is in a different process
399 * from the one they are currently in.
400 */
401 WindowProcessController mPreviousProcess;
402 /** The time at which the previous process was last visible. */
403 long mPreviousProcessVisibleTime;
404
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700405 /** List of intents that were used to start the most recent tasks. */
406 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700407 /** State of external calls telling us if the device is awake or asleep. */
408 private boolean mKeyguardShown = false;
409
410 // Wrapper around VoiceInteractionServiceManager
411 private AssistUtils mAssistUtils;
412
413 // VoiceInteraction session ID that changes for each new request except when
414 // being called for multi-window assist in a single session.
415 private int mViSessionId = 1000;
416
417 // How long to wait in getAssistContextExtras for the activity and foreground services
418 // to respond with the result.
419 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
420
421 // How long top wait when going through the modern assist (which doesn't need to block
422 // on getting this result before starting to launch its UI).
423 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
424
425 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
426 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
427
Alison Cichowlas3e340502018-08-07 17:15:01 -0400428 // Permission tokens are used to temporarily granted a trusted app the ability to call
429 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
430 // showing any appropriate error messages to the user.
431 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
432 10 * MINUTE_IN_MILLIS;
433
434 // How long before the service actually expires a token. This is slightly longer than
435 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
436 // expiration exception.
437 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
438 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
439
440 // How long the service will remember expired tokens, for the purpose of providing error
441 // messaging when a client uses an expired token.
442 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
443 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
444
445 // Activity tokens of system activities that are delegating their call to
446 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
447 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
448
449 // Permission tokens that have expired, but we remember for error reporting.
450 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
451
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700452 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
453
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700454 // Keeps track of the active voice interaction service component, notified from
455 // VoiceInteractionManagerService
456 ComponentName mActiveVoiceInteractionServiceComponent;
457
Michal Karpinskida34cd42019-04-02 19:46:52 +0100458 // A map userId and all its companion app uids
459 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000460
Wale Ogunwalee2172292018-10-25 10:11:10 -0700461 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700462 KeyguardController mKeyguardController;
463 private final ClientLifecycleManager mLifecycleManager;
464 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700465 /** The controller for all operations related to locktask. */
466 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700467 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700468
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700469 boolean mSuppressResizeConfigChanges;
470
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700471 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700472 new UpdateConfigurationResult();
473
474 static final class UpdateConfigurationResult {
475 // Configuration changes that were updated.
476 int changes;
477 // If the activity was relaunched to match the new configuration.
478 boolean activityRelaunched;
479
480 void reset() {
481 changes = 0;
482 activityRelaunched = false;
483 }
484 }
485
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700486 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700487 private int mConfigurationSeq;
488 // To cache the list of supported system locales
489 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700490
491 /**
492 * Temp object used when global and/or display override configuration is updated. It is also
493 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
494 * anyone...
495 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700496 private Configuration mTempConfig = new Configuration();
497
Wale Ogunwalef6733932018-06-27 05:14:34 -0700498 /** Temporary to avoid allocations. */
499 final StringBuilder mStringBuilder = new StringBuilder(256);
500
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700501 // Amount of time after a call to stopAppSwitches() during which we will
502 // prevent further untrusted switches from happening.
503 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
504
505 /**
506 * The time at which we will allow normal application switches again,
507 * after a call to {@link #stopAppSwitches()}.
508 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700509 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700510 /**
511 * This is set to true after the first switch after mAppSwitchesAllowedTime
512 * is set; any switches after that will clear the time.
513 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700514 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700515
Ricky Wai906af482019-06-03 17:25:28 +0100516 /**
517 * Last stop app switches time, apps finished before this time cannot start background activity
518 * even if they are in grace period.
519 */
520 private long mLastStopAppSwitchesTime;
521
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700522 IActivityController mController = null;
523 boolean mControllerIsAMonkey = false;
524
Wale Ogunwale214f3482018-10-04 11:00:47 -0700525 final int mFactoryTest;
526
527 /** Used to control how we initialize the service. */
528 ComponentName mTopComponent;
529 String mTopAction = Intent.ACTION_MAIN;
530 String mTopData;
531
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800532 /** Profiling app information. */
533 String mProfileApp = null;
534 WindowProcessController mProfileProc = null;
535 ProfilerInfo mProfilerInfo = null;
536
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700537 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700538 * Dump of the activity state at the time of the last ANR. Cleared after
539 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
540 */
541 String mLastANRState;
542
543 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700544 * Used to retain an update lock when the foreground activity is in
545 * immersive mode.
546 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700547 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700548
549 /**
550 * Packages that are being allowed to perform unrestricted app switches. Mapping is
551 * User -> Type -> uid.
552 */
553 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
554
555 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700556 private int mThumbnailWidth;
557 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700558
559 /**
560 * Flag that indicates if multi-window is enabled.
561 *
562 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
563 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
564 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
565 * At least one of the forms of multi-window must be enabled in order for this flag to be
566 * initialized to 'true'.
567 *
568 * @see #mSupportsSplitScreenMultiWindow
569 * @see #mSupportsFreeformWindowManagement
570 * @see #mSupportsPictureInPicture
571 * @see #mSupportsMultiDisplay
572 */
573 boolean mSupportsMultiWindow;
574 boolean mSupportsSplitScreenMultiWindow;
575 boolean mSupportsFreeformWindowManagement;
576 boolean mSupportsPictureInPicture;
577 boolean mSupportsMultiDisplay;
578 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700579 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700580
581 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
582
583 // VR Vr2d Display Id.
584 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700585
Wale Ogunwalef6733932018-06-27 05:14:34 -0700586 /**
587 * Set while we are wanting to sleep, to prevent any
588 * activities from being started/resumed.
589 *
590 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
591 *
592 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
593 * while in the sleep state until there is a pending transition out of sleep, in which case
594 * mSleeping is set to false, and remains false while awake.
595 *
596 * Whether mSleeping can quickly toggled between true/false without the device actually
597 * display changing states is undefined.
598 */
599 private boolean mSleeping = false;
600
601 /**
602 * The process state used for processes that are running the top activities.
603 * This changes between TOP and TOP_SLEEPING to following mSleeping.
604 */
605 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
606
Riddle Hsua0022cd2019-09-09 21:12:41 +0800607 @Retention(RetentionPolicy.SOURCE)
608 @IntDef({
609 LAYOUT_REASON_CONFIG_CHANGED,
610 LAYOUT_REASON_VISIBILITY_CHANGED,
611 })
612 @interface LayoutReason {}
613 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
614 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
615
616 /** The reasons to perform surface placement. */
617 @LayoutReason
618 private int mLayoutReasons;
619
Wale Ogunwalef6733932018-06-27 05:14:34 -0700620 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
621 // automatically. Important for devices without direct input devices.
622 private boolean mShowDialogs = true;
623
624 /** Set if we are shutting down the system, similar to sleeping. */
625 boolean mShuttingDown = false;
626
627 /**
628 * We want to hold a wake lock while running a voice interaction session, since
629 * this may happen with the screen off and we need to keep the CPU running to
630 * be able to continue to interact with the user.
631 */
632 PowerManager.WakeLock mVoiceWakeLock;
633
634 /**
635 * Set while we are running a voice interaction. This overrides sleeping while it is active.
636 */
637 IVoiceInteractionSession mRunningVoice;
638
639 /**
640 * The last resumed activity. This is identical to the current resumed activity most
641 * of the time but could be different when we're pausing one activity before we resume
642 * another activity.
643 */
644 ActivityRecord mLastResumedActivity;
645
646 /**
647 * The activity that is currently being traced as the active resumed activity.
648 *
649 * @see #updateResumedAppTrace
650 */
651 private @Nullable ActivityRecord mTracedResumedActivity;
652
653 /** If non-null, we are tracking the time the user spends in the currently focused app. */
654 AppTimeTracker mCurAppTimeTracker;
655
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700656 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700657
Wale Ogunwale53783742018-09-16 10:21:51 -0700658 /**
659 * Packages that the user has asked to have run in screen size
660 * compatibility mode instead of filling the screen.
661 */
662 CompatModePackages mCompatModePackages;
663
Wale Ogunwalef6733932018-06-27 05:14:34 -0700664 private FontScaleSettingObserver mFontScaleSettingObserver;
665
Wale Ogunwale568f9f412020-03-21 22:27:35 -0700666 WindowOrganizerController mWindowOrganizerController;
667 TaskOrganizerController mTaskOrganizerController;
Robert Carr8a2f9132019-11-11 15:03:15 -0800668
Ricky Wai96f5c352019-04-10 18:40:17 +0100669 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000670
Wale Ogunwalef6733932018-06-27 05:14:34 -0700671 private final class FontScaleSettingObserver extends ContentObserver {
672 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
673 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
674
675 public FontScaleSettingObserver() {
676 super(mH);
677 final ContentResolver resolver = mContext.getContentResolver();
678 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
679 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
680 UserHandle.USER_ALL);
681 }
682
683 @Override
Jeff Sharkey8b0cff72020-03-09 15:49:01 -0600684 public void onChange(boolean selfChange, Collection<Uri> uris, int flags,
Riddle Hsu9c024d12020-03-09 16:10:07 +0800685 @UserIdInt int userId) {
686 for (Uri uri : uris) {
687 if (mFontScaleUri.equals(uri)) {
688 updateFontScaleIfNeeded(userId);
689 } else if (mHideErrorDialogsUri.equals(uri)) {
690 synchronized (mGlobalLock) {
691 updateShouldShowDialogsLocked(getGlobalConfiguration());
692 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700693 }
694 }
695 }
696 }
697
Riddle Hsua0536432019-02-16 00:38:59 +0800698 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
699 @Target(ElementType.METHOD)
700 @Retention(RetentionPolicy.SOURCE)
701 @interface HotPath {
702 int NONE = 0;
703 int OOM_ADJUSTMENT = 1;
704 int LRU_UPDATE = 2;
705 int PROCESS_CHANGE = 3;
706 int caller() default NONE;
707 }
708
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800709 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
710 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900711 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800712 mAmInternal.updateOomAdj();
713 }
714 };
715
Charles Chen8d98dd22018-12-26 17:36:54 +0800716 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
717 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700718 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700719 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700720 mSystemThread = ActivityThread.currentActivityThread();
721 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700722 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800723 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700724 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale568f9f412020-03-21 22:27:35 -0700725 mWindowOrganizerController = new WindowOrganizerController(this);
726 mTaskOrganizerController = mWindowOrganizerController.mTaskOrganizerController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700727 }
728
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700729 public void onSystemReady() {
730 synchronized (mGlobalLock) {
731 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
732 PackageManager.FEATURE_CANT_SAVE_STATE);
733 mAssistUtils = new AssistUtils(mContext);
734 mVrController.onSystemReady();
735 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700736 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700737 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700738 }
739
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700740 public void onInitPowerManagement() {
741 synchronized (mGlobalLock) {
742 mStackSupervisor.initPowerManagement();
743 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
744 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
745 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
746 mVoiceWakeLock.setReferenceCounted(false);
747 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700748 }
749
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700750 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700751 mFontScaleSettingObserver = new FontScaleSettingObserver();
752 }
753
Wale Ogunwale59507092018-10-29 09:00:30 -0700754 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700755 final boolean freeformWindowManagement =
756 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
757 || Settings.Global.getInt(
758 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
759
760 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
761 final boolean supportsPictureInPicture = supportsMultiWindow &&
762 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
763 final boolean supportsSplitScreenMultiWindow =
764 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
765 final boolean supportsMultiDisplay = mContext.getPackageManager()
766 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700767 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
768 final boolean forceResizable = Settings.Global.getInt(
769 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700770 final boolean sizeCompatFreeform = Settings.Global.getInt(
771 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700772
773 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900774 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700775
776 final Configuration configuration = new Configuration();
777 Settings.System.getConfiguration(resolver, configuration);
778 if (forceRtl) {
779 // This will take care of setting the correct layout direction flags
780 configuration.setLayoutDirection(configuration.locale);
781 }
782
783 synchronized (mGlobalLock) {
784 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700785 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700786 final boolean multiWindowFormEnabled = freeformWindowManagement
787 || supportsSplitScreenMultiWindow
788 || supportsPictureInPicture
789 || supportsMultiDisplay;
790 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
791 mSupportsMultiWindow = true;
792 mSupportsFreeformWindowManagement = freeformWindowManagement;
793 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
794 mSupportsPictureInPicture = supportsPictureInPicture;
795 mSupportsMultiDisplay = supportsMultiDisplay;
796 } else {
797 mSupportsMultiWindow = false;
798 mSupportsFreeformWindowManagement = false;
799 mSupportsSplitScreenMultiWindow = false;
800 mSupportsPictureInPicture = false;
801 mSupportsMultiDisplay = false;
802 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700803 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700804 // This happens before any activities are started, so we can change global configuration
805 // in-place.
806 updateConfigurationLocked(configuration, null, true);
807 final Configuration globalConfig = getGlobalConfiguration();
808 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
809
810 // Load resources only after the current configuration has been set.
811 final Resources res = mContext.getResources();
812 mThumbnailWidth = res.getDimensionPixelSize(
813 com.android.internal.R.dimen.thumbnail_width);
814 mThumbnailHeight = res.getDimensionPixelSize(
815 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700816 }
817 }
818
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800819 public WindowManagerGlobalLock getGlobalLock() {
820 return mGlobalLock;
821 }
822
Yunfan Chen585f2932019-01-29 16:04:45 +0900823 /** For test purpose only. */
824 @VisibleForTesting
825 public ActivityTaskManagerInternal getAtmInternal() {
826 return mInternal;
827 }
828
Riddle Hsud93a6c42018-11-29 21:50:06 +0800829 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
830 Looper looper) {
831 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700832 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700833 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700834 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800835 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700836 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700837 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700838 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700839
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700840 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700841 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700842 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700843 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700844 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700845 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700846 mKeyguardController = mStackSupervisor.getKeyguardController();
847 }
848
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700849 public void onActivityManagerInternalAdded() {
850 synchronized (mGlobalLock) {
851 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
852 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
853 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700854 }
855
Yunfan Chen75157d72018-07-27 14:47:21 +0900856 int increaseConfigurationSeqLocked() {
857 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
858 return mConfigurationSeq;
859 }
860
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700861 protected ActivityStackSupervisor createStackSupervisor() {
862 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
863 supervisor.initialize();
864 return supervisor;
865 }
866
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800867 protected AppWarnings createAppWarnings(
868 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
869 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
870 }
871
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700872 public void setWindowManager(WindowManagerService wm) {
873 synchronized (mGlobalLock) {
874 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800875 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800876 mTempConfig.setToDefaults();
877 mTempConfig.setLocales(LocaleList.getDefault());
878 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800879 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700880 mLockTaskController.setWindowManager(wm);
881 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800882 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700883 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700884 }
885
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700886 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
887 synchronized (mGlobalLock) {
888 mUsageStatsInternal = usageStatsManager;
889 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700890 }
891
Wale Ogunwalef6733932018-06-27 05:14:34 -0700892 UserManagerService getUserManager() {
893 if (mUserManager == null) {
894 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
895 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
896 }
897 return mUserManager;
898 }
899
Philip P. Moltmannee295092020-02-10 08:46:26 -0800900 AppOpsManager getAppOpsManager() {
901 if (mAppOpsManager == null) {
902 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Wale Ogunwalef6733932018-06-27 05:14:34 -0700903 }
Philip P. Moltmannee295092020-02-10 08:46:26 -0800904 return mAppOpsManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700905 }
906
907 boolean hasUserRestriction(String restriction, int userId) {
908 return getUserManager().hasUserRestriction(restriction, userId);
909 }
910
Michal Karpinski15486842019-04-25 17:33:42 +0100911 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
Philip P. Moltmannee295092020-02-10 08:46:26 -0800912 final int mode = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
913 callingUid, callingPackage, /* featureId */ null, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100914 if (mode == AppOpsManager.MODE_DEFAULT) {
915 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
916 == PERMISSION_GRANTED;
917 }
918 return mode == AppOpsManager.MODE_ALLOWED;
919 }
920
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700921 @VisibleForTesting
922 protected void setRecentTasks(RecentTasks recentTasks) {
923 mRecentTasks = recentTasks;
924 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700925 }
926
927 RecentTasks getRecentTasks() {
928 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700929 }
930
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700931 ClientLifecycleManager getLifecycleManager() {
932 return mLifecycleManager;
933 }
934
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700935 ActivityStartController getActivityStartController() {
936 return mActivityStartController;
937 }
938
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700939 TaskChangeNotificationController getTaskChangeNotificationController() {
940 return mTaskChangeNotificationController;
941 }
942
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700943 LockTaskController getLockTaskController() {
944 return mLockTaskController;
945 }
946
Yunfan Chen75157d72018-07-27 14:47:21 +0900947 /**
948 * Return the global configuration used by the process corresponding to the input pid. This is
949 * usually the global configuration with some overrides specific to that process.
950 */
951 Configuration getGlobalConfigurationForCallingPid() {
952 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800953 return getGlobalConfigurationForPid(pid);
954 }
955
956 /**
957 * Return the global configuration used by the process corresponding to the given pid.
958 */
959 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900960 if (pid == MY_PID || pid < 0) {
961 return getGlobalConfiguration();
962 }
963 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100964 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900965 return app != null ? app.getConfiguration() : getGlobalConfiguration();
966 }
967 }
968
969 /**
970 * Return the device configuration info used by the process corresponding to the input pid.
971 * The value is consistent with the global configuration for the process.
972 */
973 @Override
974 public ConfigurationInfo getDeviceConfigurationInfo() {
975 ConfigurationInfo config = new ConfigurationInfo();
976 synchronized (mGlobalLock) {
977 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
978 config.reqTouchScreen = globalConfig.touchscreen;
979 config.reqKeyboardType = globalConfig.keyboard;
980 config.reqNavigation = globalConfig.navigation;
981 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
982 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
983 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
984 }
985 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
986 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
987 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
988 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700989 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900990 }
991 return config;
992 }
993
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700994 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700995 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700996 }
997
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700998 public static final class Lifecycle extends SystemService {
999 private final ActivityTaskManagerService mService;
1000
1001 public Lifecycle(Context context) {
1002 super(context);
1003 mService = new ActivityTaskManagerService(context);
1004 }
1005
1006 @Override
1007 public void onStart() {
1008 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001009 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001010 }
1011
Garfield Tan891146c2018-10-09 12:14:00 -07001012 @Override
1013 public void onUnlockUser(int userId) {
1014 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001015 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001016 }
1017 }
1018
1019 @Override
1020 public void onCleanupUser(int userId) {
1021 synchronized (mService.getGlobalLock()) {
1022 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1023 }
1024 }
1025
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001026 public ActivityTaskManagerService getService() {
1027 return mService;
1028 }
1029 }
1030
1031 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001032 public final int startActivity(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001033 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1034 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1035 Bundle bOptions) {
1036 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1037 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038 UserHandle.getCallingUserId());
1039 }
1040
1041 @Override
1042 public final int startActivities(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001043 String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
1044 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001045 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001046 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001047 enforceNotIsolatedCaller(reason);
1048 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001049 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001050 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001051 callingFeatureId, intents, resolvedTypes, resultTo,
1052 SafeActivityOptions.fromBundle(bOptions), userId, reason,
1053 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001054 }
1055
1056 @Override
1057 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001058 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1059 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1060 Bundle bOptions, int userId) {
1061 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1062 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001063 true /*validateIncomingUser*/);
1064 }
1065
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001066 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001067 @Nullable String callingFeatureId, Intent intent, String resolvedType,
1068 IBinder resultTo, String resultWho, int requestCode, int startFlags,
1069 ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001070 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001071 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001072
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001073 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001074 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1075
1076 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001077 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001078 .setCaller(caller)
1079 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001080 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001081 .setResolvedType(resolvedType)
1082 .setResultTo(resultTo)
1083 .setResultWho(resultWho)
1084 .setRequestCode(requestCode)
1085 .setStartFlags(startFlags)
1086 .setProfilerInfo(profilerInfo)
1087 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001088 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001089 .execute();
1090
1091 }
1092
1093 @Override
1094 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1095 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001096 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1097 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001098 // Refuse possible leaked file descriptors
1099 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1100 throw new IllegalArgumentException("File descriptors passed in Intent");
1101 }
1102
1103 if (!(target instanceof PendingIntentRecord)) {
1104 throw new IllegalArgumentException("Bad PendingIntent object");
1105 }
1106
1107 PendingIntentRecord pir = (PendingIntentRecord)target;
1108
1109 synchronized (mGlobalLock) {
1110 // If this is coming from the currently resumed activity, it is
1111 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001112 final ActivityStack stack = getTopDisplayFocusedStack();
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001113 if (stack != null && stack.mResumedActivity != null
1114 && stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001115 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001116 }
1117 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001118 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001119 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001120 }
1121
1122 @Override
1123 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1124 Bundle bOptions) {
1125 // Refuse possible leaked file descriptors
1126 if (intent != null && intent.hasFileDescriptors()) {
1127 throw new IllegalArgumentException("File descriptors passed in Intent");
1128 }
1129 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1130
1131 synchronized (mGlobalLock) {
1132 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1133 if (r == null) {
1134 SafeActivityOptions.abort(options);
1135 return false;
1136 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001137 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001138 // The caller is not running... d'oh!
1139 SafeActivityOptions.abort(options);
1140 return false;
1141 }
1142 intent = new Intent(intent);
1143 // The caller is not allowed to change the data.
1144 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1145 // And we are resetting to find the next component...
1146 intent.setComponent(null);
1147
1148 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1149
1150 ActivityInfo aInfo = null;
1151 try {
1152 List<ResolveInfo> resolves =
1153 AppGlobals.getPackageManager().queryIntentActivities(
1154 intent, r.resolvedType,
1155 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1156 UserHandle.getCallingUserId()).getList();
1157
1158 // Look for the original activity in the list...
1159 final int N = resolves != null ? resolves.size() : 0;
1160 for (int i=0; i<N; i++) {
1161 ResolveInfo rInfo = resolves.get(i);
1162 if (rInfo.activityInfo.packageName.equals(r.packageName)
1163 && rInfo.activityInfo.name.equals(r.info.name)) {
1164 // We found the current one... the next matching is
1165 // after it.
1166 i++;
1167 if (i<N) {
1168 aInfo = resolves.get(i).activityInfo;
1169 }
1170 if (debug) {
1171 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1172 + "/" + r.info.name);
1173 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1174 ? "null" : aInfo.packageName + "/" + aInfo.name));
1175 }
1176 break;
1177 }
1178 }
1179 } catch (RemoteException e) {
1180 }
1181
1182 if (aInfo == null) {
1183 // Nobody who is next!
1184 SafeActivityOptions.abort(options);
1185 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1186 return false;
1187 }
1188
1189 intent.setComponent(new ComponentName(
1190 aInfo.applicationInfo.packageName, aInfo.name));
1191 intent.setFlags(intent.getFlags()&~(
1192 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1193 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1194 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1195 FLAG_ACTIVITY_NEW_TASK));
1196
1197 // Okay now we need to start the new activity, replacing the currently running activity.
1198 // This is a little tricky because we want to start the new one as if the current one is
1199 // finished, but not finish the current one first so that there is no flicker.
1200 // And thus...
1201 final boolean wasFinishing = r.finishing;
1202 r.finishing = true;
1203
1204 // Propagate reply information over to the new activity.
1205 final ActivityRecord resultTo = r.resultTo;
1206 final String resultWho = r.resultWho;
1207 final int requestCode = r.requestCode;
1208 r.resultTo = null;
1209 if (resultTo != null) {
1210 resultTo.removeResultsLocked(r, resultWho, requestCode);
1211 }
1212
1213 final long origId = Binder.clearCallingIdentity();
1214 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001215 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001216 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001217 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001218 .setResolvedType(r.resolvedType)
1219 .setActivityInfo(aInfo)
1220 .setResultTo(resultTo != null ? resultTo.appToken : null)
1221 .setResultWho(resultWho)
1222 .setRequestCode(requestCode)
1223 .setCallingPid(-1)
1224 .setCallingUid(r.launchedFromUid)
1225 .setCallingPackage(r.launchedFromPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001226 .setCallingFeatureId(r.launchedFromFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001227 .setRealCallingPid(-1)
1228 .setRealCallingUid(r.launchedFromUid)
1229 .setActivityOptions(options)
1230 .execute();
1231 Binder.restoreCallingIdentity(origId);
1232
1233 r.finishing = wasFinishing;
1234 if (res != ActivityManager.START_SUCCESS) {
1235 return false;
1236 }
1237 return true;
1238 }
1239 }
1240
1241 @Override
Galia Peycheva6861e912019-08-21 10:20:23 +02001242 public boolean startDreamActivity(Intent intent) {
Galia Peycheva52e89222020-02-18 23:41:43 +01001243 final WindowProcessController process = mProcessMap.getProcess(Binder.getCallingPid());
1244 final long origId = Binder.clearCallingIdentity();
1245
1246 // The dream activity is only called for non-doze dreams.
1247 final ComponentName currentDream = LocalServices.getService(DreamManagerInternal.class)
1248 .getActiveDreamComponent(/* doze= */ false);
1249
1250 if (currentDream == null || currentDream.getPackageName() == null
1251 || !currentDream.getPackageName().equals(process.mInfo.packageName)) {
1252 Slog.e(TAG, "Calling package is not the current dream package. "
1253 + "Aborting startDreamActivity...");
1254 return false;
1255 }
1256
Galia Peycheva6861e912019-08-21 10:20:23 +02001257 final ActivityInfo a = new ActivityInfo();
1258 a.theme = com.android.internal.R.style.Theme_Dream;
1259 a.exported = true;
1260 a.name = DreamActivity.class.getName();
1261
Galia Peycheva6861e912019-08-21 10:20:23 +02001262
1263 a.packageName = process.mInfo.packageName;
1264 a.applicationInfo = process.mInfo;
1265 a.processName = process.mInfo.processName;
1266 a.uiOptions = process.mInfo.uiOptions;
1267 a.taskAffinity = "android:" + a.packageName + "/dream";
1268 a.enabled = true;
1269 a.launchMode = ActivityInfo.LAUNCH_SINGLE_INSTANCE;
1270
1271 a.persistableMode = ActivityInfo.PERSIST_NEVER;
1272 a.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1273 a.colorMode = ActivityInfo.COLOR_MODE_DEFAULT;
1274 a.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1275
Galia Peycheva45f48d32020-02-20 15:39:10 +01001276 final ActivityOptions options = ActivityOptions.makeBasic();
1277 options.setLaunchActivityType(ACTIVITY_TYPE_DREAM);
1278
Galia Peycheva6861e912019-08-21 10:20:23 +02001279 try {
1280 getActivityStartController().obtainStarter(intent, "dream")
1281 .setActivityInfo(a)
Galia Peycheva45f48d32020-02-20 15:39:10 +01001282 .setActivityOptions(options.toBundle())
Galia Peycheva6861e912019-08-21 10:20:23 +02001283 .setIsDream(true)
1284 .execute();
1285 return true;
1286 } finally {
1287 Binder.restoreCallingIdentity(origId);
1288 }
1289 }
1290
1291 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001292 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001293 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1294 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1295 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001296 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001297 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001298 enforceNotIsolatedCaller("startActivityAndWait");
1299 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1300 userId, "startActivityAndWait");
1301 // TODO: Switch to user app stacks here.
1302 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1303 .setCaller(caller)
1304 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001305 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001306 .setResolvedType(resolvedType)
1307 .setResultTo(resultTo)
1308 .setResultWho(resultWho)
1309 .setRequestCode(requestCode)
1310 .setStartFlags(startFlags)
1311 .setActivityOptions(bOptions)
1312 .setUserId(userId)
1313 .setProfilerInfo(profilerInfo)
1314 .setWaitResult(res)
1315 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001316 return res;
1317 }
1318
1319 @Override
1320 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001321 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1322 String resultWho, int requestCode, int startFlags, Configuration config,
1323 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001324 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001325 enforceNotIsolatedCaller("startActivityWithConfig");
1326 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1327 "startActivityWithConfig");
1328 // TODO: Switch to user app stacks here.
1329 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1330 .setCaller(caller)
1331 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001332 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001333 .setResolvedType(resolvedType)
1334 .setResultTo(resultTo)
1335 .setResultWho(resultWho)
1336 .setRequestCode(requestCode)
1337 .setStartFlags(startFlags)
1338 .setGlobalConfiguration(config)
1339 .setActivityOptions(bOptions)
1340 .setUserId(userId)
1341 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001342 }
1343
Robert Carr8a2f9132019-11-11 15:03:15 -08001344 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001345 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1346 int callingUid = Binder.getCallingUid();
1347 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1348 throw new SecurityException("Only the system process can request a permission token, "
1349 + "received request from uid: " + callingUid);
1350 }
1351 IBinder permissionToken = new Binder();
1352 synchronized (mGlobalLock) {
1353 mStartActivitySources.put(permissionToken, delegatorToken);
1354 }
1355
1356 Message expireMsg = PooledLambda.obtainMessage(
1357 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1358 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1359
1360 Message forgetMsg = PooledLambda.obtainMessage(
1361 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1362 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1363
1364 return permissionToken;
1365 }
1366
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001367 @Override
1368 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1369 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001370 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1371 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001372 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001373 // permission grants) as any app that may launch one of your own activities. So we only
1374 // allow this in two cases:
1375 // 1) The caller is an activity that is part of the core framework, and then only when it
1376 // is running as the system.
1377 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1378 // can only be requested by a system activity, which may then delegate this call to
1379 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001380 final ActivityRecord sourceRecord;
1381 final int targetUid;
1382 final String targetPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001383 final String targetFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001384 final boolean isResolver;
1385 synchronized (mGlobalLock) {
1386 if (resultTo == null) {
1387 throw new SecurityException("Must be called from an activity");
1388 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001389 final IBinder sourceToken;
1390 if (permissionToken != null) {
1391 // To even attempt to use a permissionToken, an app must also have this signature
1392 // permission.
1393 mAmInternal.enforceCallingPermission(
1394 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1395 "startActivityAsCaller");
1396 // If called with a permissionToken, we want the sourceRecord from the delegator
1397 // activity that requested this token.
1398 sourceToken = mStartActivitySources.remove(permissionToken);
1399 if (sourceToken == null) {
1400 // Invalid permissionToken, check if it recently expired.
1401 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1402 throw new SecurityException("Called with expired permission token: "
1403 + permissionToken);
1404 } else {
1405 throw new SecurityException("Called with invalid permission token: "
1406 + permissionToken);
1407 }
1408 }
1409 } else {
1410 // This method was called directly by the source.
1411 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001412 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001413
Louis Chang149d5c82019-12-30 09:47:39 +08001414 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001415 if (sourceRecord == null) {
1416 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001417 }
1418 if (sourceRecord.app == null) {
1419 throw new SecurityException("Called without a process attached to activity");
1420 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001421
1422 // Whether called directly or from a delegate, the source activity must be from the
1423 // android package.
1424 if (!sourceRecord.info.packageName.equals("android")) {
1425 throw new SecurityException("Must be called from an activity that is "
1426 + "declared in the android package");
1427 }
1428
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001429 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001430 // This is still okay, as long as this activity is running under the
1431 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001432 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001433 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001434 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001435 + " must be system uid or original calling uid "
1436 + sourceRecord.launchedFromUid);
1437 }
1438 }
1439 if (ignoreTargetSecurity) {
1440 if (intent.getComponent() == null) {
1441 throw new SecurityException(
1442 "Component must be specified with ignoreTargetSecurity");
1443 }
1444 if (intent.getSelector() != null) {
1445 throw new SecurityException(
1446 "Selector not allowed with ignoreTargetSecurity");
1447 }
1448 }
1449 targetUid = sourceRecord.launchedFromUid;
1450 targetPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001451 targetFeatureId = sourceRecord.launchedFromFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452 isResolver = sourceRecord.isResolverOrChildActivity();
1453 }
1454
1455 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001456 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001457 }
1458
1459 // TODO: Switch to user app stacks here.
1460 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001461 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001462 .setCallingUid(targetUid)
1463 .setCallingPackage(targetPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001464 .setCallingFeatureId(targetFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465 .setResolvedType(resolvedType)
1466 .setResultTo(resultTo)
1467 .setResultWho(resultWho)
1468 .setRequestCode(requestCode)
1469 .setStartFlags(startFlags)
1470 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001471 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001472 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1473 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001474 // The target may well be in the background, which would normally prevent it
1475 // from starting an activity. Here we definitely want the start to succeed.
1476 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001477 .execute();
1478 } catch (SecurityException e) {
1479 // XXX need to figure out how to propagate to original app.
1480 // A SecurityException here is generally actually a fault of the original
1481 // calling activity (such as a fairly granting permissions), so propagate it
1482 // back to them.
1483 /*
1484 StringBuilder msg = new StringBuilder();
1485 msg.append("While launching");
1486 msg.append(intent.toString());
1487 msg.append(": ");
1488 msg.append(e.getMessage());
1489 */
1490 throw e;
1491 }
1492 }
1493
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001494 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1495 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001496 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001497 }
1498
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001499 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001500 public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1501 int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001502 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1503 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001504 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001505 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001506 if (session == null || interactor == null) {
1507 throw new NullPointerException("null session or interactor");
1508 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001509 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001510 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001511 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001512 .setCallingUid(callingUid)
1513 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001514 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001515 .setResolvedType(resolvedType)
1516 .setVoiceSession(session)
1517 .setVoiceInteractor(interactor)
1518 .setStartFlags(startFlags)
1519 .setProfilerInfo(profilerInfo)
1520 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001521 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001522 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001523 .execute();
1524 }
1525
1526 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001527 public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1528 int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1529 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001530 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001531 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1532 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001533
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001534 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001535 .setCallingUid(callingUid)
1536 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001537 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001538 .setResolvedType(resolvedType)
1539 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001540 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001541 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001542 .execute();
1543 }
1544
Riddle Hsu609a8e22019-06-27 16:46:29 -06001545 /**
1546 * Start the recents activity to perform the recents animation.
1547 *
1548 * @param intent The intent to start the recents activity.
1549 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1550 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001552 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1553 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001554 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001555 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001556 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001557 final long origId = Binder.clearCallingIdentity();
1558 try {
1559 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001560 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
Philip P. Moltmannee295092020-02-10 08:46:26 -08001561 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001562 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001563 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001564
1565 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001566 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001567 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001568 recentsFeatureId, recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001569 if (recentsAnimationRunner == null) {
1570 anim.preloadRecentsActivity();
1571 } else {
1572 anim.startRecentsActivity(recentsAnimationRunner);
1573 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001574 }
1575 } finally {
1576 Binder.restoreCallingIdentity(origId);
1577 }
1578 }
1579
1580 @Override
1581 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001582 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583 "startActivityFromRecents()");
1584
1585 final int callingPid = Binder.getCallingPid();
1586 final int callingUid = Binder.getCallingUid();
1587 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1588 final long origId = Binder.clearCallingIdentity();
1589 try {
1590 synchronized (mGlobalLock) {
1591 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1592 safeOptions);
1593 }
1594 } finally {
1595 Binder.restoreCallingIdentity(origId);
1596 }
1597 }
1598
1599 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001600 * Public API to check if the client is allowed to start an activity on specified display.
1601 *
1602 * If the target display is private or virtual, some restrictions will apply.
1603 *
1604 * @param displayId Target display id.
1605 * @param intent Intent used to launch the activity.
1606 * @param resolvedType The MIME type of the intent.
1607 * @param userId The id of the user for whom the call is made.
1608 * @return {@code true} if a call to start an activity on the target display should succeed and
1609 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1610 */
1611 @Override
1612 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1613 String resolvedType, int userId) {
1614 final int callingUid = Binder.getCallingUid();
1615 final int callingPid = Binder.getCallingPid();
1616 final long origId = Binder.clearCallingIdentity();
1617
1618 try {
1619 // Collect information about the target of the Intent.
1620 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1621 0 /* startFlags */, null /* profilerInfo */, userId,
1622 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1623 UserHandle.USER_NULL));
1624 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1625
1626 synchronized (mGlobalLock) {
1627 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1628 aInfo);
1629 }
1630 } finally {
1631 Binder.restoreCallingIdentity(origId);
1632 }
1633 }
1634
1635 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001636 * This is the internal entry point for handling Activity.finish().
1637 *
1638 * @param token The Binder token referencing the Activity we want to finish.
1639 * @param resultCode Result code, if any, from this Activity.
1640 * @param resultData Result data (Intent), if any, from this Activity.
1641 * @param finishTask Whether to finish the task associated with this Activity.
1642 *
1643 * @return Returns true if the activity successfully finished, or false if it is still running.
1644 */
1645 @Override
1646 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1647 int finishTask) {
1648 // Refuse possible leaked file descriptors
1649 if (resultData != null && resultData.hasFileDescriptors()) {
1650 throw new IllegalArgumentException("File descriptors passed in Intent");
1651 }
1652
1653 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001654 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001655 if (r == null) {
1656 return true;
1657 }
1658 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001659 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001660 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001661 if (rootR == null) {
1662 Slog.w(TAG, "Finishing task with all activities already finished");
1663 }
1664 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1665 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001666 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001667 return false;
1668 }
1669
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001670 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1671 // We should consolidate.
1672 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001673 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001674 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001675 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001676 if (next != null) {
1677 // ask watcher if this is allowed
1678 boolean resumeOK = true;
1679 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001680 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001681 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001682 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001683 Watchdog.getInstance().setActivityController(null);
1684 }
1685
1686 if (!resumeOK) {
1687 Slog.i(TAG, "Not finishing activity because controller resumed");
1688 return false;
1689 }
1690 }
1691 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001692
1693 // note down that the process has finished an activity and is in background activity
1694 // starts grace period
1695 if (r.app != null) {
1696 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1697 }
1698
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001699 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001700 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001701 try {
1702 boolean res;
1703 final boolean finishWithRootActivity =
1704 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1705 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1706 || (finishWithRootActivity && r == rootR)) {
1707 // If requested, remove the task that is associated to this activity only if it
1708 // was the root activity in the task. The result code and data is ignored
1709 // because we don't support returning them across task boundaries. Also, to
1710 // keep backwards compatibility we remove the task from recents when finishing
1711 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001712 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001713 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001714 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001715 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001716 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001717 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001718 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001719 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001720 if (!res) {
1721 Slog.i(TAG, "Failed to finish by app-request");
1722 }
1723 }
1724 return res;
1725 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001726 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001727 Binder.restoreCallingIdentity(origId);
1728 }
1729 }
1730 }
1731
1732 @Override
1733 public boolean finishActivityAffinity(IBinder token) {
1734 synchronized (mGlobalLock) {
1735 final long origId = Binder.clearCallingIdentity();
1736 try {
1737 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1738 if (r == null) {
1739 return false;
1740 }
1741
1742 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1743 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001744 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001745 return false;
1746 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001747
1748 final PooledFunction p = PooledLambda.obtainFunction(
1749 ActivityRecord::finishIfSameAffinity, r,
1750 PooledLambda.__(ActivityRecord.class));
1751 r.getTask().forAllActivities(
1752 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1753 p.recycle();
1754
Andrii Kuliande93eff2019-07-12 12:21:27 -07001755 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 } finally {
1757 Binder.restoreCallingIdentity(origId);
1758 }
1759 }
1760 }
1761
1762 @Override
1763 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1764 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001765 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001766 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001767 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001768 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1769 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001770 return;
1771 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001772 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1773 false /* processPausingActivities */, config);
1774 if (stopProfiling && r.hasProcess()) {
1775 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001776 }
1777 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001778 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001779 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001780 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001781 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001782 }
1783
1784 @Override
1785 public final void activityResumed(IBinder token) {
1786 final long origId = Binder.clearCallingIdentity();
1787 synchronized (mGlobalLock) {
1788 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001789 }
1790 Binder.restoreCallingIdentity(origId);
1791 }
1792
1793 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001794 public final void activityTopResumedStateLost() {
1795 final long origId = Binder.clearCallingIdentity();
1796 synchronized (mGlobalLock) {
1797 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1798 }
1799 Binder.restoreCallingIdentity(origId);
1800 }
1801
1802 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001803 public final void activityPaused(IBinder token) {
1804 final long origId = Binder.clearCallingIdentity();
1805 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001806 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001807 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1808 if (r != null) {
1809 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001810 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001811 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001812 }
1813 Binder.restoreCallingIdentity(origId);
1814 }
1815
1816 @Override
1817 public final void activityStopped(IBinder token, Bundle icicle,
1818 PersistableBundle persistentState, CharSequence description) {
1819 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1820
1821 // Refuse possible leaked file descriptors
1822 if (icicle != null && icicle.hasFileDescriptors()) {
1823 throw new IllegalArgumentException("File descriptors passed in Bundle");
1824 }
1825
1826 final long origId = Binder.clearCallingIdentity();
1827
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001828 String restartingName = null;
1829 int restartingUid = 0;
1830 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001831 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001832 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001833 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001834 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001835 if (r.attachedToProcess()
1836 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1837 // The activity was requested to restart from
1838 // {@link #restartActivityProcessIfVisible}.
1839 restartingName = r.app.mName;
1840 restartingUid = r.app.mUid;
1841 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001842 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001843 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001844 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001845 }
1846
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001847 if (restartingName != null) {
1848 // In order to let the foreground activity can be restarted with its saved state from
1849 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1850 // until the activity reports stopped with the state. And the activity record will be
1851 // kept because the record state is restarting, then the activity will be restarted
1852 // immediately if it is still the top one.
1853 mStackSupervisor.removeRestartTimeouts(r);
1854 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1855 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001856 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001857
1858 Binder.restoreCallingIdentity(origId);
1859 }
1860
1861 @Override
1862 public final void activityDestroyed(IBinder token) {
1863 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1864 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001865 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001866 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001867 try {
1868 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1869 if (activity != null) {
1870 activity.destroyed("activityDestroyed");
1871 }
1872 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001873 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001874 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001875 }
1876 }
1877 }
1878
1879 @Override
1880 public final void activityRelaunched(IBinder token) {
1881 final long origId = Binder.clearCallingIdentity();
1882 synchronized (mGlobalLock) {
1883 mStackSupervisor.activityRelaunchedLocked(token);
1884 }
1885 Binder.restoreCallingIdentity(origId);
1886 }
1887
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001888 @Override
1889 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1890 synchronized (mGlobalLock) {
1891 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1892 if (r == null) {
1893 return;
1894 }
1895 final long origId = Binder.clearCallingIdentity();
1896 try {
1897 r.setRequestedOrientation(requestedOrientation);
1898 } finally {
1899 Binder.restoreCallingIdentity(origId);
1900 }
1901 }
1902 }
1903
1904 @Override
1905 public int getRequestedOrientation(IBinder token) {
1906 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001907 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1908 return (r != null)
1909 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001910 }
1911 }
1912
1913 @Override
1914 public void setImmersive(IBinder token, boolean immersive) {
1915 synchronized (mGlobalLock) {
1916 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1917 if (r == null) {
1918 throw new IllegalArgumentException();
1919 }
1920 r.immersive = immersive;
1921
1922 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001923 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001924 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001925 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001926 }
1927 }
1928 }
1929
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001930 void applyUpdateLockStateLocked(ActivityRecord r) {
1931 // Modifications to the UpdateLock state are done on our handler, outside
1932 // the activity manager's locks. The new state is determined based on the
1933 // state *now* of the relevant activity record. The object is passed to
1934 // the handler solely for logging detail, not to be consulted/modified.
1935 final boolean nextState = r != null && r.immersive;
1936 mH.post(() -> {
1937 if (mUpdateLock.isHeld() != nextState) {
1938 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1939 "Applying new update lock state '" + nextState + "' for " + r);
1940 if (nextState) {
1941 mUpdateLock.acquire();
1942 } else {
1943 mUpdateLock.release();
1944 }
1945 }
1946 });
1947 }
1948
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001949 @Override
1950 public boolean isImmersive(IBinder token) {
1951 synchronized (mGlobalLock) {
1952 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1953 if (r == null) {
1954 throw new IllegalArgumentException();
1955 }
1956 return r.immersive;
1957 }
1958 }
1959
1960 @Override
1961 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001962 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001963 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001964 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
1965 if (topFocusedStack == null) {
1966 return false;
1967 }
1968
1969 final ActivityRecord r = topFocusedStack.topRunningActivity();
1970 return r != null && r.immersive;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001971 }
1972 }
1973
1974 @Override
1975 public void overridePendingTransition(IBinder token, String packageName,
1976 int enterAnim, int exitAnim) {
1977 synchronized (mGlobalLock) {
1978 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1979 if (self == null) {
1980 return;
1981 }
1982
1983 final long origId = Binder.clearCallingIdentity();
1984
1985 if (self.isState(
1986 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001987 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001988 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001989 }
1990
1991 Binder.restoreCallingIdentity(origId);
1992 }
1993 }
1994
1995 @Override
1996 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001997 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001998 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001999 final ActivityStack stack = getTopDisplayFocusedStack();
2000 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002001 if (r == null) {
2002 return ActivityManager.COMPAT_MODE_UNKNOWN;
2003 }
Wale Ogunwale53783742018-09-16 10:21:51 -07002004 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002005 }
2006 }
2007
2008 @Override
2009 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002010 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002011 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002012 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002013 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002014 final ActivityStack stack = getTopDisplayFocusedStack();
2015 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002016 if (r == null) {
2017 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
2018 return;
2019 }
2020 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07002021 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002022 }
2023 }
2024
2025 @Override
2026 public int getLaunchedFromUid(IBinder activityToken) {
2027 ActivityRecord srec;
2028 synchronized (mGlobalLock) {
2029 srec = ActivityRecord.forTokenLocked(activityToken);
2030 }
2031 if (srec == null) {
2032 return -1;
2033 }
2034 return srec.launchedFromUid;
2035 }
2036
2037 @Override
2038 public String getLaunchedFromPackage(IBinder activityToken) {
2039 ActivityRecord srec;
2040 synchronized (mGlobalLock) {
2041 srec = ActivityRecord.forTokenLocked(activityToken);
2042 }
2043 if (srec == null) {
2044 return null;
2045 }
2046 return srec.launchedFromPackage;
2047 }
2048
2049 @Override
2050 public boolean convertFromTranslucent(IBinder token) {
2051 final long origId = Binder.clearCallingIdentity();
2052 try {
2053 synchronized (mGlobalLock) {
2054 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2055 if (r == null) {
2056 return false;
2057 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002058 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002059 }
2060 } finally {
2061 Binder.restoreCallingIdentity(origId);
2062 }
2063 }
2064
2065 @Override
2066 public boolean convertToTranslucent(IBinder token, Bundle options) {
2067 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2068 final long origId = Binder.clearCallingIdentity();
2069 try {
2070 synchronized (mGlobalLock) {
2071 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2072 if (r == null) {
2073 return false;
2074 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002075 final ActivityRecord under = r.getTask().getActivityBelow(r);
2076 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002077 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2078 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002079 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002080 }
2081 } finally {
2082 Binder.restoreCallingIdentity(origId);
2083 }
2084 }
2085
2086 @Override
2087 public void notifyActivityDrawn(IBinder token) {
2088 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2089 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002090 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002091 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002092 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002093 }
2094 }
2095 }
2096
2097 @Override
2098 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2099 synchronized (mGlobalLock) {
2100 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2101 if (r == null) {
2102 return;
2103 }
2104 r.reportFullyDrawnLocked(restoredFromBundle);
2105 }
2106 }
2107
2108 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002109 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002110 synchronized (mGlobalLock) {
2111 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002112 if (stack != null) {
2113 final int displayId = stack.getDisplayId();
2114 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002115 }
2116 return DEFAULT_DISPLAY;
2117 }
2118 }
2119
2120 @Override
2121 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002122 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002123 long ident = Binder.clearCallingIdentity();
2124 try {
2125 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002126 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002127 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002128 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002129 }
2130 return null;
2131 }
2132 } finally {
2133 Binder.restoreCallingIdentity(ident);
2134 }
2135 }
2136
2137 @Override
2138 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002139 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002140 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2141 final long callingId = Binder.clearCallingIdentity();
2142 try {
2143 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002144 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002145 if (stack == null) {
2146 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2147 return;
2148 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002149 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002150 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002151 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002152 }
2153 }
2154 } finally {
2155 Binder.restoreCallingIdentity(callingId);
2156 }
2157 }
2158
2159 @Override
2160 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002161 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002162 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2163 final long callingId = Binder.clearCallingIdentity();
2164 try {
2165 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002166 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002167 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002168 if (task == null) {
2169 return;
2170 }
2171 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002172 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002173 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002174 }
2175 }
2176 } finally {
2177 Binder.restoreCallingIdentity(callingId);
2178 }
2179 }
2180
2181 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002182 public void restartActivityProcessIfVisible(IBinder activityToken) {
2183 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2184 final long callingId = Binder.clearCallingIdentity();
2185 try {
2186 synchronized (mGlobalLock) {
2187 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2188 if (r == null) {
2189 return;
2190 }
2191 r.restartProcessIfVisible();
2192 }
2193 } finally {
2194 Binder.restoreCallingIdentity(callingId);
2195 }
2196 }
2197
2198 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002199 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002200 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002201 synchronized (mGlobalLock) {
2202 final long ident = Binder.clearCallingIdentity();
2203 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002204 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002205 "remove-task");
2206 } finally {
2207 Binder.restoreCallingIdentity(ident);
2208 }
2209 }
2210 }
2211
2212 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002213 public void removeAllVisibleRecentTasks() {
2214 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2215 synchronized (mGlobalLock) {
2216 final long ident = Binder.clearCallingIdentity();
2217 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002218 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002219 } finally {
2220 Binder.restoreCallingIdentity(ident);
2221 }
2222 }
2223 }
2224
2225 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002226 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2227 synchronized (mGlobalLock) {
2228 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2229 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002230 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002231 }
2232 }
2233 return false;
2234 }
2235
2236 @Override
2237 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2238 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002239
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002240 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002241 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2242 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002243 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002244 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002245 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002246 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002247 }
2248 }
2249
2250 /**
2251 * Attempts to move a task backwards in z-order (the order of activities within the task is
2252 * unchanged).
2253 *
2254 * There are several possible results of this call:
2255 * - if the task is locked, then we will show the lock toast
2256 * - if there is a task behind the provided task, then that task is made visible and resumed as
2257 * this task is moved to the back
2258 * - otherwise, if there are no other tasks in the stack:
2259 * - if this task is in the pinned stack, then we remove the stack completely, which will
2260 * have the effect of moving the task to the top or bottom of the fullscreen stack
2261 * (depending on whether it is visible)
2262 * - otherwise, we simply return home and hide this task
2263 *
2264 * @param token A reference to the activity we wish to move
2265 * @param nonRoot If false then this only works if the activity is the root
2266 * of a task; if true it will work for any activity in a task.
2267 * @return Returns true if the move completed, false if not.
2268 */
2269 @Override
2270 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002271 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002272 synchronized (mGlobalLock) {
2273 final long origId = Binder.clearCallingIdentity();
2274 try {
2275 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002276 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002277 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002278 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002279 }
2280 } finally {
2281 Binder.restoreCallingIdentity(origId);
2282 }
2283 }
2284 return false;
2285 }
2286
2287 @Override
2288 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002289 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002290 long ident = Binder.clearCallingIdentity();
2291 Rect rect = new Rect();
2292 try {
2293 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002294 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002295 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2296 if (task == null) {
2297 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2298 return rect;
2299 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002300 if (task.getParent() != null) {
2301 rect.set(task.getBounds());
2302 } else if (task.mLastNonFullscreenBounds != null) {
2303 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002304 }
2305 }
2306 } finally {
2307 Binder.restoreCallingIdentity(ident);
2308 }
2309 return rect;
2310 }
2311
2312 @Override
2313 public ActivityManager.TaskDescription getTaskDescription(int id) {
2314 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002315 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002316 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002317 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002318 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2319 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002320 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002321 }
2322 }
2323 return null;
2324 }
2325
2326 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002327 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002328 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08002329 return setTaskWindowingModeSplitScreenPrimary(taskId, toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002330 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002331 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002332 synchronized (mGlobalLock) {
2333 final long ident = Binder.clearCallingIdentity();
2334 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002335 if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2336 return setTaskWindowingModeSplitScreen(taskId, windowingMode, toTop);
2337 }
Louis Chang149d5c82019-12-30 09:47:39 +08002338 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002339 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002340 if (task == null) {
2341 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002342 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002343 }
2344
2345 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2346 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2347
2348 if (!task.isActivityTypeStandardOrUndefined()) {
2349 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2350 + " non-standard task " + taskId + " to windowing mode="
2351 + windowingMode);
2352 }
2353
2354 final ActivityStack stack = task.getStack();
2355 if (toTop) {
2356 stack.moveToFront("setTaskWindowingMode", task);
2357 }
Louis Changa009c762020-02-26 11:21:31 +08002358 // Convert some windowing-mode changes into root-task reparents for split-screen.
2359 if (stack.inSplitScreenWindowingMode()) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07002360 stack.getDisplayArea().onSplitScreenModeDismissed();
Louis Changa009c762020-02-26 11:21:31 +08002361
2362 } else {
2363 stack.setWindowingMode(windowingMode);
2364 stack.getDisplay().ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2365 true /* notifyClients */);
2366 }
Winson Chung7ccc6812020-01-23 16:15:10 -08002367 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002368 } finally {
2369 Binder.restoreCallingIdentity(ident);
2370 }
2371 }
2372 }
2373
2374 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002375 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002376 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002377 ActivityRecord r = getCallingRecordLocked(token);
2378 return r != null ? r.info.packageName : null;
2379 }
2380 }
2381
2382 @Override
2383 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002384 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002385 ActivityRecord r = getCallingRecordLocked(token);
2386 return r != null ? r.intent.getComponent() : null;
2387 }
2388 }
2389
2390 private ActivityRecord getCallingRecordLocked(IBinder token) {
2391 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2392 if (r == null) {
2393 return null;
2394 }
2395 return r.resultTo;
2396 }
2397
2398 @Override
2399 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002400 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002401
2402 synchronized (mGlobalLock) {
2403 final long origId = Binder.clearCallingIdentity();
2404 try {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002405 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
2406 if (topFocusedStack != null) {
2407 topFocusedStack.unhandledBackLocked();
2408 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002409 } finally {
2410 Binder.restoreCallingIdentity(origId);
2411 }
2412 }
2413 }
2414
Mark Renouf446251d2019-04-26 10:22:41 -04002415 @Override
2416 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2417 synchronized (mGlobalLock) {
2418 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2419 if (r == null) {
2420 return;
2421 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002422 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002423 if (stack != null && stack.isSingleTaskInstance()) {
2424 // Single-task stacks are used for activities which are presented in floating
2425 // windows above full screen activities. Instead of directly finishing the
2426 // task, a task change listener is used to notify SystemUI so the action can be
2427 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002428 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002429 mTaskChangeNotificationController
2430 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2431 } else {
2432 try {
2433 callback.requestFinish();
2434 } catch (RemoteException e) {
2435 Slog.e(TAG, "Failed to invoke request finish callback", e);
2436 }
2437 }
2438 }
2439 }
2440
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002441 /**
2442 * TODO: Add mController hook
2443 */
2444 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002445 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2446 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002447 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002448
2449 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2450 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002451 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2452 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002453 }
2454 }
2455
Ricky Waiaca8a772019-04-04 16:01:06 +01002456 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2457 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002458 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002459 final int callingPid = Binder.getCallingPid();
2460 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002461 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002462 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002463 SafeActivityOptions.abort(options);
2464 return;
2465 }
2466 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002467 WindowProcessController callerApp = null;
2468 if (appThread != null) {
2469 callerApp = getProcessController(appThread);
2470 }
2471 final ActivityStarter starter = getActivityStartController().obtainStarter(
2472 null /* intent */, "moveTaskToFront");
2473 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
Galia Peycheva6861e912019-08-21 10:20:23 +02002474 -1, callerApp, null, false, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002475 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002476 return;
2477 }
2478 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002479 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002480 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002481 if (task == null) {
2482 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002483 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002484 return;
2485 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002486 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002487 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002488 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002489 return;
2490 }
2491 ActivityOptions realOptions = options != null
2492 ? options.getOptions(mStackSupervisor)
2493 : null;
2494 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2495 false /* forceNonResizable */);
2496
Wale Ogunwale21e06482019-11-18 05:14:15 -08002497 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002498 if (topActivity != null) {
2499
2500 // We are reshowing a task, use a starting window to hide the initial draw delay
2501 // so the transition can start earlier.
2502 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2503 true /* taskSwitch */, fromRecents);
2504 }
2505 } finally {
2506 Binder.restoreCallingIdentity(origId);
2507 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002508 }
2509
Ricky Waiaca8a772019-04-04 16:01:06 +01002510 /**
2511 * Return true if callingUid is system, or packageName belongs to that callingUid.
2512 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002513 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002514 try {
2515 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2516 if (packageName == null) {
2517 return false;
2518 }
2519 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2520 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2521 UserHandle.getUserId(callingUid));
2522 return UserHandle.isSameApp(callingUid, uid);
2523 }
2524 } catch (RemoteException e) {
2525 // Should not happen
2526 }
2527 return true;
2528 }
2529
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002530 /**
2531 * Checks that the provided package name matches the current calling UID, throws a security
2532 * exception if it doesn't.
2533 */
2534 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2535 final int callingUid = Binder.getCallingUid();
2536 if (isSameApp(callingUid, packageName)) {
2537 return;
2538 }
2539 final String msg = "Permission Denial: package=" + packageName
2540 + " does not belong to uid=" + callingUid;
2541 Slog.w(TAG, msg);
2542 throw new SecurityException(msg);
2543 }
2544
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002545 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2546 int callingPid, int callingUid, String name) {
2547 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2548 return true;
2549 }
2550
2551 if (getRecentTasks().isCallerRecents(sourceUid)) {
2552 return true;
2553 }
2554
2555 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2556 if (perm == PackageManager.PERMISSION_GRANTED) {
2557 return true;
2558 }
2559 if (checkAllowAppSwitchUid(sourceUid)) {
2560 return true;
2561 }
2562
2563 // If the actual IPC caller is different from the logical source, then
2564 // also see if they are allowed to control app switches.
2565 if (callingUid != -1 && callingUid != sourceUid) {
2566 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2567 if (perm == PackageManager.PERMISSION_GRANTED) {
2568 return true;
2569 }
2570 if (checkAllowAppSwitchUid(callingUid)) {
2571 return true;
2572 }
2573 }
2574
2575 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2576 return false;
2577 }
2578
2579 private boolean checkAllowAppSwitchUid(int uid) {
2580 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2581 if (types != null) {
2582 for (int i = types.size() - 1; i >= 0; i--) {
2583 if (types.valueAt(i).intValue() == uid) {
2584 return true;
2585 }
2586 }
2587 }
2588 return false;
2589 }
2590
2591 @Override
2592 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2593 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2594 "setActivityController()");
2595 synchronized (mGlobalLock) {
2596 mController = controller;
2597 mControllerIsAMonkey = imAMonkey;
2598 Watchdog.getInstance().setActivityController(controller);
2599 }
2600 }
2601
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002602 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002603 synchronized (mGlobalLock) {
2604 return mController != null && mControllerIsAMonkey;
2605 }
2606 }
2607
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002608 @Override
2609 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2610 synchronized (mGlobalLock) {
2611 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2612 }
2613 }
2614
2615 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002616 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
Winson Chunge5ab0172020-03-21 23:00:24 -07002617 return getFilteredTasks(maxNum, false /* filterForVisibleRecents */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002618 }
2619
Winson Chunge5ab0172020-03-21 23:00:24 -07002620 /**
2621 * @param filterOnlyVisibleRecents whether to filter the tasks based on whether they would ever
2622 * be visible in the recent task list in systemui
2623 */
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002624 @Override
2625 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
Winson Chunge5ab0172020-03-21 23:00:24 -07002626 boolean filterOnlyVisibleRecents) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002627 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002628 final int callingPid = Binder.getCallingPid();
2629 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002630 final int[] profileIds = getUserManager().getProfileIds(
2631 UserHandle.getUserId(callingUid), true);
2632 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2633 for (int i = 0; i < profileIds.length; i++) {
2634 callingProfileIds.add(profileIds[i]);
2635 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002636 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2637
2638 synchronized (mGlobalLock) {
2639 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2640
Nicholas Sauer0259e532019-08-30 08:24:55 -07002641 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Winson Chunge5ab0172020-03-21 23:00:24 -07002642 mRootWindowContainer.getRunningTasks(maxNum, list, filterOnlyVisibleRecents, callingUid,
2643 allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002644 }
2645
2646 return list;
2647 }
2648
2649 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002650 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2651 synchronized (mGlobalLock) {
2652 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002653 try {
2654 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2655 if (r == null) return;
2656
2657 final PooledConsumer c = PooledLambda.obtainConsumer(
2658 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2659 r, resultWho, requestCode);
2660 // TODO: This should probably only loop over the task since you need to be in the
2661 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002662 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002663 c.recycle();
2664
2665 updateOomAdj();
2666 } finally {
2667 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002668 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002669 }
2670 }
2671
2672 @Override
2673 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002674 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002675 ActivityStack stack = ActivityRecord.getStackLocked(token);
2676 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002677 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002678 }
2679 return false;
2680 }
2681 }
2682
2683 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002684 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002685 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002686 synchronized (mGlobalLock) {
2687 final long ident = Binder.clearCallingIdentity();
2688 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002689 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002690 if (task == null) {
2691 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2692 return;
2693 }
2694
2695 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2696 + " to stackId=" + stackId + " toTop=" + toTop);
2697
Louis Chang149d5c82019-12-30 09:47:39 +08002698 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002699 if (stack == null) {
2700 throw new IllegalStateException(
2701 "moveTaskToStack: No stack for stackId=" + stackId);
2702 }
2703 if (!stack.isActivityTypeStandardOrUndefined()) {
2704 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2705 + taskId + " to stack " + stackId);
2706 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002707 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2708 "moveTaskToStack");
2709 } finally {
2710 Binder.restoreCallingIdentity(ident);
2711 }
2712 }
2713 }
2714
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002715 /**
2716 * Moves the specified task to the primary-split-screen stack.
2717 *
2718 * @param taskId Id of task to move.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002719 * @param toTop If the task and stack should be moved to the top.
Winson Chung7ccc6812020-01-23 16:15:10 -08002720 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002721 */
2722 @Override
Evan Rosky73a7fe92019-11-18 18:28:01 -08002723 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002724 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002725 "setTaskWindowingModeSplitScreenPrimary()");
2726 synchronized (mGlobalLock) {
2727 final long ident = Binder.clearCallingIdentity();
2728 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002729 return setTaskWindowingModeSplitScreen(taskId, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY,
2730 toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002731 } finally {
2732 Binder.restoreCallingIdentity(ident);
2733 }
2734 }
2735 }
2736
2737 /**
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002738 * Moves the specified task into a split-screen tile.
2739 */
2740 private boolean setTaskWindowingModeSplitScreen(int taskId, int windowingMode, boolean toTop) {
2741 if (!WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2742 throw new IllegalArgumentException("Calling setTaskWindowingModeSplitScreen with non"
2743 + "split-screen mode: " + windowingMode);
2744 }
2745 if (isInLockTaskMode()) {
2746 Slog.w(TAG, "setTaskWindowingModeSplitScreen: Is in lock task mode="
2747 + getLockTaskModeState());
2748 return false;
2749 }
2750
2751 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2752 MATCH_TASK_IN_STACKS_ONLY);
2753 if (task == null) {
2754 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2755 return false;
2756 }
2757 if (!task.isActivityTypeStandardOrUndefined()) {
2758 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2759 + " non-standard task " + taskId + " to split-screen windowing mode");
2760 }
Wale Ogunwale0d465192020-01-23 19:14:44 -08002761 if (!task.supportsSplitScreenWindowingMode()) {
2762 return false;
2763 }
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002764
2765 final int prevMode = task.getWindowingMode();
Louis Changa009c762020-02-26 11:21:31 +08002766 moveTaskToSplitScreenPrimaryTask(task, toTop);
Wale Ogunwale0d465192020-01-23 19:14:44 -08002767 return prevMode != task.getWindowingMode();
2768 }
2769
Louis Changa009c762020-02-26 11:21:31 +08002770 void moveTaskToSplitScreenPrimaryTask(Task task, boolean toTop) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07002771 final TaskDisplayArea taskDisplayArea = task.getDisplayArea();
2772 final ActivityStack primarySplitTask = taskDisplayArea.getRootSplitScreenPrimaryTask();
Louis Changa009c762020-02-26 11:21:31 +08002773 if (primarySplitTask == null) {
2774 throw new IllegalStateException("Can't enter split without associated organized task");
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002775 }
Louis Changa009c762020-02-26 11:21:31 +08002776
2777 if (toTop) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07002778 taskDisplayArea.positionStackAt(POSITION_TOP, primarySplitTask,
Andrii Kulian9ea12da2020-03-27 17:16:38 -07002779 false /* includingParents */);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002780 }
2781 WindowContainerTransaction wct = new WindowContainerTransaction();
Louis Changa009c762020-02-26 11:21:31 +08002782 wct.reparent(task.getStack().mRemoteToken, primarySplitTask.mRemoteToken, toTop);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07002783 mWindowOrganizerController.applyTransaction(wct);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002784 }
2785
2786 /**
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002787 * Removes stacks in the input windowing modes from the system if they are of activity type
2788 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2789 */
2790 @Override
2791 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002792 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002793 "removeStacksInWindowingModes()");
2794
2795 synchronized (mGlobalLock) {
2796 final long ident = Binder.clearCallingIdentity();
2797 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002798 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002799 } finally {
2800 Binder.restoreCallingIdentity(ident);
2801 }
2802 }
2803 }
2804
2805 @Override
2806 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002807 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002808 "removeStacksWithActivityTypes()");
2809
2810 synchronized (mGlobalLock) {
2811 final long ident = Binder.clearCallingIdentity();
2812 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002813 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002814 } finally {
2815 Binder.restoreCallingIdentity(ident);
2816 }
2817 }
2818 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002819
2820 @Override
2821 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2822 int userId) {
2823 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002824 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2825 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002827 synchronized (mGlobalLock) {
Winson Chung66b08f02020-03-03 14:32:35 -08002828 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, userId, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002829 }
2830 }
2831
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002832 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002833 @Override
2834 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002835 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002836 long ident = Binder.clearCallingIdentity();
2837 try {
2838 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002839 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002840 }
2841 } finally {
2842 Binder.restoreCallingIdentity(ident);
2843 }
2844 }
2845
2846 @Override
2847 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002848 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002849 long ident = Binder.clearCallingIdentity();
2850 try {
2851 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002852 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002853 }
2854 } finally {
2855 Binder.restoreCallingIdentity(ident);
2856 }
2857 }
2858
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002859 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002860 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002861 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2862 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2863 long ident = Binder.clearCallingIdentity();
2864 try {
2865 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002866 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002867 }
2868 } finally {
2869 Binder.restoreCallingIdentity(ident);
2870 }
2871 }
2872
2873 @Override
2874 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2875 int displayId) {
2876 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2877 long ident = Binder.clearCallingIdentity();
2878 try {
2879 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002880 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002881 }
2882 } finally {
2883 Binder.restoreCallingIdentity(ident);
2884 }
2885 }
2886
2887 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002888 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002889 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002890 final long callingUid = Binder.getCallingUid();
2891 final long origId = Binder.clearCallingIdentity();
2892 try {
2893 synchronized (mGlobalLock) {
2894 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002895 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002896 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2897 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2898 }
2899 } finally {
2900 Binder.restoreCallingIdentity(origId);
2901 }
2902 }
2903
2904 @Override
2905 public void startLockTaskModeByToken(IBinder token) {
2906 synchronized (mGlobalLock) {
2907 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2908 if (r == null) {
2909 return;
2910 }
Louis Changcdec0802019-11-11 11:45:07 +08002911 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002912 }
2913 }
2914
2915 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002916 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002917 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002918 // This makes inner call to look as if it was initiated by system.
2919 long ident = Binder.clearCallingIdentity();
2920 try {
2921 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002922 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002923 MATCH_TASK_IN_STACKS_ONLY);
2924 if (task == null) {
2925 return;
2926 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927
2928 // When starting lock task mode the stack must be in front and focused
2929 task.getStack().moveToFront("startSystemLockTaskMode");
2930 startLockTaskModeLocked(task, true /* isSystemCaller */);
2931 }
2932 } finally {
2933 Binder.restoreCallingIdentity(ident);
2934 }
2935 }
2936
2937 @Override
2938 public void stopLockTaskModeByToken(IBinder token) {
2939 synchronized (mGlobalLock) {
2940 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2941 if (r == null) {
2942 return;
2943 }
Louis Changcdec0802019-11-11 11:45:07 +08002944 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002945 }
2946 }
2947
2948 /**
2949 * This API should be called by SystemUI only when user perform certain action to dismiss
2950 * lock task mode. We should only dismiss pinned lock task mode in this case.
2951 */
2952 @Override
2953 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002954 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002955 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2956 }
2957
Louis Changcdec0802019-11-11 11:45:07 +08002958 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002959 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2960 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2961 return;
2962 }
2963
Louis Chang149d5c82019-12-30 09:47:39 +08002964 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002965 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002966 throw new IllegalArgumentException("Invalid task, not in foreground");
2967 }
2968
2969 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2970 // system or a specific app.
2971 // * System-initiated requests will only start the pinned mode (screen pinning)
2972 // * App-initiated requests
2973 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2974 // - will start the pinned mode, otherwise
2975 final int callingUid = Binder.getCallingUid();
2976 long ident = Binder.clearCallingIdentity();
2977 try {
2978 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002979 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002980
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002981 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982 } finally {
2983 Binder.restoreCallingIdentity(ident);
2984 }
2985 }
2986
Louis Changcdec0802019-11-11 11:45:07 +08002987 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002988 final int callingUid = Binder.getCallingUid();
2989 long ident = Binder.clearCallingIdentity();
2990 try {
2991 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002992 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002993 }
2994 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2995 // task and jumping straight into a call in the case of emergency call back.
2996 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2997 if (tm != null) {
2998 tm.showInCallScreen(false);
2999 }
3000 } finally {
3001 Binder.restoreCallingIdentity(ident);
3002 }
3003 }
3004
3005 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003006 public void updateLockTaskPackages(int userId, String[] packages) {
3007 final int callingUid = Binder.getCallingUid();
3008 if (callingUid != 0 && callingUid != SYSTEM_UID) {
3009 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
3010 "updateLockTaskPackages()");
3011 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08003012 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003013 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
3014 + Arrays.toString(packages));
3015 getLockTaskController().updateLockTaskPackages(userId, packages);
3016 }
3017 }
3018
3019 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003020 public boolean isInLockTaskMode() {
3021 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3022 }
3023
3024 @Override
3025 public int getLockTaskModeState() {
3026 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003027 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003028 }
3029 }
3030
3031 @Override
3032 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3033 synchronized (mGlobalLock) {
3034 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3035 if (r != null) {
3036 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003037 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003038 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003039 }
3040 }
3041 }
3042
3043 @Override
3044 public Bundle getActivityOptions(IBinder token) {
3045 final long origId = Binder.clearCallingIdentity();
3046 try {
3047 synchronized (mGlobalLock) {
3048 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3049 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003050 final ActivityOptions activityOptions = r.takeOptionsLocked(
3051 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003052 return activityOptions == null ? null : activityOptions.toBundle();
3053 }
3054 return null;
3055 }
3056 } finally {
3057 Binder.restoreCallingIdentity(origId);
3058 }
3059 }
3060
3061 @Override
3062 public List<IBinder> getAppTasks(String callingPackage) {
3063 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003064 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003065 long ident = Binder.clearCallingIdentity();
3066 try {
3067 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003068 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003069 }
3070 } finally {
3071 Binder.restoreCallingIdentity(ident);
3072 }
3073 }
3074
3075 @Override
3076 public void finishVoiceTask(IVoiceInteractionSession session) {
3077 synchronized (mGlobalLock) {
3078 final long origId = Binder.clearCallingIdentity();
3079 try {
3080 // TODO: VI Consider treating local voice interactions and voice tasks
3081 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003082 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003083 } finally {
3084 Binder.restoreCallingIdentity(origId);
3085 }
3086 }
3087
3088 }
3089
3090 @Override
3091 public boolean isTopOfTask(IBinder token) {
3092 synchronized (mGlobalLock) {
3093 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003094 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003095 }
3096 }
3097
3098 @Override
3099 public void notifyLaunchTaskBehindComplete(IBinder token) {
3100 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3101 }
3102
3103 @Override
3104 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003105 mH.post(() -> {
3106 synchronized (mGlobalLock) {
3107 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003108 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003109 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003110 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003111 } catch (RemoteException e) {
3112 }
3113 }
3114 }
3115
3116 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003117 }
3118
3119 /** Called from an app when assist data is ready. */
3120 @Override
3121 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3122 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003123 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003124 synchronized (pae) {
3125 pae.result = extras;
3126 pae.structure = structure;
3127 pae.content = content;
3128 if (referrer != null) {
3129 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3130 }
3131 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003132 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003133 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003134 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003135 structure.setHomeActivity(pae.isHome);
3136 }
3137 pae.haveResult = true;
3138 pae.notifyAll();
3139 if (pae.intent == null && pae.receiver == null) {
3140 // Caller is just waiting for the result.
3141 return;
3142 }
3143 }
3144 // We are now ready to launch the assist activity.
3145 IAssistDataReceiver sendReceiver = null;
3146 Bundle sendBundle = null;
3147 synchronized (mGlobalLock) {
3148 buildAssistBundleLocked(pae, extras);
3149 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003150 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003151 if (!exists) {
3152 // Timed out.
3153 return;
3154 }
3155
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003156 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003157 // Caller wants result sent back to them.
3158 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003159 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003160 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003161 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3162 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003163 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3164 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3165 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3166 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3167 }
3168 }
3169 if (sendReceiver != null) {
3170 try {
3171 sendReceiver.onHandleAssistData(sendBundle);
3172 } catch (RemoteException e) {
3173 }
3174 return;
3175 }
3176
3177 final long ident = Binder.clearCallingIdentity();
3178 try {
3179 if (TextUtils.equals(pae.intent.getAction(),
3180 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003181 // Start voice interaction through VoiceInteractionManagerService.
3182 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3183 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003184 } else {
3185 pae.intent.replaceExtras(pae.extras);
3186 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3187 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3188 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003189 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003190
3191 try {
3192 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3193 } catch (ActivityNotFoundException e) {
3194 Slog.w(TAG, "No activity to handle assist action.", e);
3195 }
3196 }
3197 } finally {
3198 Binder.restoreCallingIdentity(ident);
3199 }
3200 }
3201
3202 @Override
3203 public int addAppTask(IBinder activityToken, Intent intent,
3204 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3205 final int callingUid = Binder.getCallingUid();
3206 final long callingIdent = Binder.clearCallingIdentity();
3207
3208 try {
3209 synchronized (mGlobalLock) {
3210 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3211 if (r == null) {
3212 throw new IllegalArgumentException("Activity does not exist; token="
3213 + activityToken);
3214 }
3215 ComponentName comp = intent.getComponent();
3216 if (comp == null) {
3217 throw new IllegalArgumentException("Intent " + intent
3218 + " must specify explicit component");
3219 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003220 if (thumbnail.getWidth() != mThumbnailWidth
3221 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003222 throw new IllegalArgumentException("Bad thumbnail size: got "
3223 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003224 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003225 }
3226 if (intent.getSelector() != null) {
3227 intent.setSelector(null);
3228 }
3229 if (intent.getSourceBounds() != null) {
3230 intent.setSourceBounds(null);
3231 }
3232 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3233 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3234 // The caller has added this as an auto-remove task... that makes no
3235 // sense, so turn off auto-remove.
3236 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3237 }
3238 }
3239 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3240 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3241 if (ainfo.applicationInfo.uid != callingUid) {
3242 throw new SecurityException(
3243 "Can't add task for another application: target uid="
3244 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3245 }
3246
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003247 final ActivityStack stack = r.getRootTask();
Andrii Kulian86d676c2020-03-27 19:34:54 -07003248 final Task task = stack.getDisplayArea().createStack(stack.getWindowingMode(),
3249 stack.getActivityType(), !ON_TOP, ainfo, intent,
Louis Changa009c762020-02-26 11:21:31 +08003250 false /* createdByOrganizer */);
Wale Ogunwale0d465192020-01-23 19:14:44 -08003251
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003252 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003253 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003254 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003255 return INVALID_TASK_ID;
3256 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003257 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003258
3259 // TODO: Send the thumbnail to WM to store it.
3260
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003261 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003262 }
3263 } finally {
3264 Binder.restoreCallingIdentity(callingIdent);
3265 }
3266 }
3267
3268 @Override
3269 public Point getAppTaskThumbnailSize() {
3270 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003271 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003272 }
3273 }
3274
3275 @Override
3276 public void setTaskResizeable(int taskId, int resizeableMode) {
3277 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003278 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003279 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3280 if (task == null) {
3281 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3282 return;
3283 }
3284 task.setResizeMode(resizeableMode);
3285 }
3286 }
3287
3288 @Override
3289 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003290 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003291 long ident = Binder.clearCallingIdentity();
3292 try {
3293 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003294 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003295 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003296 if (task == null) {
3297 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3298 return;
3299 }
3300 // Place the task in the right stack if it isn't there already based on
3301 // the requested bounds.
3302 // The stack transition logic is:
3303 // - a null bounds on a freeform task moves that task to fullscreen
3304 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3305 // that task to freeform
3306 // - otherwise the task is not moved
3307 ActivityStack stack = task.getStack();
3308 if (!task.getWindowConfiguration().canResizeTask()) {
3309 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3310 }
3311 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07003312 stack = stack.getDisplayArea().getOrCreateStack(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003313 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3314 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
Andrii Kulian86d676c2020-03-27 19:34:54 -07003315 stack = stack.getDisplayArea().getOrCreateStack(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003316 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3317 }
3318
3319 // Reparent the task to the right stack if necessary
3320 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3321 if (stack != task.getStack()) {
3322 // Defer resume until the task is resized below
3323 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3324 DEFER_RESUME, "resizeTask");
3325 preserveWindow = false;
3326 }
3327
3328 // After reparenting (which only resizes the task to the stack bounds), resize the
3329 // task to the actual bounds provided
3330 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3331 }
3332 } finally {
3333 Binder.restoreCallingIdentity(ident);
3334 }
3335 }
3336
3337 @Override
3338 public boolean releaseActivityInstance(IBinder token) {
3339 synchronized (mGlobalLock) {
3340 final long origId = Binder.clearCallingIdentity();
3341 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003342 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3343 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003344 return false;
3345 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003346 r.destroyImmediately(true /* removeFromApp */, "app-req");
3347 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003348 } finally {
3349 Binder.restoreCallingIdentity(origId);
3350 }
3351 }
3352 }
3353
3354 @Override
3355 public void releaseSomeActivities(IApplicationThread appInt) {
3356 synchronized (mGlobalLock) {
3357 final long origId = Binder.clearCallingIdentity();
3358 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003359 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003360 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003361 } finally {
3362 Binder.restoreCallingIdentity(origId);
3363 }
3364 }
3365 }
3366
3367 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003368 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003369 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 != PackageManager.PERMISSION_GRANTED) {
3371 throw new SecurityException("Requires permission "
3372 + android.Manifest.permission.DEVICE_POWER);
3373 }
3374
3375 synchronized (mGlobalLock) {
3376 long ident = Binder.clearCallingIdentity();
3377 if (mKeyguardShown != keyguardShowing) {
3378 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003379 final Message msg = PooledLambda.obtainMessage(
3380 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3381 keyguardShowing);
3382 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383 }
3384 try {
wilsonshih177261f2019-02-22 12:02:18 +08003385 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003386 } finally {
3387 Binder.restoreCallingIdentity(ident);
3388 }
3389 }
3390
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003391 mH.post(() -> {
3392 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3393 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3394 }
3395 });
3396 }
3397
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003398 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003399 mH.post(() -> {
3400 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3401 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3402 }
3403 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 }
3405
3406 @Override
3407 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003408 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3409 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003410
3411 final File passedIconFile = new File(filePath);
3412 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3413 passedIconFile.getName());
3414 if (!legitIconFile.getPath().equals(filePath)
3415 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3416 throw new IllegalArgumentException("Bad file path: " + filePath
3417 + " passed for userId " + userId);
3418 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003419 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003420 }
3421
3422 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003423 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003424 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003425 synchronized (mGlobalLock) {
3426 final long ident = Binder.clearCallingIdentity();
3427 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003428 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003429 if (stack == null) {
3430 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3431 return;
3432 }
3433 if (!stack.isActivityTypeStandardOrUndefined()) {
3434 throw new IllegalArgumentException(
3435 "Removing non-standard stack is not allowed.");
3436 }
3437 mStackSupervisor.removeStack(stack);
3438 } finally {
3439 Binder.restoreCallingIdentity(ident);
3440 }
3441 }
3442 }
3443
3444 @Override
3445 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003446 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003447
3448 synchronized (mGlobalLock) {
3449 final long ident = Binder.clearCallingIdentity();
3450 try {
3451 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3452 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003453 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003454 } finally {
3455 Binder.restoreCallingIdentity(ident);
3456 }
3457 }
3458 }
3459
3460 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003461 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003462 synchronized (mGlobalLock) {
3463 long ident = Binder.clearCallingIdentity();
3464 try {
3465 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3466 if (r == null) {
3467 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003468 "toggleFreeformWindowingMode: No activity record matching token="
3469 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003470 }
3471
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003472 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003473 if (stack == null) {
3474 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3475 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003476 }
3477
Yunfan Chend967af82019-01-17 18:30:18 +09003478 if (!stack.inFreeformWindowingMode()
3479 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3480 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3481 + "toggle between fullscreen and freeform.");
3482 }
3483
3484 if (stack.inFreeformWindowingMode()) {
3485 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003486 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003487 throw new IllegalStateException("Size-compat windows are currently not"
3488 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003489 } else if (stack.getParent().inFreeformWindowingMode()) {
3490 // If the window is on a freeform display, set it to undefined. It will be
3491 // resolved to freeform and it can adjust windowing mode when the display mode
3492 // changes in runtime.
3493 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003494 } else {
3495 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3496 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003497 } finally {
3498 Binder.restoreCallingIdentity(ident);
3499 }
3500 }
3501 }
3502
3503 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3504 @Override
3505 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003506 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003507 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003508 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003509 }
3510
3511 /** Unregister a task stack listener so that it stops receiving callbacks. */
3512 @Override
3513 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003514 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003515 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003516 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003517 }
3518
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003519 @Override
3520 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3521 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3522 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3523 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3524 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3525 }
3526
3527 @Override
3528 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3529 IBinder activityToken, int flags) {
3530 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3531 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3532 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3533 }
3534
3535 @Override
3536 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3537 Bundle args) {
3538 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3539 true /* focused */, true /* newSessionId */, userHandle, args,
3540 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3541 }
3542
3543 @Override
3544 public Bundle getAssistContextExtras(int requestType) {
3545 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3546 null, null, true /* focused */, true /* newSessionId */,
3547 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3548 if (pae == null) {
3549 return null;
3550 }
3551 synchronized (pae) {
3552 while (!pae.haveResult) {
3553 try {
3554 pae.wait();
3555 } catch (InterruptedException e) {
3556 }
3557 }
3558 }
3559 synchronized (mGlobalLock) {
3560 buildAssistBundleLocked(pae, pae.result);
3561 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003562 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003563 }
3564 return pae.extras;
3565 }
3566
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003567 /**
3568 * Binder IPC calls go through the public entry point.
3569 * This can be called with or without the global lock held.
3570 */
3571 private static int checkCallingPermission(String permission) {
3572 return checkPermission(
3573 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3574 }
3575
3576 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003577 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003578 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3579 mAmInternal.enforceCallingPermission(permission, func);
3580 }
3581 }
3582
3583 @VisibleForTesting
3584 int checkGetTasksPermission(String permission, int pid, int uid) {
3585 return checkPermission(permission, pid, uid);
3586 }
3587
3588 static int checkPermission(String permission, int pid, int uid) {
3589 if (permission == null) {
3590 return PackageManager.PERMISSION_DENIED;
3591 }
3592 return checkComponentPermission(permission, pid, uid, -1, true);
3593 }
3594
Wale Ogunwale214f3482018-10-04 11:00:47 -07003595 public static int checkComponentPermission(String permission, int pid, int uid,
3596 int owningUid, boolean exported) {
3597 return ActivityManagerService.checkComponentPermission(
3598 permission, pid, uid, owningUid, exported);
3599 }
3600
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003601 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3602 if (getRecentTasks().isCallerRecents(callingUid)) {
3603 // Always allow the recents component to get tasks
3604 return true;
3605 }
3606
3607 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3608 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3609 if (!allowed) {
3610 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3611 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3612 // Temporary compatibility: some existing apps on the system image may
3613 // still be requesting the old permission and not switched to the new
3614 // one; if so, we'll still allow them full access. This means we need
3615 // to see if they are holding the old permission and are a system app.
3616 try {
3617 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3618 allowed = true;
3619 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3620 + " is using old GET_TASKS but privileged; allowing");
3621 }
3622 } catch (RemoteException e) {
3623 }
3624 }
3625 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3626 + " does not hold REAL_GET_TASKS; limiting output");
3627 }
3628 return allowed;
3629 }
3630
Nicholas Sauer0259e532019-08-30 08:24:55 -07003631 boolean isCrossUserAllowed(int pid, int uid) {
3632 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3633 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3634 }
3635
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003636 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3637 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3638 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3639 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003640 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003641 "enqueueAssistContext()");
3642
3643 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08003644 final ActivityStack stack = getTopDisplayFocusedStack();
3645 ActivityRecord activity = stack != null ? stack.getTopNonFinishingActivity() : null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003646 if (activity == null) {
3647 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3648 return null;
3649 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003650 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003651 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3652 return null;
3653 }
3654 if (focused) {
3655 if (activityToken != null) {
3656 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3657 if (activity != caller) {
3658 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3659 + " is not current top " + activity);
3660 return null;
3661 }
3662 }
3663 } else {
3664 activity = ActivityRecord.forTokenLocked(activityToken);
3665 if (activity == null) {
3666 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3667 + " couldn't be found");
3668 return null;
3669 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003670 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003671 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3672 return null;
3673 }
3674 }
3675
3676 PendingAssistExtras pae;
3677 Bundle extras = new Bundle();
3678 if (args != null) {
3679 extras.putAll(args);
3680 }
3681 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003682 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003683
3684 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3685 userHandle);
3686 pae.isHome = activity.isActivityTypeHome();
3687
3688 // Increment the sessionId if necessary
3689 if (newSessionId) {
3690 mViSessionId++;
3691 }
3692 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003693 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3694 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003695 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003696 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003697 } catch (RemoteException e) {
3698 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3699 return null;
3700 }
3701 return pae;
3702 }
3703 }
3704
3705 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3706 if (result != null) {
3707 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3708 }
3709 if (pae.hint != null) {
3710 pae.extras.putBoolean(pae.hint, true);
3711 }
3712 }
3713
3714 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3715 IAssistDataReceiver receiver;
3716 synchronized (mGlobalLock) {
3717 mPendingAssistExtras.remove(pae);
3718 receiver = pae.receiver;
3719 }
3720 if (receiver != null) {
3721 // Caller wants result sent back to them.
3722 Bundle sendBundle = new Bundle();
3723 // At least return the receiver extras
3724 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3725 try {
3726 pae.receiver.onHandleAssistData(sendBundle);
3727 } catch (RemoteException e) {
3728 }
3729 }
3730 }
3731
3732 public class PendingAssistExtras extends Binder implements Runnable {
3733 public final ActivityRecord activity;
3734 public boolean isHome;
3735 public final Bundle extras;
3736 public final Intent intent;
3737 public final String hint;
3738 public final IAssistDataReceiver receiver;
3739 public final int userHandle;
3740 public boolean haveResult = false;
3741 public Bundle result = null;
3742 public AssistStructure structure = null;
3743 public AssistContent content = null;
3744 public Bundle receiverExtras;
3745
3746 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3747 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3748 int _userHandle) {
3749 activity = _activity;
3750 extras = _extras;
3751 intent = _intent;
3752 hint = _hint;
3753 receiver = _receiver;
3754 receiverExtras = _receiverExtras;
3755 userHandle = _userHandle;
3756 }
3757
3758 @Override
3759 public void run() {
3760 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3761 synchronized (this) {
3762 haveResult = true;
3763 notifyAll();
3764 }
3765 pendingAssistExtrasTimedOut(this);
3766 }
3767 }
3768
3769 @Override
3770 public boolean isAssistDataAllowedOnCurrentActivity() {
3771 int userId;
3772 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003773 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003774 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3775 return false;
3776 }
3777
Wale Ogunwale21e06482019-11-18 05:14:15 -08003778 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003779 if (activity == null) {
3780 return false;
3781 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003782 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003783 }
3784 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3785 }
3786
3787 @Override
3788 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3789 long ident = Binder.clearCallingIdentity();
3790 try {
3791 synchronized (mGlobalLock) {
3792 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003793 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003794 if (top != caller) {
3795 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3796 + " is not current top " + top);
3797 return false;
3798 }
3799 if (!top.nowVisible) {
3800 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3801 + " is not visible");
3802 return false;
3803 }
3804 }
3805 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3806 token);
3807 } finally {
3808 Binder.restoreCallingIdentity(ident);
3809 }
3810 }
3811
3812 @Override
3813 public boolean isRootVoiceInteraction(IBinder token) {
3814 synchronized (mGlobalLock) {
3815 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3816 if (r == null) {
3817 return false;
3818 }
3819 return r.rootVoiceInteraction;
3820 }
3821 }
3822
Wale Ogunwalef6733932018-06-27 05:14:34 -07003823 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3824 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3825 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3826 if (activityToCallback == null) return;
3827 activityToCallback.setVoiceSessionLocked(voiceSession);
3828
3829 // Inform the activity
3830 try {
3831 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3832 voiceInteractor);
3833 long token = Binder.clearCallingIdentity();
3834 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003835 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003836 } finally {
3837 Binder.restoreCallingIdentity(token);
3838 }
3839 // TODO: VI Should we cache the activity so that it's easier to find later
3840 // rather than scan through all the stacks and activities?
3841 } catch (RemoteException re) {
3842 activityToCallback.clearVoiceSessionLocked();
3843 // TODO: VI Should this terminate the voice session?
3844 }
3845 }
3846
3847 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3848 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3849 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3850 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3851 boolean wasRunningVoice = mRunningVoice != null;
3852 mRunningVoice = session;
3853 if (!wasRunningVoice) {
3854 mVoiceWakeLock.acquire();
3855 updateSleepIfNeededLocked();
3856 }
3857 }
3858 }
3859
3860 void finishRunningVoiceLocked() {
3861 if (mRunningVoice != null) {
3862 mRunningVoice = null;
3863 mVoiceWakeLock.release();
3864 updateSleepIfNeededLocked();
3865 }
3866 }
3867
3868 @Override
3869 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3870 synchronized (mGlobalLock) {
3871 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3872 if (keepAwake) {
3873 mVoiceWakeLock.acquire();
3874 } else {
3875 mVoiceWakeLock.release();
3876 }
3877 }
3878 }
3879 }
3880
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003881 @Override
3882 public ComponentName getActivityClassForToken(IBinder token) {
3883 synchronized (mGlobalLock) {
3884 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3885 if (r == null) {
3886 return null;
3887 }
3888 return r.intent.getComponent();
3889 }
3890 }
3891
3892 @Override
3893 public String getPackageForToken(IBinder token) {
3894 synchronized (mGlobalLock) {
3895 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3896 if (r == null) {
3897 return null;
3898 }
3899 return r.packageName;
3900 }
3901 }
3902
3903 @Override
3904 public void showLockTaskEscapeMessage(IBinder token) {
3905 synchronized (mGlobalLock) {
3906 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3907 if (r == null) {
3908 return;
3909 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003910 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003911 }
3912 }
3913
3914 @Override
3915 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003916 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003917 final long token = Binder.clearCallingIdentity();
3918 try {
3919 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003920 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003921 }
3922 } finally {
3923 Binder.restoreCallingIdentity(token);
3924 }
3925 }
3926
3927 /**
3928 * Try to place task to provided position. The final position might be different depending on
3929 * current user and stacks state. The task will be moved to target stack if it's currently in
3930 * different stack.
3931 */
3932 @Override
3933 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003934 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003935 synchronized (mGlobalLock) {
3936 long ident = Binder.clearCallingIdentity();
3937 try {
3938 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3939 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003940 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003941 if (task == null) {
3942 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3943 + taskId);
3944 }
3945
Louis Chang149d5c82019-12-30 09:47:39 +08003946 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003947
3948 if (stack == null) {
3949 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3950 + stackId);
3951 }
3952 if (!stack.isActivityTypeStandardOrUndefined()) {
3953 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3954 + " the position of task " + taskId + " in/to non-standard stack");
3955 }
3956
3957 // TODO: Have the callers of this API call a separate reparent method if that is
3958 // what they intended to do vs. having this method also do reparenting.
3959 if (task.getStack() == stack) {
3960 // Change position in current stack.
3961 stack.positionChildAt(task, position);
3962 } else {
3963 // Reparent to new stack.
3964 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3965 !DEFER_RESUME, "positionTaskInStack");
3966 }
3967 } finally {
3968 Binder.restoreCallingIdentity(ident);
3969 }
3970 }
3971 }
3972
3973 @Override
3974 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3975 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3976 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003977 + Arrays.toString(horizontalSizeConfiguration) + " "
3978 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003979 synchronized (mGlobalLock) {
3980 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3981 if (record == null) {
3982 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3983 + "found for: " + token);
3984 }
3985 record.setSizeConfigurations(horizontalSizeConfiguration,
3986 verticalSizeConfigurations, smallestSizeConfigurations);
3987 }
3988 }
3989
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003990 @Override
3991 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003992 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003993 synchronized (mGlobalLock) {
3994 mSuppressResizeConfigChanges = suppress;
3995 }
3996 }
3997
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003998 @Override
3999 // TODO: API should just be about changing windowing modes...
4000 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004001 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004002 "moveTasksToFullscreenStack()");
4003 synchronized (mGlobalLock) {
4004 final long origId = Binder.clearCallingIdentity();
4005 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004006 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004007 if (stack != null){
4008 if (!stack.isActivityTypeStandardOrUndefined()) {
4009 throw new IllegalArgumentException(
4010 "You can't move tasks from non-standard stacks.");
4011 }
4012 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4013 }
4014 } finally {
4015 Binder.restoreCallingIdentity(origId);
4016 }
4017 }
4018 }
4019
4020 /**
4021 * Moves the top activity in the input stackId to the pinned stack.
4022 *
4023 * @param stackId Id of stack to move the top activity to pinned stack.
4024 * @param bounds Bounds to use for pinned stack.
4025 *
4026 * @return True if the top activity of the input stack was successfully moved to the pinned
4027 * stack.
4028 */
4029 @Override
4030 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004031 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004032 "moveTopActivityToPinnedStack()");
4033 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004034 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004035 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4036 + "Device doesn't support picture-in-picture mode");
4037 }
4038
4039 long ident = Binder.clearCallingIdentity();
4040 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004041 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004042 } finally {
4043 Binder.restoreCallingIdentity(ident);
4044 }
4045 }
4046 }
4047
4048 @Override
4049 public boolean isInMultiWindowMode(IBinder token) {
4050 final long origId = Binder.clearCallingIdentity();
4051 try {
4052 synchronized (mGlobalLock) {
4053 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4054 if (r == null) {
4055 return false;
4056 }
4057 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4058 return r.inMultiWindowMode();
4059 }
4060 } finally {
4061 Binder.restoreCallingIdentity(origId);
4062 }
4063 }
4064
4065 @Override
4066 public boolean isInPictureInPictureMode(IBinder token) {
4067 final long origId = Binder.clearCallingIdentity();
4068 try {
4069 synchronized (mGlobalLock) {
4070 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4071 }
4072 } finally {
4073 Binder.restoreCallingIdentity(origId);
4074 }
4075 }
4076
4077 private boolean isInPictureInPictureMode(ActivityRecord r) {
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004078 return r != null
4079 && r.getRootTask() != null
4080 && r.inPinnedWindowingMode()
4081 && r.getRootTask().isInStackLocked(r) != null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004082 }
4083
4084 @Override
4085 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4086 final long origId = Binder.clearCallingIdentity();
4087 try {
4088 synchronized (mGlobalLock) {
4089 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4090 "enterPictureInPictureMode", token, params);
4091
4092 // If the activity is already in picture in picture mode, then just return early
4093 if (isInPictureInPictureMode(r)) {
4094 return true;
4095 }
4096
4097 // Activity supports picture-in-picture, now check that we can enter PiP at this
4098 // point, if it is
4099 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4100 false /* beforeStopping */)) {
4101 return false;
4102 }
4103
4104 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004105 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004106 if (r.getParent() == null) {
4107 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4108 return;
4109 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004110 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004111 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004112 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4113 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4114 // Adjust the source bounds by the insets for the transition down
4115 final Rect sourceBounds = new Rect(
4116 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004117 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004118 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004119 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004120 stack.setPictureInPictureAspectRatio(aspectRatio);
4121 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004122 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4123 r.info.applicationInfo.uid, r.shortComponentName,
4124 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004125 logPictureInPictureArgs(params);
4126 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004127 };
4128
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004129 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004130 // If the keyguard is showing or occluded, then try and dismiss it before
4131 // entering picture-in-picture (this will prompt the user to authenticate if the
4132 // device is currently locked).
4133 dismissKeyguard(token, new KeyguardDismissCallback() {
4134 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004135 public void onDismissSucceeded() {
4136 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004137 }
4138 }, null /* message */);
4139 } else {
4140 // Enter picture in picture immediately otherwise
4141 enterPipRunnable.run();
4142 }
4143 return true;
4144 }
4145 } finally {
4146 Binder.restoreCallingIdentity(origId);
4147 }
4148 }
4149
4150 @Override
4151 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4152 final long origId = Binder.clearCallingIdentity();
4153 try {
4154 synchronized (mGlobalLock) {
4155 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4156 "setPictureInPictureParams", token, params);
4157
4158 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004159 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004160 if (r.inPinnedWindowingMode()) {
4161 // If the activity is already in picture-in-picture, update the pinned stack now
4162 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4163 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004164 final ActivityStack stack = r.getRootTask();
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004165 stack.setPictureInPictureAspectRatio(
4166 r.pictureInPictureArgs.getAspectRatio());
4167 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004168 }
4169 logPictureInPictureArgs(params);
4170 }
4171 } finally {
4172 Binder.restoreCallingIdentity(origId);
4173 }
4174 }
4175
4176 @Override
4177 public int getMaxNumPictureInPictureActions(IBinder token) {
4178 // Currently, this is a static constant, but later, we may change this to be dependent on
4179 // the context of the activity
4180 return 3;
4181 }
4182
4183 private void logPictureInPictureArgs(PictureInPictureParams params) {
4184 if (params.hasSetActions()) {
4185 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4186 params.getActions().size());
4187 }
4188 if (params.hasSetAspectRatio()) {
4189 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4190 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4191 MetricsLogger.action(lm);
4192 }
4193 }
4194
4195 /**
4196 * Checks the state of the system and the activity associated with the given {@param token} to
4197 * verify that picture-in-picture is supported for that activity.
4198 *
4199 * @return the activity record for the given {@param token} if all the checks pass.
4200 */
4201 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4202 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004203 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004204 throw new IllegalStateException(caller
4205 + ": Device doesn't support picture-in-picture mode.");
4206 }
4207
4208 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4209 if (r == null) {
4210 throw new IllegalStateException(caller
4211 + ": Can't find activity for token=" + token);
4212 }
4213
4214 if (!r.supportsPictureInPicture()) {
4215 throw new IllegalStateException(caller
4216 + ": Current activity does not support picture-in-picture.");
4217 }
4218
4219 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004220 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004221 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004222 final float minAspectRatio = mContext.getResources().getFloat(
4223 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4224 final float maxAspectRatio = mContext.getResources().getFloat(
4225 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4226 throw new IllegalArgumentException(String.format(caller
4227 + ": Aspect ratio is too extreme (must be between %f and %f).",
4228 minAspectRatio, maxAspectRatio));
4229 }
4230
4231 // Truncate the number of actions if necessary
4232 params.truncateActions(getMaxNumPictureInPictureActions(token));
4233
4234 return r;
4235 }
4236
4237 @Override
4238 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004239 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004240 synchronized (mGlobalLock) {
4241 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4242 if (r == null) {
4243 throw new IllegalArgumentException("Activity does not exist; token="
4244 + activityToken);
4245 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004246 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004247 }
4248 }
4249
Evan Rosky73a7fe92019-11-18 18:28:01 -08004250 // TODO(b/149338177): remove when CTS no-longer requires it
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004251 @Override
4252 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4253 Rect tempDockedTaskInsetBounds,
4254 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004255 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004256 long ident = Binder.clearCallingIdentity();
4257 try {
4258 synchronized (mGlobalLock) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08004259 final DisplayContent dc = mRootWindowContainer.getDefaultDisplay();
Louis Changa009c762020-02-26 11:21:31 +08004260 final Task primary = dc.getRootSplitScreenPrimaryTask();
4261 final Task secondary = dc.getTask(t -> t.mCreatedByOrganizer && t.isRootTask()
4262 && t.inSplitScreenSecondaryWindowingMode());
Evan Rosky73a7fe92019-11-18 18:28:01 -08004263 if (primary == null || secondary == null) {
4264 return;
4265 }
4266 final WindowContainerTransaction wct = new WindowContainerTransaction();
4267 final Rect primaryRect =
4268 tempDockedTaskInsetBounds != null ? tempDockedTaskInsetBounds
4269 : (tempDockedTaskBounds != null ? tempDockedTaskBounds
4270 : dockedBounds);
4271 wct.setBounds(primary.mRemoteToken, primaryRect);
4272 Rect otherRect = tempOtherTaskInsetBounds != null ? tempOtherTaskInsetBounds
4273 : tempOtherTaskBounds;
4274 if (otherRect == null) {
4275 // Temporary estimation... again this is just for tests.
4276 otherRect = new Rect(secondary.getBounds());
4277 if (dc.getBounds().width() > dc.getBounds().height()) {
4278 otherRect.left = primaryRect.right + 6;
4279 } else {
4280 otherRect.top = primaryRect.bottom + 6;
4281 }
4282 }
4283 wct.setBounds(secondary.mRemoteToken, otherRect);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004284 mWindowOrganizerController.applyTransaction(wct);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004285 }
4286 } finally {
4287 Binder.restoreCallingIdentity(ident);
4288 }
4289 }
4290
4291 @Override
4292 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004293 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004294 final long ident = Binder.clearCallingIdentity();
4295 try {
4296 synchronized (mGlobalLock) {
4297 mStackSupervisor.setSplitScreenResizing(resizing);
4298 }
4299 } finally {
4300 Binder.restoreCallingIdentity(ident);
4301 }
4302 }
4303
Evan Rosky0037e5f2019-11-05 10:26:24 -08004304 @Override
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004305 public IWindowOrganizerController getWindowOrganizerController() {
Evan Rosky0037e5f2019-11-05 10:26:24 -08004306 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004307 "getWindowOrganizerController()");
4308 return mWindowOrganizerController;
Evan Rosky0037e5f2019-11-05 10:26:24 -08004309 }
4310
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004311 /**
4312 * Check that we have the features required for VR-related API calls, and throw an exception if
4313 * not.
4314 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004315 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004316 if (!mContext.getPackageManager().hasSystemFeature(
4317 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4318 throw new UnsupportedOperationException("VR mode not supported on this device!");
4319 }
4320 }
4321
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004322 @Override
4323 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004324 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004325
4326 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4327
4328 ActivityRecord r;
4329 synchronized (mGlobalLock) {
4330 r = ActivityRecord.isInStackLocked(token);
4331 }
4332
4333 if (r == null) {
4334 throw new IllegalArgumentException();
4335 }
4336
4337 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004338 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004339 VrManagerInternal.NO_ERROR) {
4340 return err;
4341 }
4342
4343 // Clear the binder calling uid since this path may call moveToTask().
4344 final long callingId = Binder.clearCallingIdentity();
4345 try {
4346 synchronized (mGlobalLock) {
4347 r.requestedVrComponent = (enabled) ? packageName : null;
4348
4349 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004350 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004351 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004352 }
4353 return 0;
4354 }
4355 } finally {
4356 Binder.restoreCallingIdentity(callingId);
4357 }
4358 }
4359
4360 @Override
4361 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4362 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4363 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004364 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004365 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4366 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4367 }
Louis Changcdec0802019-11-11 11:45:07 +08004368 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004369 || activity.voiceSession != null) {
4370 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4371 return;
4372 }
4373 if (activity.pendingVoiceInteractionStart) {
4374 Slog.w(TAG, "Pending start of voice interaction already.");
4375 return;
4376 }
4377 activity.pendingVoiceInteractionStart = true;
4378 }
4379 LocalServices.getService(VoiceInteractionManagerInternal.class)
4380 .startLocalVoiceInteraction(callingActivity, options);
4381 }
4382
4383 @Override
4384 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4385 LocalServices.getService(VoiceInteractionManagerInternal.class)
4386 .stopLocalVoiceInteraction(callingActivity);
4387 }
4388
4389 @Override
4390 public boolean supportsLocalVoiceInteraction() {
4391 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4392 .supportsLocalVoiceInteraction();
4393 }
4394
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004395 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004396 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004397 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004398
4399 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004400 if (mWindowManager == null) {
4401 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4402 return false;
4403 }
4404
4405 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004406 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004407 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004408 }
4409
Riddle Hsua0022cd2019-09-09 21:12:41 +08004410 mH.sendMessage(PooledLambda.obtainMessage(
4411 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4412 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004413
4414 final long origId = Binder.clearCallingIdentity();
4415 try {
4416 if (values != null) {
4417 Settings.System.clearConfiguration(values);
4418 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004419 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004420 UserHandle.USER_NULL, false /* deferResume */,
4421 mTmpUpdateConfigurationResult);
4422 return mTmpUpdateConfigurationResult.changes != 0;
4423 } finally {
4424 Binder.restoreCallingIdentity(origId);
4425 }
4426 }
4427 }
4428
4429 @Override
4430 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4431 CharSequence message) {
4432 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004433 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004434 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4435 }
4436 final long callingId = Binder.clearCallingIdentity();
4437 try {
4438 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004439 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004440 }
4441 } finally {
4442 Binder.restoreCallingIdentity(callingId);
4443 }
4444 }
4445
4446 @Override
4447 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004448 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004449 "cancelTaskWindowTransition()");
4450 final long ident = Binder.clearCallingIdentity();
4451 try {
4452 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004453 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 MATCH_TASK_IN_STACKS_ONLY);
4455 if (task == null) {
4456 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4457 return;
4458 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004459 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004460 }
4461 } finally {
4462 Binder.restoreCallingIdentity(ident);
4463 }
4464 }
4465
4466 @Override
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004467 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004468 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004469 final long ident = Binder.clearCallingIdentity();
4470 try {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004471 return getTaskSnapshot(taskId, isLowResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004472 } finally {
4473 Binder.restoreCallingIdentity(ident);
4474 }
4475 }
4476
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004477 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004478 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004479 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004480 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004481 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004482 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4483 if (task == null) {
4484 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4485 return null;
4486 }
4487 }
4488 // Don't call this while holding the lock as this operation might hit the disk.
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004489 return task.getSnapshot(isLowResolution, restoreFromDisk);
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004490 }
4491
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004492 @Override
4493 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4494 synchronized (mGlobalLock) {
4495 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4496 if (r == null) {
4497 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4498 + token);
4499 return;
4500 }
4501 final long origId = Binder.clearCallingIdentity();
4502 try {
4503 r.setDisablePreviewScreenshots(disable);
4504 } finally {
4505 Binder.restoreCallingIdentity(origId);
4506 }
4507 }
4508 }
4509
Riddle Hsu440f88b2019-11-06 22:17:35 +08004510 @Override
4511 public void invalidateHomeTaskSnapshot(IBinder token) {
4512 synchronized (mGlobalLock) {
4513 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4514 if (r == null || !r.isActivityTypeHome()) {
4515 return;
4516 }
4517 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4518 }
4519 }
4520
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004521 /** Return the user id of the last resumed activity. */
4522 @Override
4523 public @UserIdInt
4524 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004525 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004526 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4527 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004528 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004529 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004530 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004531 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004532 }
4533 }
4534
4535 @Override
4536 public void updateLockTaskFeatures(int userId, int flags) {
4537 final int callingUid = Binder.getCallingUid();
4538 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004539 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004540 "updateLockTaskFeatures()");
4541 }
4542 synchronized (mGlobalLock) {
4543 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4544 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004545 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004546 }
4547 }
4548
4549 @Override
4550 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4551 synchronized (mGlobalLock) {
4552 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4553 if (r == null) {
4554 return;
4555 }
4556 final long origId = Binder.clearCallingIdentity();
4557 try {
4558 r.setShowWhenLocked(showWhenLocked);
4559 } finally {
4560 Binder.restoreCallingIdentity(origId);
4561 }
4562 }
4563 }
4564
4565 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004566 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4567 synchronized (mGlobalLock) {
4568 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4569 if (r == null) {
4570 return;
4571 }
4572 final long origId = Binder.clearCallingIdentity();
4573 try {
4574 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4575 } finally {
4576 Binder.restoreCallingIdentity(origId);
4577 }
4578 }
4579 }
4580
4581 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004582 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4583 synchronized (mGlobalLock) {
4584 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4585 if (r == null) {
4586 return;
4587 }
4588 final long origId = Binder.clearCallingIdentity();
4589 try {
4590 r.setTurnScreenOn(turnScreenOn);
4591 } finally {
4592 Binder.restoreCallingIdentity(origId);
4593 }
4594 }
4595 }
4596
4597 @Override
4598 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004599 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004600 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004601 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004602 synchronized (mGlobalLock) {
4603 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4604 if (r == null) {
4605 return;
4606 }
4607 final long origId = Binder.clearCallingIdentity();
4608 try {
4609 r.registerRemoteAnimations(definition);
4610 } finally {
4611 Binder.restoreCallingIdentity(origId);
4612 }
4613 }
4614 }
4615
4616 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004617 public void unregisterRemoteAnimations(IBinder token) {
4618 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4619 "unregisterRemoteAnimations");
4620 synchronized (mGlobalLock) {
4621 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4622 if (r == null) {
4623 return;
4624 }
4625 final long origId = Binder.clearCallingIdentity();
4626 try {
4627 r.unregisterRemoteAnimations();
4628 } finally {
4629 Binder.restoreCallingIdentity(origId);
4630 }
4631 }
4632 }
4633
4634 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004635 public void registerRemoteAnimationForNextActivityStart(String packageName,
4636 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004637 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004638 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004639 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004640 synchronized (mGlobalLock) {
4641 final long origId = Binder.clearCallingIdentity();
4642 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004643 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004644 packageName, adapter);
4645 } finally {
4646 Binder.restoreCallingIdentity(origId);
4647 }
4648 }
4649 }
4650
Evan Rosky966759f2019-01-15 10:33:58 -08004651 @Override
4652 public void registerRemoteAnimationsForDisplay(int displayId,
4653 RemoteAnimationDefinition definition) {
4654 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4655 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004656 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004657 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004658 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004659 if (display == null) {
4660 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4661 return;
4662 }
4663 final long origId = Binder.clearCallingIdentity();
4664 try {
4665 display.mDisplayContent.registerRemoteAnimations(definition);
4666 } finally {
4667 Binder.restoreCallingIdentity(origId);
4668 }
4669 }
4670 }
4671
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004672 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4673 @Override
4674 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4675 synchronized (mGlobalLock) {
4676 final long origId = Binder.clearCallingIdentity();
4677 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004678 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004679 } finally {
4680 Binder.restoreCallingIdentity(origId);
4681 }
4682 }
4683 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004684
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004685 @Override
4686 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004687 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004688 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004689 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004690 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004691 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004692 }
4693 }
4694
4695 @Override
4696 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004697 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004698 != PERMISSION_GRANTED) {
4699 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4700 + Binder.getCallingPid()
4701 + ", uid=" + Binder.getCallingUid()
4702 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4703 Slog.w(TAG, msg);
4704 throw new SecurityException(msg);
4705 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004706 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004707 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004708 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004709 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004710 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004711 }
4712 }
4713
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004714 @Override
4715 public void stopAppSwitches() {
4716 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4717 synchronized (mGlobalLock) {
4718 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004719 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004720 mDidAppSwitch = false;
4721 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4722 }
4723 }
4724
4725 @Override
4726 public void resumeAppSwitches() {
4727 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4728 synchronized (mGlobalLock) {
4729 // Note that we don't execute any pending app switches... we will
4730 // let those wait until either the timeout, or the next start
4731 // activity request.
4732 mAppSwitchesAllowedTime = 0;
4733 }
4734 }
4735
Ricky Wai906af482019-06-03 17:25:28 +01004736 long getLastStopAppSwitchesTime() {
4737 return mLastStopAppSwitchesTime;
4738 }
4739
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004740 void onStartActivitySetDidAppSwitch() {
4741 if (mDidAppSwitch) {
4742 // This is the second allowed switch since we stopped switches, so now just generally
4743 // allow switches. Use case:
4744 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4745 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4746 // anyone to switch again).
4747 mAppSwitchesAllowedTime = 0;
4748 } else {
4749 mDidAppSwitch = true;
4750 }
4751 }
4752
4753 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004754 boolean shouldDisableNonVrUiLocked() {
4755 return mVrController.shouldDisableNonVrUiLocked();
4756 }
4757
Wale Ogunwale53783742018-09-16 10:21:51 -07004758 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004759 // 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 +00004760 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004761 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004762 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4763 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004764 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004765 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004766 }
4767 mH.post(() -> {
4768 if (!mVrController.onVrModeChanged(r)) {
4769 return;
4770 }
4771 synchronized (mGlobalLock) {
4772 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4773 mWindowManager.disableNonVrUi(disableNonVrUi);
4774 if (disableNonVrUi) {
4775 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4776 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004777 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004778 }
4779 }
4780 });
4781 }
4782
Wale Ogunwale53783742018-09-16 10:21:51 -07004783 @Override
4784 public int getPackageScreenCompatMode(String packageName) {
4785 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4786 synchronized (mGlobalLock) {
4787 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4788 }
4789 }
4790
4791 @Override
4792 public void setPackageScreenCompatMode(String packageName, int mode) {
4793 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4794 "setPackageScreenCompatMode");
4795 synchronized (mGlobalLock) {
4796 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4797 }
4798 }
4799
4800 @Override
4801 public boolean getPackageAskScreenCompat(String packageName) {
4802 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4803 synchronized (mGlobalLock) {
4804 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4805 }
4806 }
4807
4808 @Override
4809 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4810 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4811 "setPackageAskScreenCompat");
4812 synchronized (mGlobalLock) {
4813 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4814 }
4815 }
4816
Wale Ogunwale64258362018-10-16 15:13:37 -07004817 public static String relaunchReasonToString(int relaunchReason) {
4818 switch (relaunchReason) {
4819 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4820 return "window_resize";
4821 case RELAUNCH_REASON_FREE_RESIZE:
4822 return "free_resize";
4823 default:
4824 return null;
4825 }
4826 }
4827
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004828 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004829 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004830 }
4831
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004832 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004833 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004834 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4835 }
4836
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004837 boolean isKeyguardLocked() {
4838 return mKeyguardController.isKeyguardLocked();
4839 }
4840
Garfield Tan01548632018-11-27 10:15:48 -08004841 /**
4842 * Clears launch params for the given package.
4843 * @param packageNames the names of the packages of which the launch params are to be cleared
4844 */
4845 @Override
4846 public void clearLaunchParamsForPackages(List<String> packageNames) {
4847 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4848 "clearLaunchParamsForPackages");
4849 synchronized (mGlobalLock) {
4850 for (int i = 0; i < packageNames.size(); ++i) {
4851 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4852 }
4853 }
4854 }
4855
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004856 /**
4857 * Makes the display with the given id a single task instance display. I.e the display can only
4858 * contain one task.
4859 */
4860 @Override
4861 public void setDisplayToSingleTaskInstance(int displayId) {
4862 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4863 "setDisplayToSingleTaskInstance");
4864 final long origId = Binder.clearCallingIdentity();
4865 try {
Louis Chang677921f2019-12-06 16:44:24 +08004866 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004867 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004868 if (display != null) {
4869 display.setDisplayToSingleTaskInstance();
4870 }
4871 } finally {
4872 Binder.restoreCallingIdentity(origId);
4873 }
4874 }
4875
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004876 /**
4877 * Requests that an activity should enter picture-in-picture mode if possible.
4878 */
4879 @Override
4880 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4881 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4882 "requestPictureInPictureMode");
4883 final long origId = Binder.clearCallingIdentity();
4884 try {
4885 synchronized (mGlobalLock) {
4886 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4887 if (activity == null) {
4888 return;
4889 }
4890
4891 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4892 "requestPictureInPictureMode", /* beforeStopping */ false);
4893 if (!canEnterPictureInPicture) {
4894 throw new IllegalStateException(
4895 "Requested PIP on an activity that doesn't support it");
4896 }
4897
4898 try {
4899 final ClientTransaction transaction = ClientTransaction.obtain(
4900 activity.app.getThread(),
4901 activity.token);
4902 transaction.addCallback(EnterPipRequestedItem.obtain());
4903 getLifecycleManager().scheduleTransaction(transaction);
4904 } catch (Exception e) {
4905 Slog.w(TAG, "Failed to send enter pip requested item: "
4906 + activity.intent.getComponent(), e);
4907 }
4908 }
4909 } finally {
4910 Binder.restoreCallingIdentity(origId);
4911 }
4912 }
4913
Wale Ogunwale31913b52018-10-13 08:29:31 -07004914 void dumpLastANRLocked(PrintWriter pw) {
4915 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4916 if (mLastANRState == null) {
4917 pw.println(" <no ANR has occurred since boot>");
4918 } else {
4919 pw.println(mLastANRState);
4920 }
4921 }
4922
4923 void dumpLastANRTracesLocked(PrintWriter pw) {
4924 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4925
4926 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4927 if (ArrayUtils.isEmpty(files)) {
4928 pw.println(" <no ANR has occurred since boot>");
4929 return;
4930 }
4931 // Find the latest file.
4932 File latest = null;
4933 for (File f : files) {
4934 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4935 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004936 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004937 }
4938 pw.print("File: ");
4939 pw.print(latest.getName());
4940 pw.println();
4941 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4942 String line;
4943 while ((line = in.readLine()) != null) {
4944 pw.println(line);
4945 }
4946 } catch (IOException e) {
4947 pw.print("Unable to read: ");
4948 pw.print(e);
4949 pw.println();
4950 }
4951 }
4952
4953 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4954 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4955 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4956 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4957 }
4958
4959 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4960 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4961 pw.println(header);
4962
Louis Chang149d5c82019-12-30 09:47:39 +08004963 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004964 dumpPackage);
4965 boolean needSep = printedAnything;
4966
4967 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08004968 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004969 " ResumedActivity: ");
4970 if (printed) {
4971 printedAnything = true;
4972 needSep = false;
4973 }
4974
4975 if (dumpPackage == null) {
4976 if (needSep) {
4977 pw.println();
4978 }
4979 printedAnything = true;
4980 mStackSupervisor.dump(pw, " ");
Winson Chung268eccb2020-03-26 13:43:44 -07004981 mTaskOrganizerController.dump(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004982 }
4983
4984 if (!printedAnything) {
4985 pw.println(" (nothing)");
4986 }
4987 }
4988
4989 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004990 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08004991 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004992 pw.println(" ");
4993 }
4994
4995 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4996 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4997 getActivityStartController().dump(pw, "", dumpPackage);
4998 }
4999
5000 /**
5001 * There are three things that cmd can be:
5002 * - a flattened component name that matches an existing activity
5003 * - the cmd arg isn't the flattened component name of an existing activity:
5004 * dump all activity whose component contains the cmd as a substring
5005 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005006 * <p>
5007 * The caller should not hold lock when calling this method because it will wait for the
5008 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005009 *
5010 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5011 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5012 */
5013 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5014 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5015 ArrayList<ActivityRecord> activities;
5016
5017 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005018 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005019 dumpFocusedStackOnly);
5020 }
5021
5022 if (activities.size() <= 0) {
5023 return false;
5024 }
5025
5026 String[] newArgs = new String[args.length - opti];
5027 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5028
Louis Changcdec0802019-11-11 11:45:07 +08005029 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005030 boolean needSep = false;
5031 for (int i = activities.size() - 1; i >= 0; i--) {
5032 ActivityRecord r = activities.get(i);
5033 if (needSep) {
5034 pw.println();
5035 }
5036 needSep = true;
5037 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005038 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005039 if (lastTask != task) {
5040 lastTask = task;
5041 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005042 pw.print(" id="); pw.print(lastTask.mTaskId);
5043 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005044 if (dumpAll) {
5045 lastTask.dump(pw, " ");
5046 }
5047 }
5048 }
5049 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5050 }
5051 return true;
5052 }
5053
5054 /**
5055 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5056 * there is a thread associated with the activity.
5057 */
5058 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5059 final ActivityRecord r, String[] args, boolean dumpAll) {
5060 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005061 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005062 synchronized (mGlobalLock) {
5063 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5064 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5065 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005066 if (r.hasProcess()) {
5067 pw.println(r.app.getPid());
5068 appThread = r.app.getThread();
5069 } else {
5070 pw.println("(not running)");
5071 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005072 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005073 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005074 }
5075 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005076 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005077 // flush anything that is already in the PrintWriter since the thread is going
5078 // to write to the file descriptor directly
5079 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005080 try (TransferPipe tp = new TransferPipe()) {
5081 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5082 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005083 } catch (IOException e) {
5084 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5085 } catch (RemoteException e) {
5086 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5087 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005088 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005089 }
5090
sanryhuang498e77e2018-12-06 14:57:01 +08005091 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5092 boolean testPssMode) {
5093 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5094 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5095 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005096 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005097 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5098 st.toString());
5099 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005100 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5101 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5102 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005103 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5104 testPssMode);
5105 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005106 }
5107
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005108 int getCurrentUserId() {
5109 return mAmInternal.getCurrentUserId();
5110 }
5111
5112 private void enforceNotIsolatedCaller(String caller) {
5113 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5114 throw new SecurityException("Isolated process not allowed to call " + caller);
5115 }
5116 }
5117
Wale Ogunwalef6733932018-06-27 05:14:34 -07005118 public Configuration getConfiguration() {
5119 Configuration ci;
5120 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005121 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005122 ci.userSetLocale = false;
5123 }
5124 return ci;
5125 }
5126
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005127 /**
5128 * Current global configuration information. Contains general settings for the entire system,
5129 * also corresponds to the merged configuration of the default display.
5130 */
5131 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005132 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005133 // while initializing process record for system, see {@link
5134 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005135 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005136 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005137 }
5138
5139 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5140 boolean initLocale) {
5141 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5142 }
5143
5144 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5145 boolean initLocale, boolean deferResume) {
5146 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5147 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5148 UserHandle.USER_NULL, deferResume);
5149 }
5150
Wale Ogunwale59507092018-10-29 09:00:30 -07005151 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005152 final long origId = Binder.clearCallingIdentity();
5153 try {
5154 synchronized (mGlobalLock) {
5155 updateConfigurationLocked(values, null, false, true, userId,
5156 false /* deferResume */);
5157 }
5158 } finally {
5159 Binder.restoreCallingIdentity(origId);
5160 }
5161 }
5162
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005163 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5164 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5165 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5166 deferResume, null /* result */);
5167 }
5168
5169 /**
5170 * Do either or both things: (1) change the current configuration, and (2)
5171 * make sure the given activity is running with the (now) current
5172 * configuration. Returns true if the activity has been left running, or
5173 * false if <var>starting</var> is being destroyed to match the new
5174 * configuration.
5175 *
5176 * @param userId is only used when persistent parameter is set to true to persist configuration
5177 * for that particular user
5178 */
5179 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5180 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5181 ActivityTaskManagerService.UpdateConfigurationResult result) {
5182 int changes = 0;
5183 boolean kept = true;
5184
Riddle Hsua0022cd2019-09-09 21:12:41 +08005185 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005186 try {
5187 if (values != null) {
5188 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5189 deferResume);
5190 }
5191
5192 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5193 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005194 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005195 }
5196
5197 if (result != null) {
5198 result.changes = changes;
5199 result.activityRelaunched = !kept;
5200 }
5201 return kept;
5202 }
5203
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005204 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005205 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005206 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005207
Louis Chang677921f2019-12-06 16:44:24 +08005208 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005209 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005210
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005211 mTempConfig.setTo(getGlobalConfiguration());
5212 final int changes = mTempConfig.updateFrom(values);
5213 if (changes == 0) {
5214 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5215 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5216 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5217 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005218 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005219 return 0;
5220 }
5221
5222 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5223 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005224 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005225 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005226 values.colorMode,
5227 values.densityDpi,
5228 values.fontScale,
5229 values.hardKeyboardHidden,
5230 values.keyboard,
5231 values.keyboardHidden,
5232 values.mcc,
5233 values.mnc,
5234 values.navigation,
5235 values.navigationHidden,
5236 values.orientation,
5237 values.screenHeightDp,
5238 values.screenLayout,
5239 values.screenWidthDp,
5240 values.smallestScreenWidthDp,
5241 values.touchscreen,
5242 values.uiMode);
5243
5244
5245 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5246 final LocaleList locales = values.getLocales();
5247 int bestLocaleIndex = 0;
5248 if (locales.size() > 1) {
5249 if (mSupportedSystemLocales == null) {
5250 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5251 }
5252 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5253 }
5254 SystemProperties.set("persist.sys.locale",
5255 locales.get(bestLocaleIndex).toLanguageTag());
5256 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005257
5258 final Message m = PooledLambda.obtainMessage(
5259 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5260 locales.get(bestLocaleIndex));
5261 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005262 }
5263
Yunfan Chen75157d72018-07-27 14:47:21 +09005264 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005265
5266 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005267 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005268
5269 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5270 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005271 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005272
5273 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005274 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005275
5276 AttributeCache ac = AttributeCache.instance();
5277 if (ac != null) {
5278 ac.updateConfiguration(mTempConfig);
5279 }
5280
5281 // Make sure all resources in our process are updated right now, so that anyone who is going
5282 // to retrieve resource values after we return will be sure to get the new ones. This is
5283 // especially important during boot, where the first config change needs to guarantee all
5284 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005285 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005286
5287 // We need another copy of global config because we're scheduling some calls instead of
5288 // running them in place. We need to be sure that object we send will be handled unchanged.
5289 final Configuration configCopy = new Configuration(mTempConfig);
5290 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005291 final Message msg = PooledLambda.obtainMessage(
5292 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5293 this, userId, configCopy);
5294 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005295 }
5296
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005297 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5298 for (int i = pidMap.size() - 1; i >= 0; i--) {
5299 final int pid = pidMap.keyAt(i);
5300 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005301 if (DEBUG_CONFIGURATION) {
5302 Slog.v(TAG_CONFIGURATION, "Update process config of "
5303 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005304 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005305 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005306 }
5307
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005308 final Message msg = PooledLambda.obtainMessage(
5309 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5310 mAmInternal, changes, initLocale);
5311 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005312
5313 // Override configuration of the default display duplicates global config, so we need to
5314 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005315 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005316 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005317
5318 return changes;
5319 }
5320
Riddle Hsua0022cd2019-09-09 21:12:41 +08005321 /** @see WindowSurfacePlacer#deferLayout */
5322 void deferWindowLayout() {
5323 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5324 // Reset the reasons at the first entrance because we only care about the changes in the
5325 // deferred scope.
5326 mLayoutReasons = 0;
5327 }
5328
5329 mWindowManager.mWindowPlacerLocked.deferLayout();
5330 }
5331
5332 /** @see WindowSurfacePlacer#continueLayout */
5333 void continueWindowLayout() {
5334 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5335 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5336 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5337 }
5338 }
5339
5340 /**
5341 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5342 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5343 * defer count is gone.
5344 */
5345 void addWindowLayoutReasons(@LayoutReason int reasons) {
5346 mLayoutReasons |= reasons;
5347 }
5348
Wale Ogunwalef6733932018-06-27 05:14:34 -07005349 private void updateEventDispatchingLocked(boolean booted) {
5350 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5351 }
5352
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005353 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5354 final ContentResolver resolver = mContext.getContentResolver();
5355 Settings.System.putConfigurationForUser(resolver, config, userId);
5356 }
5357
5358 private void sendLocaleToMountDaemonMsg(Locale l) {
5359 try {
5360 IBinder service = ServiceManager.getService("mount");
5361 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5362 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5363 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5364 } catch (RemoteException e) {
5365 Log.e(TAG, "Error storing locale for decryption UI", e);
5366 }
5367 }
5368
Alison Cichowlas3e340502018-08-07 17:15:01 -04005369 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5370 mStartActivitySources.remove(permissionToken);
5371 mExpiredStartAsCallerTokens.add(permissionToken);
5372 }
5373
5374 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5375 mExpiredStartAsCallerTokens.remove(permissionToken);
5376 }
5377
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005378 boolean isActivityStartsLoggingEnabled() {
5379 return mAmInternal.isActivityStartsLoggingEnabled();
5380 }
5381
Michal Karpinski8596ded2018-11-14 14:43:48 +00005382 boolean isBackgroundActivityStartsEnabled() {
5383 return mAmInternal.isBackgroundActivityStartsEnabled();
5384 }
5385
Wale Ogunwalef6733932018-06-27 05:14:34 -07005386 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005387 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005388 mWindowManager.enableScreenAfterBoot();
5389
5390 synchronized (mGlobalLock) {
5391 updateEventDispatchingLocked(booted);
5392 }
5393 }
5394
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005395 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5396 if (r == null || !r.hasProcess()) {
5397 return KEY_DISPATCHING_TIMEOUT_MS;
5398 }
5399 return getInputDispatchingTimeoutLocked(r.app);
5400 }
5401
5402 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005403 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005404 }
5405
Wale Ogunwalef6733932018-06-27 05:14:34 -07005406 /**
5407 * Decide based on the configuration whether we should show the ANR,
5408 * crash, etc dialogs. The idea is that if there is no affordance to
5409 * press the on-screen buttons, or the user experience would be more
5410 * greatly impacted than the crash itself, we shouldn't show the dialog.
5411 *
5412 * A thought: SystemUI might also want to get told about this, the Power
5413 * dialog / global actions also might want different behaviors.
5414 */
5415 private void updateShouldShowDialogsLocked(Configuration config) {
5416 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5417 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5418 && config.navigation == Configuration.NAVIGATION_NONAV);
5419 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5420 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5421 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5422 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5423 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5424 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5425 HIDE_ERROR_DIALOGS, 0) != 0;
5426 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5427 }
5428
5429 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5430 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5431 FONT_SCALE, 1.0f, userId);
5432
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005433 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005434 if (getGlobalConfiguration().fontScale == scaleFactor) {
5435 return;
5436 }
5437
5438 final Configuration configuration
5439 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5440 configuration.fontScale = scaleFactor;
5441 updatePersistentConfiguration(configuration, userId);
5442 }
5443 }
5444
5445 // Actually is sleeping or shutting down or whatever else in the future
5446 // is an inactive state.
5447 boolean isSleepingOrShuttingDownLocked() {
5448 return isSleepingLocked() || mShuttingDown;
5449 }
5450
5451 boolean isSleepingLocked() {
5452 return mSleeping;
5453 }
5454
Riddle Hsu16567132018-08-16 21:37:47 +08005455 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005456 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005457 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005458 if (task.isActivityTypeStandard()) {
5459 if (mCurAppTimeTracker != r.appTimeTracker) {
5460 // We are switching app tracking. Complete the current one.
5461 if (mCurAppTimeTracker != null) {
5462 mCurAppTimeTracker.stop();
5463 mH.obtainMessage(
5464 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005465 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005466 mCurAppTimeTracker = null;
5467 }
5468 if (r.appTimeTracker != null) {
5469 mCurAppTimeTracker = r.appTimeTracker;
5470 startTimeTrackingFocusedActivityLocked();
5471 }
5472 } else {
5473 startTimeTrackingFocusedActivityLocked();
5474 }
5475 } else {
5476 r.appTimeTracker = null;
5477 }
5478 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5479 // TODO: Probably not, because we don't want to resume voice on switching
5480 // back to this activity
5481 if (task.voiceInteractor != null) {
5482 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5483 } else {
5484 finishRunningVoiceLocked();
5485
5486 if (mLastResumedActivity != null) {
5487 final IVoiceInteractionSession session;
5488
Louis Changcdec0802019-11-11 11:45:07 +08005489 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005490 if (lastResumedActivityTask != null
5491 && lastResumedActivityTask.voiceSession != null) {
5492 session = lastResumedActivityTask.voiceSession;
5493 } else {
5494 session = mLastResumedActivity.voiceSession;
5495 }
5496
5497 if (session != null) {
5498 // We had been in a voice interaction session, but now focused has
5499 // move to something different. Just finish the session, we can't
5500 // return to it and retain the proper state and synchronization with
5501 // the voice interaction service.
5502 finishVoiceTask(session);
5503 }
5504 }
5505 }
5506
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005507 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5508 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005509 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005510 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5511
Wale Ogunwalef6733932018-06-27 05:14:34 -07005512 updateResumedAppTrace(r);
5513 mLastResumedActivity = r;
5514
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005515 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005516
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005517 if (prevTask == null || task != prevTask) {
5518 if (prevTask != null) {
5519 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5520 }
5521 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5522 }
5523
Wale Ogunwalef6733932018-06-27 05:14:34 -07005524 applyUpdateLockStateLocked(r);
5525 applyUpdateVrModeLocked(r);
5526
Jeff Changd136e772019-11-05 20:33:52 +08005527 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005528 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005529 r == null ? "NULL" : r.shortComponentName,
5530 reason);
5531 }
5532
5533 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5534 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005535 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005536 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005537 updateSleepIfNeededLocked();
5538 return token;
5539 }
5540 }
5541
5542 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005543 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005544 final boolean wasSleeping = mSleeping;
5545 boolean updateOomAdj = false;
5546
5547 if (!shouldSleep) {
5548 // If wasSleeping is true, we need to wake up activity manager state from when
5549 // we started sleeping. In either case, we need to apply the sleep tokens, which
5550 // will wake up stacks or put them to sleep as appropriate.
5551 if (wasSleeping) {
5552 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005553 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5554 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005555 startTimeTrackingFocusedActivityLocked();
5556 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005557 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005558 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5559 }
Louis Chang149d5c82019-12-30 09:47:39 +08005560 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005561 if (wasSleeping) {
5562 updateOomAdj = true;
5563 }
5564 } else if (!mSleeping && shouldSleep) {
5565 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005566 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5567 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005568 if (mCurAppTimeTracker != null) {
5569 mCurAppTimeTracker.stop();
5570 }
5571 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005572 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005573 mStackSupervisor.goingToSleepLocked();
5574 updateResumedAppTrace(null /* resumed */);
5575 updateOomAdj = true;
5576 }
5577 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005578 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005579 }
5580 }
5581
5582 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005583 mH.removeCallbacks(mUpdateOomAdjRunnable);
5584 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005585 }
5586
Wale Ogunwale53783742018-09-16 10:21:51 -07005587 void updateCpuStats() {
5588 mH.post(mAmInternal::updateCpuStats);
5589 }
5590
Hui Yu03d12402018-12-06 18:00:37 -08005591 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5592 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005593 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5594 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005595 mH.sendMessage(m);
5596 }
5597
Hui Yu03d12402018-12-06 18:00:37 -08005598 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005599 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005600 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005601 if (task != null) {
5602 final ActivityRecord rootActivity = task.getRootActivity();
5603 if (rootActivity != null) {
5604 taskRoot = rootActivity.mActivityComponent;
5605 }
5606 }
5607
Hui Yu03d12402018-12-06 18:00:37 -08005608 final Message m = PooledLambda.obtainMessage(
5609 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005610 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005611 mH.sendMessage(m);
5612 }
5613
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005614 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5615 String hostingType) {
5616 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005617 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5618 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005619 + activity.processName);
5620 }
5621 // Post message to start process to avoid possible deadlock of calling into AMS with the
5622 // ATMS lock held.
5623 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5624 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5625 isTop, hostingType, activity.intent.getComponent());
5626 mH.sendMessage(m);
5627 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005628 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005629 }
5630 }
5631
Wale Ogunwale53783742018-09-16 10:21:51 -07005632 void setBooting(boolean booting) {
5633 mAmInternal.setBooting(booting);
5634 }
5635
5636 boolean isBooting() {
5637 return mAmInternal.isBooting();
5638 }
5639
5640 void setBooted(boolean booted) {
5641 mAmInternal.setBooted(booted);
5642 }
5643
5644 boolean isBooted() {
5645 return mAmInternal.isBooted();
5646 }
5647
5648 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5649 mH.post(() -> {
5650 if (finishBooting) {
5651 mAmInternal.finishBooting();
5652 }
5653 if (enableScreen) {
5654 mInternal.enableScreenAfterBoot(isBooted());
5655 }
5656 });
5657 }
5658
5659 void setHeavyWeightProcess(ActivityRecord root) {
5660 mHeavyWeightProcess = root.app;
5661 final Message m = PooledLambda.obtainMessage(
5662 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005663 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005664 mH.sendMessage(m);
5665 }
5666
5667 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5668 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5669 return;
5670 }
5671
5672 mHeavyWeightProcess = null;
5673 final Message m = PooledLambda.obtainMessage(
5674 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5675 proc.mUserId);
5676 mH.sendMessage(m);
5677 }
5678
5679 private void cancelHeavyWeightProcessNotification(int userId) {
5680 final INotificationManager inm = NotificationManager.getService();
5681 if (inm == null) {
5682 return;
5683 }
5684 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005685 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005686 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5687 } catch (RuntimeException e) {
5688 Slog.w(TAG, "Error canceling notification for service", e);
5689 } catch (RemoteException e) {
5690 }
5691
5692 }
5693
5694 private void postHeavyWeightProcessNotification(
5695 WindowProcessController proc, Intent intent, int userId) {
5696 if (proc == null) {
5697 return;
5698 }
5699
5700 final INotificationManager inm = NotificationManager.getService();
5701 if (inm == null) {
5702 return;
5703 }
5704
5705 try {
5706 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5707 String text = mContext.getString(R.string.heavy_weight_notification,
5708 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5709 Notification notification =
5710 new Notification.Builder(context,
5711 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5712 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5713 .setWhen(0)
5714 .setOngoing(true)
5715 .setTicker(text)
5716 .setColor(mContext.getColor(
5717 com.android.internal.R.color.system_notification_accent_color))
5718 .setContentTitle(text)
5719 .setContentText(
5720 mContext.getText(R.string.heavy_weight_notification_detail))
5721 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5722 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5723 new UserHandle(userId)))
5724 .build();
5725 try {
5726 inm.enqueueNotificationWithTag("android", "android", null,
5727 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5728 } catch (RuntimeException e) {
5729 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5730 } catch (RemoteException e) {
5731 }
5732 } catch (PackageManager.NameNotFoundException e) {
5733 Slog.w(TAG, "Unable to create context for heavy notification", e);
5734 }
5735
5736 }
5737
Philip P. Moltmannee295092020-02-10 08:46:26 -08005738 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5739 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5740 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005741
5742 ActivityRecord activity = null;
5743 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5744 activity = ActivityRecord.isInStackLocked(token);
5745 if (activity == null) {
5746 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5747 return null;
5748 }
5749 if (activity.finishing) {
5750 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5751 return null;
5752 }
5753 }
5754
5755 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005756 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5757 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005758 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5759 if (noCreate) {
5760 return rec;
5761 }
5762 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5763 if (activity.pendingResults == null) {
5764 activity.pendingResults = new HashSet<>();
5765 }
5766 activity.pendingResults.add(rec.ref);
5767 }
5768 return rec;
5769 }
5770
Andrii Kulian52d255c2018-07-13 11:32:19 -07005771 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005772 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005773 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005774 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5775 mCurAppTimeTracker.start(resumedActivity.packageName);
5776 }
5777 }
5778
5779 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5780 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005781 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005782 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5783 }
5784 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005785 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005786 constructResumedTraceName(resumed.packageName), 0);
5787 }
5788 mTracedResumedActivity = resumed;
5789 }
5790
5791 private String constructResumedTraceName(String packageName) {
5792 return "focused app: " + packageName;
5793 }
5794
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005795 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005796 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005797 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005798 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005799 // mainStack is null during startup.
5800 if (mainStack != null) {
5801 if (changes != 0 && starting == null) {
5802 // If the configuration changed, and the caller is not already
5803 // in the process of starting an activity, then find the top
5804 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005805 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005806 }
5807
5808 if (starting != null) {
5809 kept = starting.ensureActivityConfiguration(changes,
5810 false /* preserveWindow */);
5811 // And we need to make sure at this point that all other activities
5812 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005813 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005814 !PRESERVE_WINDOWS);
5815 }
5816 }
5817
5818 return kept;
5819 }
5820
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005821 void scheduleAppGcsLocked() {
5822 mH.post(() -> mAmInternal.scheduleAppGcs());
5823 }
5824
Wale Ogunwale53783742018-09-16 10:21:51 -07005825 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5826 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5827 }
5828
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005829 /**
5830 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5831 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5832 * on demand.
5833 */
5834 IPackageManager getPackageManager() {
5835 return AppGlobals.getPackageManager();
5836 }
5837
5838 PackageManagerInternal getPackageManagerInternalLocked() {
5839 if (mPmInternal == null) {
5840 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5841 }
5842 return mPmInternal;
5843 }
5844
Darryl L Johnsona0982222020-02-18 18:21:51 -08005845 ComponentName getSysUiServiceComponentLocked() {
5846 if (mSysUiServiceComponent == null) {
5847 final PackageManagerInternal pm = getPackageManagerInternalLocked();
5848 mSysUiServiceComponent = pm.getSystemUiServiceComponent();
5849 }
5850 return mSysUiServiceComponent;
5851 }
5852
Hai Zhangf4da9be2019-05-01 13:46:06 +08005853 PermissionPolicyInternal getPermissionPolicyInternal() {
5854 if (mPermissionPolicyInternal == null) {
5855 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5856 }
5857 return mPermissionPolicyInternal;
5858 }
5859
Wale Ogunwale008163e2018-07-23 23:11:08 -07005860 AppWarnings getAppWarningsLocked() {
5861 return mAppWarnings;
5862 }
5863
Wale Ogunwale214f3482018-10-04 11:00:47 -07005864 Intent getHomeIntent() {
5865 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5866 intent.setComponent(mTopComponent);
5867 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5868 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5869 intent.addCategory(Intent.CATEGORY_HOME);
5870 }
5871 return intent;
5872 }
5873
Chilun2ef71f72018-11-16 17:57:15 +08005874 /**
5875 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5876 * activities.
5877 *
Chilun939b05c2020-02-19 14:50:59 +08005878 * @param preferredPackage Specify a preferred package name, otherwise use the package name
5879 * defined in config_secondaryHomePackage.
Chilun2ef71f72018-11-16 17:57:15 +08005880 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5881 */
5882 Intent getSecondaryHomeIntent(String preferredPackage) {
5883 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005884 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5885 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5886 if (preferredPackage == null || useSystemProvidedLauncher) {
Chilun939b05c2020-02-19 14:50:59 +08005887 // Using the package name stored in config if no preferred package name or forced.
5888 final String secondaryHomePackage = mContext.getResources().getString(
5889 com.android.internal.R.string.config_secondaryHomePackage);
5890 intent.setPackage(secondaryHomePackage);
Chilun2ef71f72018-11-16 17:57:15 +08005891 } else {
5892 intent.setPackage(preferredPackage);
5893 }
5894 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5895 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5896 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5897 }
5898 return intent;
5899 }
5900
Wale Ogunwale214f3482018-10-04 11:00:47 -07005901 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5902 if (info == null) return null;
5903 ApplicationInfo newInfo = new ApplicationInfo(info);
5904 newInfo.initForUser(userId);
5905 return newInfo;
5906 }
5907
Wale Ogunwale9c103022018-10-18 07:44:54 -07005908 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005909 if (uid == SYSTEM_UID) {
5910 // The system gets to run in any process. If there are multiple processes with the same
5911 // uid, just pick the first (this should never happen).
5912 final SparseArray<WindowProcessController> procs =
5913 mProcessNames.getMap().get(processName);
5914 if (procs == null) return null;
5915 final int procCount = procs.size();
5916 for (int i = 0; i < procCount; i++) {
5917 final int procUid = procs.keyAt(i);
5918 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5919 // Don't use an app process or different user process for system component.
5920 continue;
5921 }
5922 return procs.valueAt(i);
5923 }
5924 }
5925
5926 return mProcessNames.get(processName, uid);
5927 }
5928
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005929 WindowProcessController getProcessController(IApplicationThread thread) {
5930 if (thread == null) {
5931 return null;
5932 }
5933
5934 final IBinder threadBinder = thread.asBinder();
5935 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5936 for (int i = pmap.size()-1; i >= 0; i--) {
5937 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5938 for (int j = procs.size() - 1; j >= 0; j--) {
5939 final WindowProcessController proc = procs.valueAt(j);
5940 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5941 return proc;
5942 }
5943 }
5944 }
5945
5946 return null;
5947 }
5948
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005949 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005950 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005951 if (proc == null) return null;
5952 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5953 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005954 }
5955 return null;
5956 }
5957
Riddle Hsua0536432019-02-16 00:38:59 +08005958 int getUidState(int uid) {
5959 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005960 }
5961
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005962 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005963 // A uid is considered to be foreground if it has a visible non-toast window.
5964 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005965 }
5966
Ricky Wai96f5c352019-04-10 18:40:17 +01005967 boolean isDeviceOwner(int uid) {
5968 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005969 }
5970
Ricky Wai96f5c352019-04-10 18:40:17 +01005971 void setDeviceOwnerUid(int uid) {
5972 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005973 }
5974
Wale Ogunwale9de19442018-10-18 19:05:03 -07005975 /**
5976 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5977 * the whitelist
5978 */
5979 String getPendingTempWhitelistTagForUidLocked(int uid) {
5980 return mPendingTempWhitelist.get(uid);
5981 }
5982
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005983 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5984 if (true || Build.IS_USER) {
5985 return;
5986 }
5987
5988 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5989 StrictMode.allowThreadDiskWrites();
5990 try {
5991 File tracesDir = new File("/data/anr");
5992 File tracesFile = null;
5993 try {
5994 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5995
5996 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005997 String timeString =
5998 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5999 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006000 sb.append(": ");
6001 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6002 sb.append(" since ");
6003 sb.append(msg);
6004 FileOutputStream fos = new FileOutputStream(tracesFile);
6005 fos.write(sb.toString().getBytes());
6006 if (app == null) {
6007 fos.write("\n*** No application process!".getBytes());
6008 }
6009 fos.close();
6010 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6011 } catch (IOException e) {
6012 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6013 return;
6014 }
6015
6016 if (app != null && app.getPid() > 0) {
6017 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6018 firstPids.add(app.getPid());
6019 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6020 }
6021
6022 File lastTracesFile = null;
6023 File curTracesFile = null;
6024 for (int i=9; i>=0; i--) {
6025 String name = String.format(Locale.US, "slow%02d.txt", i);
6026 curTracesFile = new File(tracesDir, name);
6027 if (curTracesFile.exists()) {
6028 if (lastTracesFile != null) {
6029 curTracesFile.renameTo(lastTracesFile);
6030 } else {
6031 curTracesFile.delete();
6032 }
6033 }
6034 lastTracesFile = curTracesFile;
6035 }
6036 tracesFile.renameTo(curTracesFile);
6037 } finally {
6038 StrictMode.setThreadPolicy(oldPolicy);
6039 }
6040 }
6041
Michal Karpinskida34cd42019-04-02 19:46:52 +01006042 boolean isAssociatedCompanionApp(int userId, int uid) {
6043 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6044 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006045 return false;
6046 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006047 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006048 }
6049
Issei Suzuki734bc942019-06-05 13:59:52 +02006050 void notifySingleTaskDisplayEmpty(int displayId) {
6051 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6052 }
6053
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006054 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006055 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006056
6057
Wale Ogunwale98875612018-10-12 07:53:02 -07006058 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6059 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006060
Riddle Hsud93a6c42018-11-29 21:50:06 +08006061 H(Looper looper) {
6062 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006063 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006064
6065 @Override
6066 public void handleMessage(Message msg) {
6067 switch (msg.what) {
6068 case REPORT_TIME_TRACKER_MSG: {
6069 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6070 tracker.deliverResult(mContext);
6071 } break;
6072 }
6073 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006074 }
6075
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006076 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006077 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006078
6079 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006080 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006081 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006082
6083 @Override
6084 public void handleMessage(Message msg) {
6085 switch (msg.what) {
6086 case DISMISS_DIALOG_UI_MSG: {
6087 final Dialog d = (Dialog) msg.obj;
6088 d.dismiss();
6089 break;
6090 }
6091 }
6092 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006093 }
6094
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006095 final class LocalService extends ActivityTaskManagerInternal {
6096 @Override
6097 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006098 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006099 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006100 }
6101
6102 @Override
6103 public ComponentName getHomeActivityForUser(int userId) {
6104 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006105 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006106 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006107 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006108 }
6109 }
6110
6111 @Override
6112 public void onLocalVoiceInteractionStarted(IBinder activity,
6113 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6114 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006115 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006116 }
6117 }
6118
6119 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006120 public void notifySingleTaskDisplayDrawn(int displayId) {
6121 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6122 }
6123
6124 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006125 public void notifyAppTransitionFinished() {
6126 synchronized (mGlobalLock) {
6127 mStackSupervisor.notifyAppTransitionDone();
6128 }
6129 }
6130
6131 @Override
6132 public void notifyAppTransitionCancelled() {
6133 synchronized (mGlobalLock) {
6134 mStackSupervisor.notifyAppTransitionDone();
6135 }
6136 }
6137
6138 @Override
6139 public List<IBinder> getTopVisibleActivities() {
6140 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006141 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006142 }
6143 }
6144
6145 @Override
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00006146 public boolean hasResumedActivity(int uid) {
6147 synchronized (mGlobalLock) {
6148 final ArraySet<WindowProcessController> processes = mProcessMap.getProcesses(uid);
6149 for (int i = 0, n = processes.size(); i < n; i++) {
6150 final WindowProcessController process = processes.valueAt(i);
6151 if (process.hasResumedActivity()) {
6152 return true;
6153 }
6154 }
6155 }
6156 return false;
6157 }
6158
6159 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006160 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6161 int userId, Intent[] intents, Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006162 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006163 final String[] resolvedTypes = new String[intents.length];
6164
6165 // UID of the package on user userId.
6166 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6167 // packageUid may not be initialized.
6168 int packageUid = 0;
6169 final long ident = Binder.clearCallingIdentity();
6170
6171 try {
6172 for (int i = 0; i < intents.length; i++) {
6173 resolvedTypes[i] =
6174 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6175 }
6176
6177 packageUid = AppGlobals.getPackageManager().getPackageUid(
6178 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6179 } catch (RemoteException e) {
6180 // Shouldn't happen.
6181 } finally {
6182 Binder.restoreCallingIdentity(ident);
6183 }
6184
Riddle Hsu591bf612019-02-14 17:55:31 +08006185 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006186 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006187 intents, resolvedTypes, null /* resultTo */,
6188 SafeActivityOptions.fromBundle(bOptions), userId,
6189 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6190 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006191 }
6192
6193 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006194 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006195 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6196 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6197 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006198 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006199 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006200 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006201 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006202 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6203 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006204 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006205 }
6206 }
6207
6208 @Override
6209 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006210 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6211 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6212 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6213 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006214 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006215 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006216 synchronized (mGlobalLock) {
6217 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006218 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6219 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6220 reason, validateIncomingUser, originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006221 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006222 }
6223 }
6224
6225 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006226 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006227 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6228 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006229 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006230 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006231 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006232 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006233 false /*validateIncomingUser*/);
6234 }
6235
6236 @Override
lumark588a3e82018-07-20 18:53:54 +08006237 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006238 synchronized (mGlobalLock) {
6239
6240 // We might change the visibilities here, so prepare an empty app transition which
6241 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006242 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006243 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006244 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006245 return;
6246 }
Louis Chang677921f2019-12-06 16:44:24 +08006247 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006248 final boolean wasTransitionSet =
6249 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006250 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006251 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006252 }
Louis Chang149d5c82019-12-30 09:47:39 +08006253 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006254
6255 // If there was a transition set already we don't want to interfere with it as we
6256 // might be starting it too early.
6257 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006258 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006259 }
6260 }
6261 if (callback != null) {
6262 callback.run();
6263 }
6264 }
6265
6266 @Override
6267 public void notifyKeyguardTrustedChanged() {
6268 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006269 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006270 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006271 }
6272 }
6273 }
6274
6275 /**
6276 * Called after virtual display Id is updated by
6277 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6278 * {@param vrVr2dDisplayId}.
6279 */
6280 @Override
6281 public void setVr2dDisplayId(int vr2dDisplayId) {
6282 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6283 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006284 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006285 }
6286 }
6287
6288 @Override
6289 public void setFocusedActivity(IBinder token) {
6290 synchronized (mGlobalLock) {
6291 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6292 if (r == null) {
6293 throw new IllegalArgumentException(
6294 "setFocusedActivity: No activity record matching token=" + token);
6295 }
Louis Chang19443452018-10-09 12:10:21 +08006296 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006297 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006298 }
6299 }
6300 }
6301
6302 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006303 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006304 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006305 }
6306
6307 @Override
6308 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006309 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006310 }
6311
6312 @Override
6313 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006314 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006315 }
6316
6317 @Override
6318 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6319 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6320 }
6321
6322 @Override
6323 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006324 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006325 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006326
6327 @Override
6328 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6329 synchronized (mGlobalLock) {
6330 mActiveVoiceInteractionServiceComponent = component;
6331 }
6332 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006333
6334 @Override
6335 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6336 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6337 return;
6338 }
6339 synchronized (mGlobalLock) {
6340 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6341 if (types == null) {
6342 if (uid < 0) {
6343 return;
6344 }
6345 types = new ArrayMap<>();
6346 mAllowAppSwitchUids.put(userId, types);
6347 }
6348 if (uid < 0) {
6349 types.remove(type);
6350 } else {
6351 types.put(type, uid);
6352 }
6353 }
6354 }
6355
6356 @Override
6357 public void onUserStopped(int userId) {
6358 synchronized (mGlobalLock) {
6359 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6360 mAllowAppSwitchUids.remove(userId);
6361 }
6362 }
6363
6364 @Override
6365 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6366 synchronized (mGlobalLock) {
6367 return ActivityTaskManagerService.this.isGetTasksAllowed(
6368 caller, callingPid, callingUid);
6369 }
6370 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006371
Riddle Hsua0536432019-02-16 00:38:59 +08006372 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006373 @Override
6374 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006375 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006376 mProcessNames.put(proc.mName, proc.mUid, proc);
6377 }
6378 }
6379
Riddle Hsua0536432019-02-16 00:38:59 +08006380 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006381 @Override
6382 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006383 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006384 mProcessNames.remove(name, uid);
6385 }
6386 }
6387
Riddle Hsua0536432019-02-16 00:38:59 +08006388 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006389 @Override
6390 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006391 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006392 if (proc == mHomeProcess) {
6393 mHomeProcess = null;
6394 }
6395 if (proc == mPreviousProcess) {
6396 mPreviousProcess = null;
6397 }
6398 }
6399 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006400
Riddle Hsua0536432019-02-16 00:38:59 +08006401 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006402 @Override
6403 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006404 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006405 return mTopProcessState;
6406 }
6407 }
6408
Riddle Hsua0536432019-02-16 00:38:59 +08006409 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006410 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006411 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006412 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006413 return proc == mHeavyWeightProcess;
6414 }
6415 }
6416
Riddle Hsua0536432019-02-16 00:38:59 +08006417 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006418 @Override
6419 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006420 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006421 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6422 }
6423 }
6424
6425 @Override
6426 public void finishHeavyWeightApp() {
6427 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006428 if (mHeavyWeightProcess != null) {
6429 mHeavyWeightProcess.finishActivities();
6430 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006431 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6432 mHeavyWeightProcess);
6433 }
6434 }
6435
Riddle Hsua0536432019-02-16 00:38:59 +08006436 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006437 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006438 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006439 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006440 return isSleepingLocked();
6441 }
6442 }
6443
6444 @Override
6445 public boolean isShuttingDown() {
6446 synchronized (mGlobalLock) {
6447 return mShuttingDown;
6448 }
6449 }
6450
6451 @Override
6452 public boolean shuttingDown(boolean booted, int timeout) {
6453 synchronized (mGlobalLock) {
6454 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006455 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006456 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006457 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006458 return mStackSupervisor.shutdownLocked(timeout);
6459 }
6460 }
6461
6462 @Override
6463 public void enableScreenAfterBoot(boolean booted) {
6464 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006465 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006466 mWindowManager.enableScreenAfterBoot();
6467 updateEventDispatchingLocked(booted);
6468 }
6469 }
6470
6471 @Override
6472 public boolean showStrictModeViolationDialog() {
6473 synchronized (mGlobalLock) {
6474 return mShowDialogs && !mSleeping && !mShuttingDown;
6475 }
6476 }
6477
6478 @Override
6479 public void showSystemReadyErrorDialogsIfNeeded() {
6480 synchronized (mGlobalLock) {
6481 try {
6482 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6483 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6484 + " data partition or your device will be unstable.");
6485 mUiHandler.post(() -> {
6486 if (mShowDialogs) {
6487 AlertDialog d = new BaseErrorDialog(mUiContext);
6488 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6489 d.setCancelable(false);
6490 d.setTitle(mUiContext.getText(R.string.android_system_label));
6491 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6492 d.setButton(DialogInterface.BUTTON_POSITIVE,
6493 mUiContext.getText(R.string.ok),
6494 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6495 d.show();
6496 }
6497 });
6498 }
6499 } catch (RemoteException e) {
6500 }
6501
6502 if (!Build.isBuildConsistent()) {
6503 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6504 mUiHandler.post(() -> {
6505 if (mShowDialogs) {
6506 AlertDialog d = new BaseErrorDialog(mUiContext);
6507 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6508 d.setCancelable(false);
6509 d.setTitle(mUiContext.getText(R.string.android_system_label));
6510 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6511 d.setButton(DialogInterface.BUTTON_POSITIVE,
6512 mUiContext.getText(R.string.ok),
6513 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6514 d.show();
6515 }
6516 });
6517 }
6518 }
6519 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006520
6521 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006522 public void onProcessMapped(int pid, WindowProcessController proc) {
6523 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006524 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006525 }
6526 }
6527
6528 @Override
6529 public void onProcessUnMapped(int pid) {
6530 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006531 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006532 }
6533 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006534
6535 @Override
6536 public void onPackageDataCleared(String name) {
6537 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006538 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006539 mAppWarnings.onPackageDataCleared(name);
6540 }
6541 }
6542
6543 @Override
6544 public void onPackageUninstalled(String name) {
6545 synchronized (mGlobalLock) {
6546 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006547 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006548 }
6549 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006550
6551 @Override
6552 public void onPackageAdded(String name, boolean replacing) {
6553 synchronized (mGlobalLock) {
6554 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6555 }
6556 }
6557
6558 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006559 public void onPackageReplaced(ApplicationInfo aInfo) {
6560 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006561 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006562 }
6563 }
6564
6565 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006566 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6567 synchronized (mGlobalLock) {
6568 return compatibilityInfoForPackageLocked(ai);
6569 }
6570 }
6571
Yunfan Chen75157d72018-07-27 14:47:21 +09006572 /**
6573 * Set the corresponding display information for the process global configuration. To be
6574 * called when we need to show IME on a different display.
6575 *
6576 * @param pid The process id associated with the IME window.
6577 * @param displayId The ID of the display showing the IME.
6578 */
6579 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006580 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006581 // Don't update process-level configuration for Multi-Client IME process since other
6582 // IMEs on other displays will also receive this configuration change due to IME
6583 // services use the same application config/context.
6584 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006585
Yunfan Chen75157d72018-07-27 14:47:21 +09006586 if (pid == MY_PID || pid < 0) {
6587 if (DEBUG_CONFIGURATION) {
6588 Slog.w(TAG,
6589 "Trying to update display configuration for system/invalid process.");
6590 }
6591 return;
6592 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006593 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006594 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006595 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006596 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006597 // Call might come when display is not yet added or has been removed.
6598 if (DEBUG_CONFIGURATION) {
6599 Slog.w(TAG, "Trying to update display configuration for non-existing "
6600 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006601 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006602 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006603 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006604 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006605 if (process == null) {
6606 if (DEBUG_CONFIGURATION) {
6607 Slog.w(TAG, "Trying to update display configuration for invalid "
6608 + "process, pid=" + pid);
6609 }
6610 return;
6611 }
lumarkddc77fb2019-06-27 22:22:23 +08006612 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006613 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006614 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006615 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006616
6617 @Override
6618 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006619 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006620 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006621 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006622 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006623 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006624 }
6625 }
6626 }
6627
6628 @Override
6629 public void clearPendingResultForActivity(IBinder activityToken,
6630 WeakReference<PendingIntentRecord> pir) {
6631 synchronized (mGlobalLock) {
6632 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6633 if (r != null && r.pendingResults != null) {
6634 r.pendingResults.remove(pir);
6635 }
6636 }
6637 }
6638
6639 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006640 public ActivityTokens getTopActivityForTask(int taskId) {
6641 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006642 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006643 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006644 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6645 + " Requested task not found");
6646 return null;
6647 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006648 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006649 if (activity == null) {
6650 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6651 + " Requested activity not found");
6652 return null;
6653 }
6654 if (!activity.attachedToProcess()) {
6655 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6656 + activity);
6657 return null;
6658 }
6659 return new ActivityTokens(activity.appToken, activity.assistToken,
6660 activity.app.getThread());
6661 }
6662 }
6663
6664 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006665 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006666 @Nullable String featureId, int callingUid, int userId, IBinder token,
6667 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6668 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006669 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006670 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6671 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006672 }
6673 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006674
6675 @Override
6676 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6677 synchronized (mGlobalLock) {
6678 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6679 if (r == null) {
6680 return null;
6681 }
6682 if (r.mServiceConnectionsHolder == null) {
6683 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6684 ActivityTaskManagerService.this, r);
6685 }
6686
6687 return r.mServiceConnectionsHolder;
6688 }
6689 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006690
6691 @Override
6692 public Intent getHomeIntent() {
6693 synchronized (mGlobalLock) {
6694 return ActivityTaskManagerService.this.getHomeIntent();
6695 }
6696 }
6697
6698 @Override
6699 public boolean startHomeActivity(int userId, String reason) {
6700 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006701 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006702 }
6703 }
6704
6705 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006706 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006707 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006708 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006709 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006710 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006711 }
Chilun8b1f1be2019-03-13 17:14:36 +08006712 }
6713
6714 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006715 public boolean startHomeOnAllDisplays(int userId, String reason) {
6716 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006717 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006718 }
6719 }
6720
Riddle Hsua0536432019-02-16 00:38:59 +08006721 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006722 @Override
6723 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006724 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006725 if (mFactoryTest == FACTORY_TEST_OFF) {
6726 return false;
6727 }
6728 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6729 && wpc.mName.equals(mTopComponent.getPackageName())) {
6730 return true;
6731 }
6732 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6733 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6734 }
6735 }
6736
6737 @Override
6738 public void updateTopComponentForFactoryTest() {
6739 synchronized (mGlobalLock) {
6740 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6741 return;
6742 }
6743 final ResolveInfo ri = mContext.getPackageManager()
6744 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6745 final CharSequence errorMsg;
6746 if (ri != null) {
6747 final ActivityInfo ai = ri.activityInfo;
6748 final ApplicationInfo app = ai.applicationInfo;
6749 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6750 mTopAction = Intent.ACTION_FACTORY_TEST;
6751 mTopData = null;
6752 mTopComponent = new ComponentName(app.packageName, ai.name);
6753 errorMsg = null;
6754 } else {
6755 errorMsg = mContext.getResources().getText(
6756 com.android.internal.R.string.factorytest_not_system);
6757 }
6758 } else {
6759 errorMsg = mContext.getResources().getText(
6760 com.android.internal.R.string.factorytest_no_action);
6761 }
6762 if (errorMsg == null) {
6763 return;
6764 }
6765
6766 mTopAction = null;
6767 mTopData = null;
6768 mTopComponent = null;
6769 mUiHandler.post(() -> {
6770 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6771 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006772 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006773 });
6774 }
6775 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006776
Riddle Hsua0536432019-02-16 00:38:59 +08006777 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006778 @Override
6779 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6780 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006781 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006782 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006783 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006784
6785 wpc.clearRecentTasks();
6786 wpc.clearActivities();
6787
6788 if (wpc.isInstrumenting()) {
6789 finishInstrumentationCallback.run();
6790 }
6791
Jorim Jaggid0752812018-10-16 16:07:20 +02006792 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006793 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006794 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006795 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006796 // If there was nothing to resume, and we are not already restarting
6797 // this process, but there is a visible activity that is hosted by the
6798 // process...then make sure all visible activities are running, taking
6799 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006800 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006801 !PRESERVE_WINDOWS);
6802 }
6803 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006804 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006805 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806 }
6807 }
6808 }
6809
6810 @Override
6811 public void closeSystemDialogs(String reason) {
6812 enforceNotIsolatedCaller("closeSystemDialogs");
6813
6814 final int pid = Binder.getCallingPid();
6815 final int uid = Binder.getCallingUid();
6816 final long origId = Binder.clearCallingIdentity();
6817 try {
6818 synchronized (mGlobalLock) {
6819 // Only allow this from foreground processes, so that background
6820 // applications can't abuse it to prevent system UI from being shown.
6821 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006822 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006823 if (!proc.isPerceptible()) {
6824 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6825 + " from background process " + proc);
6826 return;
6827 }
6828 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006829 mWindowManager.closeSystemDialogs(reason);
6830
Louis Chang149d5c82019-12-30 09:47:39 +08006831 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006832 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006833 // Call into AM outside the synchronized block.
6834 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006835 } finally {
6836 Binder.restoreCallingIdentity(origId);
6837 }
6838 }
6839
6840 @Override
6841 public void cleanupDisabledPackageComponents(
6842 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6843 synchronized (mGlobalLock) {
6844 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006845 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006846 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006847 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006848 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006849 }
6850
6851 // Clean-up disabled tasks
6852 getRecentTasks().cleanupDisabledPackageTasksLocked(
6853 packageName, disabledClasses, userId);
6854 }
6855 }
6856
6857 @Override
6858 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6859 int userId) {
6860 synchronized (mGlobalLock) {
6861
6862 boolean didSomething =
6863 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006864 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006865 null, doit, evenPersistent, userId);
6866 return didSomething;
6867 }
6868 }
6869
6870 @Override
6871 public void resumeTopActivities(boolean scheduleIdle) {
6872 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006873 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006874 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006875 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006876 }
6877 }
6878 }
6879
Riddle Hsua0536432019-02-16 00:38:59 +08006880 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006881 @Override
6882 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006883 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006884 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6885 }
6886 }
6887
Riddle Hsua0536432019-02-16 00:38:59 +08006888 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006889 @Override
6890 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006891 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006892 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6893 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6894 }
6895 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006896 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006897 } finally {
6898 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6899 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006900 }
6901 }
6902
6903 @Override
6904 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6905 try {
6906 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6907 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6908 }
6909 } catch (RemoteException ex) {
6910 throw new SecurityException("Fail to check is caller a privileged app", ex);
6911 }
6912
6913 synchronized (mGlobalLock) {
6914 final long ident = Binder.clearCallingIdentity();
6915 try {
6916 if (mAmInternal.shouldConfirmCredentials(userId)) {
6917 if (mKeyguardController.isKeyguardLocked()) {
6918 // Showing launcher to avoid user entering credential twice.
6919 startHomeActivity(currentUserId, "notifyLockedProfile");
6920 }
Louis Chang149d5c82019-12-30 09:47:39 +08006921 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006922 }
6923 } finally {
6924 Binder.restoreCallingIdentity(ident);
6925 }
6926 }
6927 }
6928
6929 @Override
6930 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6931 mAmInternal.enforceCallingPermission(
6932 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6933
6934 synchronized (mGlobalLock) {
6935 final long ident = Binder.clearCallingIdentity();
6936 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006937 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6938 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006939 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006940 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6941 UserHandle.CURRENT);
6942 } finally {
6943 Binder.restoreCallingIdentity(ident);
6944 }
6945 }
6946 }
6947
6948 @Override
6949 public void writeActivitiesToProto(ProtoOutputStream proto) {
6950 synchronized (mGlobalLock) {
6951 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006952 mRootWindowContainer.dumpDebug(
6953 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006954 }
6955 }
6956
6957 @Override
6958 public void saveANRState(String reason) {
6959 synchronized (mGlobalLock) {
6960 final StringWriter sw = new StringWriter();
6961 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6962 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6963 if (reason != null) {
6964 pw.println(" Reason: " + reason);
6965 }
6966 pw.println();
6967 getActivityStartController().dump(pw, " ", null);
6968 pw.println();
6969 pw.println("-------------------------------------------------------------------------------");
6970 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6971 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6972 "" /* header */);
6973 pw.println();
6974 pw.close();
6975
6976 mLastANRState = sw.toString();
6977 }
6978 }
6979
6980 @Override
6981 public void clearSavedANRState() {
6982 synchronized (mGlobalLock) {
6983 mLastANRState = null;
6984 }
6985 }
6986
6987 @Override
6988 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6989 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6990 synchronized (mGlobalLock) {
6991 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6992 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6993 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6994 dumpLastANRLocked(pw);
6995 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6996 dumpLastANRTracesLocked(pw);
6997 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6998 dumpActivityStarterLocked(pw, dumpPackage);
6999 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7000 dumpActivityContainersLocked(pw);
7001 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7002 if (getRecentTasks() != null) {
7003 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7004 }
7005 }
7006 }
7007 }
7008
7009 @Override
7010 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7011 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7012 int wakefulness) {
7013 synchronized (mGlobalLock) {
7014 if (mHomeProcess != null && (dumpPackage == null
7015 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7016 if (needSep) {
7017 pw.println();
7018 needSep = false;
7019 }
7020 pw.println(" mHomeProcess: " + mHomeProcess);
7021 }
7022 if (mPreviousProcess != null && (dumpPackage == null
7023 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7024 if (needSep) {
7025 pw.println();
7026 needSep = false;
7027 }
7028 pw.println(" mPreviousProcess: " + mPreviousProcess);
7029 }
7030 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7031 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7032 StringBuilder sb = new StringBuilder(128);
7033 sb.append(" mPreviousProcessVisibleTime: ");
7034 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7035 pw.println(sb);
7036 }
7037 if (mHeavyWeightProcess != null && (dumpPackage == null
7038 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7039 if (needSep) {
7040 pw.println();
7041 needSep = false;
7042 }
7043 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7044 }
7045 if (dumpPackage == null) {
7046 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007047 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007048 }
7049 if (dumpAll) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007050 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7051 if (dumpPackage == null && topFocusedStack != null) {
7052 pw.println(" mConfigWillChange: " + topFocusedStack.mConfigWillChange);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007053 }
7054 if (mCompatModePackages.getPackages().size() > 0) {
7055 boolean printed = false;
7056 for (Map.Entry<String, Integer> entry
7057 : mCompatModePackages.getPackages().entrySet()) {
7058 String pkg = entry.getKey();
7059 int mode = entry.getValue();
7060 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7061 continue;
7062 }
7063 if (!printed) {
7064 pw.println(" mScreenCompatPackages:");
7065 printed = true;
7066 }
7067 pw.println(" " + pkg + ": " + mode);
7068 }
7069 }
7070 }
7071
7072 if (dumpPackage == null) {
7073 pw.println(" mWakefulness="
7074 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007075 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007076 if (mRunningVoice != null) {
7077 pw.println(" mRunningVoice=" + mRunningVoice);
7078 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7079 }
7080 pw.println(" mSleeping=" + mSleeping);
7081 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7082 pw.println(" mVrController=" + mVrController);
7083 }
7084 if (mCurAppTimeTracker != null) {
7085 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7086 }
7087 if (mAllowAppSwitchUids.size() > 0) {
7088 boolean printed = false;
7089 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7090 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7091 for (int j = 0; j < types.size(); j++) {
7092 if (dumpPackage == null ||
7093 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7094 if (needSep) {
7095 pw.println();
7096 needSep = false;
7097 }
7098 if (!printed) {
7099 pw.println(" mAllowAppSwitchUids:");
7100 printed = true;
7101 }
7102 pw.print(" User ");
7103 pw.print(mAllowAppSwitchUids.keyAt(i));
7104 pw.print(": Type ");
7105 pw.print(types.keyAt(j));
7106 pw.print(" = ");
7107 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7108 pw.println();
7109 }
7110 }
7111 }
7112 }
7113 if (dumpPackage == null) {
7114 if (mController != null) {
7115 pw.println(" mController=" + mController
7116 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7117 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007118 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7119 pw.println(" mLaunchingActivityWakeLock="
7120 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007121 }
7122
7123 return needSep;
7124 }
7125 }
7126
7127 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007128 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7129 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007130 synchronized (mGlobalLock) {
7131 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007132 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007133 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7134 if (topFocusedStack != null) {
7135 proto.write(CONFIG_WILL_CHANGE, topFocusedStack.mConfigWillChange);
7136 }
sanryhuang498e77e2018-12-06 14:57:01 +08007137 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7138 if (mRunningVoice != null) {
7139 final long vrToken = proto.start(
7140 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7141 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7142 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007143 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007144 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7145 proto.end(vrToken);
7146 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007147 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007148 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007149 if (mController != null) {
7150 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007151 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7152 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007153 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7154 proto.end(token);
7155 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007156 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7157 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007158 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007159 }
7160
7161 if (mHomeProcess != null && (dumpPackage == null
7162 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007163 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007164 }
7165
7166 if (mPreviousProcess != null && (dumpPackage == null
7167 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007168 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007169 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7170 }
7171
7172 if (mHeavyWeightProcess != null && (dumpPackage == null
7173 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007174 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007175 }
7176
7177 for (Map.Entry<String, Integer> entry
7178 : mCompatModePackages.getPackages().entrySet()) {
7179 String pkg = entry.getKey();
7180 int mode = entry.getValue();
7181 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7182 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7183 proto.write(PACKAGE, pkg);
7184 proto.write(MODE, mode);
7185 proto.end(compatToken);
7186 }
7187 }
7188
7189 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007190 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007191 }
7192
7193 }
7194 }
7195
7196 @Override
7197 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7198 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7199 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007200 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7201 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007202 }
7203
7204 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007205 public void dumpForOom(PrintWriter pw) {
7206 synchronized (mGlobalLock) {
7207 pw.println(" mHomeProcess: " + mHomeProcess);
7208 pw.println(" mPreviousProcess: " + mPreviousProcess);
7209 if (mHeavyWeightProcess != null) {
7210 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7211 }
7212 }
7213 }
7214
7215 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007216 public boolean canGcNow() {
7217 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007218 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007219 }
7220 }
7221
Riddle Hsua0536432019-02-16 00:38:59 +08007222 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007223 @Override
7224 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007225 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007226 if (mRootWindowContainer == null) {
7227 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007228 // oomadj after AMS created.
7229 return null;
7230 }
Louis Chang149d5c82019-12-30 09:47:39 +08007231 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007232 return top != null ? top.app : null;
7233 }
7234 }
7235
Riddle Hsua0536432019-02-16 00:38:59 +08007236 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007237 @Override
7238 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007239 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007240 if (mRootWindowContainer != null) {
7241 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007242 }
7243 }
7244 }
7245
7246 @Override
7247 public void scheduleDestroyAllActivities(String reason) {
7248 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007249 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007250 }
7251 }
7252
7253 @Override
7254 public void removeUser(int userId) {
7255 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007256 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007257 }
7258 }
7259
7260 @Override
7261 public boolean switchUser(int userId, UserState userState) {
7262 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007263 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007264 }
7265 }
7266
7267 @Override
7268 public void onHandleAppCrash(WindowProcessController wpc) {
7269 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007270 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007271 }
7272 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007273
7274 @Override
7275 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7276 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007277 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007278 }
7279 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007280
Riddle Hsua0536432019-02-16 00:38:59 +08007281 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007282 @Override
7283 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007284 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007285 }
7286
Riddle Hsua0536432019-02-16 00:38:59 +08007287 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007288 @Override
7289 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007290 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007291 }
7292
Riddle Hsua0536432019-02-16 00:38:59 +08007293 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007294 @Override
7295 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007296 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007297 }
7298
Riddle Hsua0536432019-02-16 00:38:59 +08007299 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007300 @Override
7301 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007302 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007303 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007304
7305 @Override
7306 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007307 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007308 mPendingTempWhitelist.put(uid, tag);
7309 }
7310 }
7311
7312 @Override
7313 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007314 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007315 mPendingTempWhitelist.remove(uid);
7316 }
7317 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007318
7319 @Override
7320 public boolean handleAppCrashInActivityController(String processName, int pid,
7321 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7322 Runnable killCrashingAppCallback) {
7323 synchronized (mGlobalLock) {
7324 if (mController == null) {
7325 return false;
7326 }
7327
7328 try {
7329 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7330 stackTrace)) {
7331 killCrashingAppCallback.run();
7332 return true;
7333 }
7334 } catch (RemoteException e) {
7335 mController = null;
7336 Watchdog.getInstance().setActivityController(null);
7337 }
7338 return false;
7339 }
7340 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007341
7342 @Override
7343 public void removeRecentTasksByPackageName(String packageName, int userId) {
7344 synchronized (mGlobalLock) {
7345 mRecentTasks.removeTasksByPackageName(packageName, userId);
7346 }
7347 }
7348
7349 @Override
7350 public void cleanupRecentTasksForUser(int userId) {
7351 synchronized (mGlobalLock) {
7352 mRecentTasks.cleanupLocked(userId);
7353 }
7354 }
7355
7356 @Override
7357 public void loadRecentTasksForUser(int userId) {
7358 synchronized (mGlobalLock) {
7359 mRecentTasks.loadUserRecentsLocked(userId);
7360 }
7361 }
7362
7363 @Override
7364 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7365 synchronized (mGlobalLock) {
7366 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7367 }
7368 }
7369
7370 @Override
7371 public void flushRecentTasks() {
7372 mRecentTasks.flush();
7373 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007374
7375 @Override
7376 public WindowProcessController getHomeProcess() {
7377 synchronized (mGlobalLock) {
7378 return mHomeProcess;
7379 }
7380 }
7381
7382 @Override
7383 public WindowProcessController getPreviousProcess() {
7384 synchronized (mGlobalLock) {
7385 return mPreviousProcess;
7386 }
7387 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007388
7389 @Override
7390 public void clearLockedTasks(String reason) {
7391 synchronized (mGlobalLock) {
7392 getLockTaskController().clearLockedTasks(reason);
7393 }
7394 }
7395
7396 @Override
7397 public void updateUserConfiguration() {
7398 synchronized (mGlobalLock) {
7399 final Configuration configuration = new Configuration(getGlobalConfiguration());
7400 final int currentUserId = mAmInternal.getCurrentUserId();
7401 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7402 configuration, currentUserId, Settings.System.canWrite(mContext));
7403 updateConfigurationLocked(configuration, null /* starting */,
7404 false /* initLocale */, false /* persistent */, currentUserId,
7405 false /* deferResume */);
7406 }
7407 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007408
7409 @Override
7410 public boolean canShowErrorDialogs() {
7411 synchronized (mGlobalLock) {
7412 return mShowDialogs && !mSleeping && !mShuttingDown
7413 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7414 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7415 mAmInternal.getCurrentUserId())
7416 && !(UserManager.isDeviceInDemoMode(mContext)
7417 && mAmInternal.getCurrentUser().isDemo());
7418 }
7419 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007420
7421 @Override
7422 public void setProfileApp(String profileApp) {
7423 synchronized (mGlobalLock) {
7424 mProfileApp = profileApp;
7425 }
7426 }
7427
7428 @Override
7429 public void setProfileProc(WindowProcessController wpc) {
7430 synchronized (mGlobalLock) {
7431 mProfileProc = wpc;
7432 }
7433 }
7434
7435 @Override
7436 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7437 synchronized (mGlobalLock) {
7438 mProfilerInfo = profilerInfo;
7439 }
7440 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007441
7442 @Override
7443 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7444 synchronized (mGlobalLock) {
7445 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7446 }
7447 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007448
7449 @Override
Zak Cohen84b43182020-03-09 14:36:01 -07007450 public ActivityManager.TaskSnapshot getTaskSnapshotBlocking(
7451 int taskId, boolean isLowResolution) {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08007452 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution,
Zak Cohen84b43182020-03-09 14:36:01 -07007453 true /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007454 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007455
7456 @Override
7457 public boolean isUidForeground(int uid) {
7458 synchronized (mGlobalLock) {
7459 return ActivityTaskManagerService.this.isUidForeground(uid);
7460 }
7461 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007462
7463 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007464 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007465 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007466 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007467 }
7468 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007469
7470 @Override
7471 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007472 // Translate package names into UIDs
7473 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007474 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007475 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7476 if (uid >= 0) {
7477 result.add(uid);
7478 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007479 }
7480 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007481 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007482 }
7483 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007484 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007485}