blob: 35492f4d145df4d46ff09657d6333c0d85af8bed [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Jonathan Scott92335342019-12-17 14:46:26 +000031import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070035import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
36import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070037import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
38import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
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 Peycheva6861e912019-08-21 10:20:23 +02001276 try {
1277 getActivityStartController().obtainStarter(intent, "dream")
1278 .setActivityInfo(a)
1279 .setIsDream(true)
1280 .execute();
1281 return true;
1282 } finally {
1283 Binder.restoreCallingIdentity(origId);
1284 }
1285 }
1286
1287 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001288 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001289 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1290 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1291 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001292 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001293 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001294 enforceNotIsolatedCaller("startActivityAndWait");
1295 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1296 userId, "startActivityAndWait");
1297 // TODO: Switch to user app stacks here.
1298 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1299 .setCaller(caller)
1300 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001301 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001302 .setResolvedType(resolvedType)
1303 .setResultTo(resultTo)
1304 .setResultWho(resultWho)
1305 .setRequestCode(requestCode)
1306 .setStartFlags(startFlags)
1307 .setActivityOptions(bOptions)
1308 .setUserId(userId)
1309 .setProfilerInfo(profilerInfo)
1310 .setWaitResult(res)
1311 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001312 return res;
1313 }
1314
1315 @Override
1316 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001317 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1318 String resultWho, int requestCode, int startFlags, Configuration config,
1319 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001320 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001321 enforceNotIsolatedCaller("startActivityWithConfig");
1322 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1323 "startActivityWithConfig");
1324 // TODO: Switch to user app stacks here.
1325 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1326 .setCaller(caller)
1327 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001328 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001329 .setResolvedType(resolvedType)
1330 .setResultTo(resultTo)
1331 .setResultWho(resultWho)
1332 .setRequestCode(requestCode)
1333 .setStartFlags(startFlags)
1334 .setGlobalConfiguration(config)
1335 .setActivityOptions(bOptions)
1336 .setUserId(userId)
1337 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001338 }
1339
Robert Carr8a2f9132019-11-11 15:03:15 -08001340 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001341 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1342 int callingUid = Binder.getCallingUid();
1343 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1344 throw new SecurityException("Only the system process can request a permission token, "
1345 + "received request from uid: " + callingUid);
1346 }
1347 IBinder permissionToken = new Binder();
1348 synchronized (mGlobalLock) {
1349 mStartActivitySources.put(permissionToken, delegatorToken);
1350 }
1351
1352 Message expireMsg = PooledLambda.obtainMessage(
1353 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1354 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1355
1356 Message forgetMsg = PooledLambda.obtainMessage(
1357 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1358 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1359
1360 return permissionToken;
1361 }
1362
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001363 @Override
1364 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1365 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001366 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1367 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001369 // permission grants) as any app that may launch one of your own activities. So we only
1370 // allow this in two cases:
1371 // 1) The caller is an activity that is part of the core framework, and then only when it
1372 // is running as the system.
1373 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1374 // can only be requested by a system activity, which may then delegate this call to
1375 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001376 final ActivityRecord sourceRecord;
1377 final int targetUid;
1378 final String targetPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001379 final String targetFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001380 final boolean isResolver;
1381 synchronized (mGlobalLock) {
1382 if (resultTo == null) {
1383 throw new SecurityException("Must be called from an activity");
1384 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001385 final IBinder sourceToken;
1386 if (permissionToken != null) {
1387 // To even attempt to use a permissionToken, an app must also have this signature
1388 // permission.
1389 mAmInternal.enforceCallingPermission(
1390 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1391 "startActivityAsCaller");
1392 // If called with a permissionToken, we want the sourceRecord from the delegator
1393 // activity that requested this token.
1394 sourceToken = mStartActivitySources.remove(permissionToken);
1395 if (sourceToken == null) {
1396 // Invalid permissionToken, check if it recently expired.
1397 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1398 throw new SecurityException("Called with expired permission token: "
1399 + permissionToken);
1400 } else {
1401 throw new SecurityException("Called with invalid permission token: "
1402 + permissionToken);
1403 }
1404 }
1405 } else {
1406 // This method was called directly by the source.
1407 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001408 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001409
Louis Chang149d5c82019-12-30 09:47:39 +08001410 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001411 if (sourceRecord == null) {
1412 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413 }
1414 if (sourceRecord.app == null) {
1415 throw new SecurityException("Called without a process attached to activity");
1416 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001417
1418 // Whether called directly or from a delegate, the source activity must be from the
1419 // android package.
1420 if (!sourceRecord.info.packageName.equals("android")) {
1421 throw new SecurityException("Must be called from an activity that is "
1422 + "declared in the android package");
1423 }
1424
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001425 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001426 // This is still okay, as long as this activity is running under the
1427 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001428 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001429 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001430 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001431 + " must be system uid or original calling uid "
1432 + sourceRecord.launchedFromUid);
1433 }
1434 }
1435 if (ignoreTargetSecurity) {
1436 if (intent.getComponent() == null) {
1437 throw new SecurityException(
1438 "Component must be specified with ignoreTargetSecurity");
1439 }
1440 if (intent.getSelector() != null) {
1441 throw new SecurityException(
1442 "Selector not allowed with ignoreTargetSecurity");
1443 }
1444 }
1445 targetUid = sourceRecord.launchedFromUid;
1446 targetPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001447 targetFeatureId = sourceRecord.launchedFromFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001448 isResolver = sourceRecord.isResolverOrChildActivity();
1449 }
1450
1451 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001452 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 }
1454
1455 // TODO: Switch to user app stacks here.
1456 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001457 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458 .setCallingUid(targetUid)
1459 .setCallingPackage(targetPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001460 .setCallingFeatureId(targetFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001461 .setResolvedType(resolvedType)
1462 .setResultTo(resultTo)
1463 .setResultWho(resultWho)
1464 .setRequestCode(requestCode)
1465 .setStartFlags(startFlags)
1466 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001467 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001468 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1469 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001470 // The target may well be in the background, which would normally prevent it
1471 // from starting an activity. Here we definitely want the start to succeed.
1472 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 .execute();
1474 } catch (SecurityException e) {
1475 // XXX need to figure out how to propagate to original app.
1476 // A SecurityException here is generally actually a fault of the original
1477 // calling activity (such as a fairly granting permissions), so propagate it
1478 // back to them.
1479 /*
1480 StringBuilder msg = new StringBuilder();
1481 msg.append("While launching");
1482 msg.append(intent.toString());
1483 msg.append(": ");
1484 msg.append(e.getMessage());
1485 */
1486 throw e;
1487 }
1488 }
1489
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001490 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1491 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001492 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001493 }
1494
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001495 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001496 public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1497 int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001498 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1499 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001500 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001501 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001502 if (session == null || interactor == null) {
1503 throw new NullPointerException("null session or interactor");
1504 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001505 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001506 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001507 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001508 .setCallingUid(callingUid)
1509 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001510 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001511 .setResolvedType(resolvedType)
1512 .setVoiceSession(session)
1513 .setVoiceInteractor(interactor)
1514 .setStartFlags(startFlags)
1515 .setProfilerInfo(profilerInfo)
1516 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001517 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001518 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001519 .execute();
1520 }
1521
1522 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001523 public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1524 int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1525 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001526 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001527 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1528 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001529
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001530 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001531 .setCallingUid(callingUid)
1532 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001533 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001534 .setResolvedType(resolvedType)
1535 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001536 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001537 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001538 .execute();
1539 }
1540
Riddle Hsu609a8e22019-06-27 16:46:29 -06001541 /**
1542 * Start the recents activity to perform the recents animation.
1543 *
1544 * @param intent The intent to start the recents activity.
1545 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1546 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001547 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001548 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1549 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001550 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001552 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001553 final long origId = Binder.clearCallingIdentity();
1554 try {
1555 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001556 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
Philip P. Moltmannee295092020-02-10 08:46:26 -08001557 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001558 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001559 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001560
1561 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001562 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001563 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001564 recentsFeatureId, recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001565 if (recentsAnimationRunner == null) {
1566 anim.preloadRecentsActivity();
1567 } else {
1568 anim.startRecentsActivity(recentsAnimationRunner);
1569 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001570 }
1571 } finally {
1572 Binder.restoreCallingIdentity(origId);
1573 }
1574 }
1575
1576 @Override
1577 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001578 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001579 "startActivityFromRecents()");
1580
1581 final int callingPid = Binder.getCallingPid();
1582 final int callingUid = Binder.getCallingUid();
1583 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1584 final long origId = Binder.clearCallingIdentity();
1585 try {
1586 synchronized (mGlobalLock) {
1587 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1588 safeOptions);
1589 }
1590 } finally {
1591 Binder.restoreCallingIdentity(origId);
1592 }
1593 }
1594
1595 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001596 * Public API to check if the client is allowed to start an activity on specified display.
1597 *
1598 * If the target display is private or virtual, some restrictions will apply.
1599 *
1600 * @param displayId Target display id.
1601 * @param intent Intent used to launch the activity.
1602 * @param resolvedType The MIME type of the intent.
1603 * @param userId The id of the user for whom the call is made.
1604 * @return {@code true} if a call to start an activity on the target display should succeed and
1605 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1606 */
1607 @Override
1608 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1609 String resolvedType, int userId) {
1610 final int callingUid = Binder.getCallingUid();
1611 final int callingPid = Binder.getCallingPid();
1612 final long origId = Binder.clearCallingIdentity();
1613
1614 try {
1615 // Collect information about the target of the Intent.
1616 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1617 0 /* startFlags */, null /* profilerInfo */, userId,
1618 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1619 UserHandle.USER_NULL));
1620 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1621
1622 synchronized (mGlobalLock) {
1623 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1624 aInfo);
1625 }
1626 } finally {
1627 Binder.restoreCallingIdentity(origId);
1628 }
1629 }
1630
1631 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001632 * This is the internal entry point for handling Activity.finish().
1633 *
1634 * @param token The Binder token referencing the Activity we want to finish.
1635 * @param resultCode Result code, if any, from this Activity.
1636 * @param resultData Result data (Intent), if any, from this Activity.
1637 * @param finishTask Whether to finish the task associated with this Activity.
1638 *
1639 * @return Returns true if the activity successfully finished, or false if it is still running.
1640 */
1641 @Override
1642 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1643 int finishTask) {
1644 // Refuse possible leaked file descriptors
1645 if (resultData != null && resultData.hasFileDescriptors()) {
1646 throw new IllegalArgumentException("File descriptors passed in Intent");
1647 }
1648
1649 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001650 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001651 if (r == null) {
1652 return true;
1653 }
1654 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001655 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001656 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001657 if (rootR == null) {
1658 Slog.w(TAG, "Finishing task with all activities already finished");
1659 }
1660 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1661 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001662 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001663 return false;
1664 }
1665
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001666 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1667 // We should consolidate.
1668 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001669 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001670 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001671 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001672 if (next != null) {
1673 // ask watcher if this is allowed
1674 boolean resumeOK = true;
1675 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001676 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001677 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001678 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001679 Watchdog.getInstance().setActivityController(null);
1680 }
1681
1682 if (!resumeOK) {
1683 Slog.i(TAG, "Not finishing activity because controller resumed");
1684 return false;
1685 }
1686 }
1687 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001688
1689 // note down that the process has finished an activity and is in background activity
1690 // starts grace period
1691 if (r.app != null) {
1692 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1693 }
1694
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001695 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001696 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001697 try {
1698 boolean res;
1699 final boolean finishWithRootActivity =
1700 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1701 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1702 || (finishWithRootActivity && r == rootR)) {
1703 // If requested, remove the task that is associated to this activity only if it
1704 // was the root activity in the task. The result code and data is ignored
1705 // because we don't support returning them across task boundaries. Also, to
1706 // keep backwards compatibility we remove the task from recents when finishing
1707 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001708 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001709 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001710 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001711 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001712 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001713 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001714 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001715 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001716 if (!res) {
1717 Slog.i(TAG, "Failed to finish by app-request");
1718 }
1719 }
1720 return res;
1721 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001722 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001723 Binder.restoreCallingIdentity(origId);
1724 }
1725 }
1726 }
1727
1728 @Override
1729 public boolean finishActivityAffinity(IBinder token) {
1730 synchronized (mGlobalLock) {
1731 final long origId = Binder.clearCallingIdentity();
1732 try {
1733 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1734 if (r == null) {
1735 return false;
1736 }
1737
1738 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1739 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001740 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001741 return false;
1742 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001743
1744 final PooledFunction p = PooledLambda.obtainFunction(
1745 ActivityRecord::finishIfSameAffinity, r,
1746 PooledLambda.__(ActivityRecord.class));
1747 r.getTask().forAllActivities(
1748 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1749 p.recycle();
1750
Andrii Kuliande93eff2019-07-12 12:21:27 -07001751 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001752 } finally {
1753 Binder.restoreCallingIdentity(origId);
1754 }
1755 }
1756 }
1757
1758 @Override
1759 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1760 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001761 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001762 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001763 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001764 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1765 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001766 return;
1767 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001768 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1769 false /* processPausingActivities */, config);
1770 if (stopProfiling && r.hasProcess()) {
1771 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001772 }
1773 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001774 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001775 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001776 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001777 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001778 }
1779
1780 @Override
1781 public final void activityResumed(IBinder token) {
1782 final long origId = Binder.clearCallingIdentity();
1783 synchronized (mGlobalLock) {
1784 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001785 }
1786 Binder.restoreCallingIdentity(origId);
1787 }
1788
1789 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001790 public final void activityTopResumedStateLost() {
1791 final long origId = Binder.clearCallingIdentity();
1792 synchronized (mGlobalLock) {
1793 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1794 }
1795 Binder.restoreCallingIdentity(origId);
1796 }
1797
1798 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001799 public final void activityPaused(IBinder token) {
1800 final long origId = Binder.clearCallingIdentity();
1801 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001802 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001803 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1804 if (r != null) {
1805 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001806 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001807 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001808 }
1809 Binder.restoreCallingIdentity(origId);
1810 }
1811
1812 @Override
1813 public final void activityStopped(IBinder token, Bundle icicle,
1814 PersistableBundle persistentState, CharSequence description) {
1815 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1816
1817 // Refuse possible leaked file descriptors
1818 if (icicle != null && icicle.hasFileDescriptors()) {
1819 throw new IllegalArgumentException("File descriptors passed in Bundle");
1820 }
1821
1822 final long origId = Binder.clearCallingIdentity();
1823
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001824 String restartingName = null;
1825 int restartingUid = 0;
1826 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001827 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001828 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001829 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001830 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001831 if (r.attachedToProcess()
1832 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1833 // The activity was requested to restart from
1834 // {@link #restartActivityProcessIfVisible}.
1835 restartingName = r.app.mName;
1836 restartingUid = r.app.mUid;
1837 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001838 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001839 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001840 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001841 }
1842
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001843 if (restartingName != null) {
1844 // In order to let the foreground activity can be restarted with its saved state from
1845 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1846 // until the activity reports stopped with the state. And the activity record will be
1847 // kept because the record state is restarting, then the activity will be restarted
1848 // immediately if it is still the top one.
1849 mStackSupervisor.removeRestartTimeouts(r);
1850 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1851 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001852 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001853
1854 Binder.restoreCallingIdentity(origId);
1855 }
1856
1857 @Override
1858 public final void activityDestroyed(IBinder token) {
1859 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1860 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001861 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001862 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001863 try {
1864 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1865 if (activity != null) {
1866 activity.destroyed("activityDestroyed");
1867 }
1868 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001869 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001870 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001871 }
1872 }
1873 }
1874
1875 @Override
1876 public final void activityRelaunched(IBinder token) {
1877 final long origId = Binder.clearCallingIdentity();
1878 synchronized (mGlobalLock) {
1879 mStackSupervisor.activityRelaunchedLocked(token);
1880 }
1881 Binder.restoreCallingIdentity(origId);
1882 }
1883
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001884 @Override
1885 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1886 synchronized (mGlobalLock) {
1887 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1888 if (r == null) {
1889 return;
1890 }
1891 final long origId = Binder.clearCallingIdentity();
1892 try {
1893 r.setRequestedOrientation(requestedOrientation);
1894 } finally {
1895 Binder.restoreCallingIdentity(origId);
1896 }
1897 }
1898 }
1899
1900 @Override
1901 public int getRequestedOrientation(IBinder token) {
1902 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001903 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1904 return (r != null)
1905 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001906 }
1907 }
1908
1909 @Override
1910 public void setImmersive(IBinder token, boolean immersive) {
1911 synchronized (mGlobalLock) {
1912 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1913 if (r == null) {
1914 throw new IllegalArgumentException();
1915 }
1916 r.immersive = immersive;
1917
1918 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001919 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001920 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001921 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001922 }
1923 }
1924 }
1925
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001926 void applyUpdateLockStateLocked(ActivityRecord r) {
1927 // Modifications to the UpdateLock state are done on our handler, outside
1928 // the activity manager's locks. The new state is determined based on the
1929 // state *now* of the relevant activity record. The object is passed to
1930 // the handler solely for logging detail, not to be consulted/modified.
1931 final boolean nextState = r != null && r.immersive;
1932 mH.post(() -> {
1933 if (mUpdateLock.isHeld() != nextState) {
1934 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1935 "Applying new update lock state '" + nextState + "' for " + r);
1936 if (nextState) {
1937 mUpdateLock.acquire();
1938 } else {
1939 mUpdateLock.release();
1940 }
1941 }
1942 });
1943 }
1944
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 @Override
1946 public boolean isImmersive(IBinder token) {
1947 synchronized (mGlobalLock) {
1948 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1949 if (r == null) {
1950 throw new IllegalArgumentException();
1951 }
1952 return r.immersive;
1953 }
1954 }
1955
1956 @Override
1957 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001958 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001959 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001960 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
1961 if (topFocusedStack == null) {
1962 return false;
1963 }
1964
1965 final ActivityRecord r = topFocusedStack.topRunningActivity();
1966 return r != null && r.immersive;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001967 }
1968 }
1969
1970 @Override
1971 public void overridePendingTransition(IBinder token, String packageName,
1972 int enterAnim, int exitAnim) {
1973 synchronized (mGlobalLock) {
1974 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1975 if (self == null) {
1976 return;
1977 }
1978
1979 final long origId = Binder.clearCallingIdentity();
1980
1981 if (self.isState(
1982 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001983 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001984 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001985 }
1986
1987 Binder.restoreCallingIdentity(origId);
1988 }
1989 }
1990
1991 @Override
1992 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001993 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001994 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001995 final ActivityStack stack = getTopDisplayFocusedStack();
1996 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001997 if (r == null) {
1998 return ActivityManager.COMPAT_MODE_UNKNOWN;
1999 }
Wale Ogunwale53783742018-09-16 10:21:51 -07002000 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002001 }
2002 }
2003
2004 @Override
2005 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002006 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002007 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002008 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002009 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002010 final ActivityStack stack = getTopDisplayFocusedStack();
2011 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002012 if (r == null) {
2013 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
2014 return;
2015 }
2016 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07002017 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002018 }
2019 }
2020
2021 @Override
2022 public int getLaunchedFromUid(IBinder activityToken) {
2023 ActivityRecord srec;
2024 synchronized (mGlobalLock) {
2025 srec = ActivityRecord.forTokenLocked(activityToken);
2026 }
2027 if (srec == null) {
2028 return -1;
2029 }
2030 return srec.launchedFromUid;
2031 }
2032
2033 @Override
2034 public String getLaunchedFromPackage(IBinder activityToken) {
2035 ActivityRecord srec;
2036 synchronized (mGlobalLock) {
2037 srec = ActivityRecord.forTokenLocked(activityToken);
2038 }
2039 if (srec == null) {
2040 return null;
2041 }
2042 return srec.launchedFromPackage;
2043 }
2044
2045 @Override
2046 public boolean convertFromTranslucent(IBinder token) {
2047 final long origId = Binder.clearCallingIdentity();
2048 try {
2049 synchronized (mGlobalLock) {
2050 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2051 if (r == null) {
2052 return false;
2053 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002054 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002055 }
2056 } finally {
2057 Binder.restoreCallingIdentity(origId);
2058 }
2059 }
2060
2061 @Override
2062 public boolean convertToTranslucent(IBinder token, Bundle options) {
2063 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2064 final long origId = Binder.clearCallingIdentity();
2065 try {
2066 synchronized (mGlobalLock) {
2067 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2068 if (r == null) {
2069 return false;
2070 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002071 final ActivityRecord under = r.getTask().getActivityBelow(r);
2072 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2074 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002075 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002076 }
2077 } finally {
2078 Binder.restoreCallingIdentity(origId);
2079 }
2080 }
2081
2082 @Override
2083 public void notifyActivityDrawn(IBinder token) {
2084 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2085 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002086 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002087 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002088 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002089 }
2090 }
2091 }
2092
2093 @Override
2094 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2095 synchronized (mGlobalLock) {
2096 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2097 if (r == null) {
2098 return;
2099 }
2100 r.reportFullyDrawnLocked(restoredFromBundle);
2101 }
2102 }
2103
2104 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002105 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002106 synchronized (mGlobalLock) {
2107 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002108 if (stack != null) {
2109 final int displayId = stack.getDisplayId();
2110 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002111 }
2112 return DEFAULT_DISPLAY;
2113 }
2114 }
2115
2116 @Override
2117 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002118 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002119 long ident = Binder.clearCallingIdentity();
2120 try {
2121 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002122 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002123 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002124 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002125 }
2126 return null;
2127 }
2128 } finally {
2129 Binder.restoreCallingIdentity(ident);
2130 }
2131 }
2132
2133 @Override
2134 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002135 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002136 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2137 final long callingId = Binder.clearCallingIdentity();
2138 try {
2139 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002140 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002141 if (stack == null) {
2142 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2143 return;
2144 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002145 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002146 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002147 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002148 }
2149 }
2150 } finally {
2151 Binder.restoreCallingIdentity(callingId);
2152 }
2153 }
2154
2155 @Override
2156 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002157 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002158 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2159 final long callingId = Binder.clearCallingIdentity();
2160 try {
2161 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002162 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002163 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002164 if (task == null) {
2165 return;
2166 }
2167 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002168 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002169 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002170 }
2171 }
2172 } finally {
2173 Binder.restoreCallingIdentity(callingId);
2174 }
2175 }
2176
2177 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002178 public void restartActivityProcessIfVisible(IBinder activityToken) {
2179 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2180 final long callingId = Binder.clearCallingIdentity();
2181 try {
2182 synchronized (mGlobalLock) {
2183 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2184 if (r == null) {
2185 return;
2186 }
2187 r.restartProcessIfVisible();
2188 }
2189 } finally {
2190 Binder.restoreCallingIdentity(callingId);
2191 }
2192 }
2193
2194 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002195 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002196 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002197 synchronized (mGlobalLock) {
2198 final long ident = Binder.clearCallingIdentity();
2199 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002200 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002201 "remove-task");
2202 } finally {
2203 Binder.restoreCallingIdentity(ident);
2204 }
2205 }
2206 }
2207
2208 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002209 public void removeAllVisibleRecentTasks() {
2210 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2211 synchronized (mGlobalLock) {
2212 final long ident = Binder.clearCallingIdentity();
2213 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002214 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002215 } finally {
2216 Binder.restoreCallingIdentity(ident);
2217 }
2218 }
2219 }
2220
2221 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002222 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2223 synchronized (mGlobalLock) {
2224 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2225 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002226 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 }
2228 }
2229 return false;
2230 }
2231
2232 @Override
2233 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2234 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002235
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002236 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002237 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2238 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002239 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002240 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002241 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002242 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002243 }
2244 }
2245
2246 /**
2247 * Attempts to move a task backwards in z-order (the order of activities within the task is
2248 * unchanged).
2249 *
2250 * There are several possible results of this call:
2251 * - if the task is locked, then we will show the lock toast
2252 * - if there is a task behind the provided task, then that task is made visible and resumed as
2253 * this task is moved to the back
2254 * - otherwise, if there are no other tasks in the stack:
2255 * - if this task is in the pinned stack, then we remove the stack completely, which will
2256 * have the effect of moving the task to the top or bottom of the fullscreen stack
2257 * (depending on whether it is visible)
2258 * - otherwise, we simply return home and hide this task
2259 *
2260 * @param token A reference to the activity we wish to move
2261 * @param nonRoot If false then this only works if the activity is the root
2262 * of a task; if true it will work for any activity in a task.
2263 * @return Returns true if the move completed, false if not.
2264 */
2265 @Override
2266 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002267 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002268 synchronized (mGlobalLock) {
2269 final long origId = Binder.clearCallingIdentity();
2270 try {
2271 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002272 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002273 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002274 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002275 }
2276 } finally {
2277 Binder.restoreCallingIdentity(origId);
2278 }
2279 }
2280 return false;
2281 }
2282
2283 @Override
2284 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002285 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002286 long ident = Binder.clearCallingIdentity();
2287 Rect rect = new Rect();
2288 try {
2289 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002290 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002291 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2292 if (task == null) {
2293 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2294 return rect;
2295 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002296 if (task.getParent() != null) {
2297 rect.set(task.getBounds());
2298 } else if (task.mLastNonFullscreenBounds != null) {
2299 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002300 }
2301 }
2302 } finally {
2303 Binder.restoreCallingIdentity(ident);
2304 }
2305 return rect;
2306 }
2307
2308 @Override
2309 public ActivityManager.TaskDescription getTaskDescription(int id) {
2310 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002311 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002312 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002313 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002314 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2315 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002316 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002317 }
2318 }
2319 return null;
2320 }
2321
2322 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002323 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002324 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08002325 return setTaskWindowingModeSplitScreenPrimary(taskId, toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002326 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002327 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002328 synchronized (mGlobalLock) {
2329 final long ident = Binder.clearCallingIdentity();
2330 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002331 if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2332 return setTaskWindowingModeSplitScreen(taskId, windowingMode, toTop);
2333 }
Louis Chang149d5c82019-12-30 09:47:39 +08002334 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002335 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002336 if (task == null) {
2337 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002338 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002339 }
2340
2341 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2342 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2343
2344 if (!task.isActivityTypeStandardOrUndefined()) {
2345 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2346 + " non-standard task " + taskId + " to windowing mode="
2347 + windowingMode);
2348 }
2349
2350 final ActivityStack stack = task.getStack();
2351 if (toTop) {
2352 stack.moveToFront("setTaskWindowingMode", task);
2353 }
Louis Changa009c762020-02-26 11:21:31 +08002354 // Convert some windowing-mode changes into root-task reparents for split-screen.
2355 if (stack.inSplitScreenWindowingMode()) {
2356 stack.getDisplay().onSplitScreenModeDismissed();
2357
2358 } else {
2359 stack.setWindowingMode(windowingMode);
2360 stack.getDisplay().ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2361 true /* notifyClients */);
2362 }
Winson Chung7ccc6812020-01-23 16:15:10 -08002363 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002364 } finally {
2365 Binder.restoreCallingIdentity(ident);
2366 }
2367 }
2368 }
2369
2370 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002371 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002372 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002373 ActivityRecord r = getCallingRecordLocked(token);
2374 return r != null ? r.info.packageName : null;
2375 }
2376 }
2377
2378 @Override
2379 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002380 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002381 ActivityRecord r = getCallingRecordLocked(token);
2382 return r != null ? r.intent.getComponent() : null;
2383 }
2384 }
2385
2386 private ActivityRecord getCallingRecordLocked(IBinder token) {
2387 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2388 if (r == null) {
2389 return null;
2390 }
2391 return r.resultTo;
2392 }
2393
2394 @Override
2395 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002396 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002397
2398 synchronized (mGlobalLock) {
2399 final long origId = Binder.clearCallingIdentity();
2400 try {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002401 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
2402 if (topFocusedStack != null) {
2403 topFocusedStack.unhandledBackLocked();
2404 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002405 } finally {
2406 Binder.restoreCallingIdentity(origId);
2407 }
2408 }
2409 }
2410
Mark Renouf446251d2019-04-26 10:22:41 -04002411 @Override
2412 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2413 synchronized (mGlobalLock) {
2414 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2415 if (r == null) {
2416 return;
2417 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002418 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002419 if (stack != null && stack.isSingleTaskInstance()) {
2420 // Single-task stacks are used for activities which are presented in floating
2421 // windows above full screen activities. Instead of directly finishing the
2422 // task, a task change listener is used to notify SystemUI so the action can be
2423 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002424 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002425 mTaskChangeNotificationController
2426 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2427 } else {
2428 try {
2429 callback.requestFinish();
2430 } catch (RemoteException e) {
2431 Slog.e(TAG, "Failed to invoke request finish callback", e);
2432 }
2433 }
2434 }
2435 }
2436
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002437 /**
2438 * TODO: Add mController hook
2439 */
2440 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002441 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2442 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002443 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002444
2445 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2446 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002447 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2448 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002449 }
2450 }
2451
Ricky Waiaca8a772019-04-04 16:01:06 +01002452 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2453 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002454 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002455 final int callingPid = Binder.getCallingPid();
2456 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002457 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002458 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002459 SafeActivityOptions.abort(options);
2460 return;
2461 }
2462 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002463 WindowProcessController callerApp = null;
2464 if (appThread != null) {
2465 callerApp = getProcessController(appThread);
2466 }
2467 final ActivityStarter starter = getActivityStartController().obtainStarter(
2468 null /* intent */, "moveTaskToFront");
2469 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
Galia Peycheva6861e912019-08-21 10:20:23 +02002470 -1, callerApp, null, false, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002471 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002472 return;
2473 }
2474 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002475 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002476 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002477 if (task == null) {
2478 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002479 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002480 return;
2481 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002482 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002483 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002484 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002485 return;
2486 }
2487 ActivityOptions realOptions = options != null
2488 ? options.getOptions(mStackSupervisor)
2489 : null;
2490 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2491 false /* forceNonResizable */);
2492
Wale Ogunwale21e06482019-11-18 05:14:15 -08002493 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002494 if (topActivity != null) {
2495
2496 // We are reshowing a task, use a starting window to hide the initial draw delay
2497 // so the transition can start earlier.
2498 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2499 true /* taskSwitch */, fromRecents);
2500 }
2501 } finally {
2502 Binder.restoreCallingIdentity(origId);
2503 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002504 }
2505
Ricky Waiaca8a772019-04-04 16:01:06 +01002506 /**
2507 * Return true if callingUid is system, or packageName belongs to that callingUid.
2508 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002509 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002510 try {
2511 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2512 if (packageName == null) {
2513 return false;
2514 }
2515 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2516 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2517 UserHandle.getUserId(callingUid));
2518 return UserHandle.isSameApp(callingUid, uid);
2519 }
2520 } catch (RemoteException e) {
2521 // Should not happen
2522 }
2523 return true;
2524 }
2525
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002526 /**
2527 * Checks that the provided package name matches the current calling UID, throws a security
2528 * exception if it doesn't.
2529 */
2530 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2531 final int callingUid = Binder.getCallingUid();
2532 if (isSameApp(callingUid, packageName)) {
2533 return;
2534 }
2535 final String msg = "Permission Denial: package=" + packageName
2536 + " does not belong to uid=" + callingUid;
2537 Slog.w(TAG, msg);
2538 throw new SecurityException(msg);
2539 }
2540
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002541 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2542 int callingPid, int callingUid, String name) {
2543 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2544 return true;
2545 }
2546
2547 if (getRecentTasks().isCallerRecents(sourceUid)) {
2548 return true;
2549 }
2550
2551 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2552 if (perm == PackageManager.PERMISSION_GRANTED) {
2553 return true;
2554 }
2555 if (checkAllowAppSwitchUid(sourceUid)) {
2556 return true;
2557 }
2558
2559 // If the actual IPC caller is different from the logical source, then
2560 // also see if they are allowed to control app switches.
2561 if (callingUid != -1 && callingUid != sourceUid) {
2562 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2563 if (perm == PackageManager.PERMISSION_GRANTED) {
2564 return true;
2565 }
2566 if (checkAllowAppSwitchUid(callingUid)) {
2567 return true;
2568 }
2569 }
2570
2571 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2572 return false;
2573 }
2574
2575 private boolean checkAllowAppSwitchUid(int uid) {
2576 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2577 if (types != null) {
2578 for (int i = types.size() - 1; i >= 0; i--) {
2579 if (types.valueAt(i).intValue() == uid) {
2580 return true;
2581 }
2582 }
2583 }
2584 return false;
2585 }
2586
2587 @Override
2588 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2589 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2590 "setActivityController()");
2591 synchronized (mGlobalLock) {
2592 mController = controller;
2593 mControllerIsAMonkey = imAMonkey;
2594 Watchdog.getInstance().setActivityController(controller);
2595 }
2596 }
2597
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002598 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002599 synchronized (mGlobalLock) {
2600 return mController != null && mControllerIsAMonkey;
2601 }
2602 }
2603
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002604 @Override
2605 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2606 synchronized (mGlobalLock) {
2607 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2608 }
2609 }
2610
2611 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002612 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2613 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2614 }
2615
2616 @Override
2617 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2618 @WindowConfiguration.ActivityType int ignoreActivityType,
2619 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2620 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002621 final int callingPid = Binder.getCallingPid();
2622 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002623 final int[] profileIds = getUserManager().getProfileIds(
2624 UserHandle.getUserId(callingUid), true);
2625 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2626 for (int i = 0; i < profileIds.length; i++) {
2627 callingProfileIds.add(profileIds[i]);
2628 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002629 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2630
2631 synchronized (mGlobalLock) {
2632 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2633
Nicholas Sauer0259e532019-08-30 08:24:55 -07002634 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002635 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002636 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002637 }
2638
2639 return list;
2640 }
2641
2642 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002643 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2644 synchronized (mGlobalLock) {
2645 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002646 try {
2647 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2648 if (r == null) return;
2649
2650 final PooledConsumer c = PooledLambda.obtainConsumer(
2651 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2652 r, resultWho, requestCode);
2653 // TODO: This should probably only loop over the task since you need to be in the
2654 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002655 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002656 c.recycle();
2657
2658 updateOomAdj();
2659 } finally {
2660 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002661 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002662 }
2663 }
2664
2665 @Override
2666 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002667 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002668 ActivityStack stack = ActivityRecord.getStackLocked(token);
2669 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002670 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002671 }
2672 return false;
2673 }
2674 }
2675
2676 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002677 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002678 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002679 synchronized (mGlobalLock) {
2680 final long ident = Binder.clearCallingIdentity();
2681 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002682 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002683 if (task == null) {
2684 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2685 return;
2686 }
2687
2688 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2689 + " to stackId=" + stackId + " toTop=" + toTop);
2690
Louis Chang149d5c82019-12-30 09:47:39 +08002691 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002692 if (stack == null) {
2693 throw new IllegalStateException(
2694 "moveTaskToStack: No stack for stackId=" + stackId);
2695 }
2696 if (!stack.isActivityTypeStandardOrUndefined()) {
2697 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2698 + taskId + " to stack " + stackId);
2699 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002700 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2701 "moveTaskToStack");
2702 } finally {
2703 Binder.restoreCallingIdentity(ident);
2704 }
2705 }
2706 }
2707
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002708 /**
2709 * Moves the specified task to the primary-split-screen stack.
2710 *
2711 * @param taskId Id of task to move.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002712 * @param toTop If the task and stack should be moved to the top.
Winson Chung7ccc6812020-01-23 16:15:10 -08002713 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002714 */
2715 @Override
Evan Rosky73a7fe92019-11-18 18:28:01 -08002716 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002717 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002718 "setTaskWindowingModeSplitScreenPrimary()");
2719 synchronized (mGlobalLock) {
2720 final long ident = Binder.clearCallingIdentity();
2721 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002722 return setTaskWindowingModeSplitScreen(taskId, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY,
2723 toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002724 } finally {
2725 Binder.restoreCallingIdentity(ident);
2726 }
2727 }
2728 }
2729
2730 /**
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002731 * Moves the specified task into a split-screen tile.
2732 */
2733 private boolean setTaskWindowingModeSplitScreen(int taskId, int windowingMode, boolean toTop) {
2734 if (!WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2735 throw new IllegalArgumentException("Calling setTaskWindowingModeSplitScreen with non"
2736 + "split-screen mode: " + windowingMode);
2737 }
2738 if (isInLockTaskMode()) {
2739 Slog.w(TAG, "setTaskWindowingModeSplitScreen: Is in lock task mode="
2740 + getLockTaskModeState());
2741 return false;
2742 }
2743
2744 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2745 MATCH_TASK_IN_STACKS_ONLY);
2746 if (task == null) {
2747 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2748 return false;
2749 }
2750 if (!task.isActivityTypeStandardOrUndefined()) {
2751 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2752 + " non-standard task " + taskId + " to split-screen windowing mode");
2753 }
Wale Ogunwale0d465192020-01-23 19:14:44 -08002754 if (!task.supportsSplitScreenWindowingMode()) {
2755 return false;
2756 }
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002757
2758 final int prevMode = task.getWindowingMode();
Louis Changa009c762020-02-26 11:21:31 +08002759 moveTaskToSplitScreenPrimaryTask(task, toTop);
Wale Ogunwale0d465192020-01-23 19:14:44 -08002760 return prevMode != task.getWindowingMode();
2761 }
2762
Louis Changa009c762020-02-26 11:21:31 +08002763 void moveTaskToSplitScreenPrimaryTask(Task task, boolean toTop) {
2764 final DisplayContent display = task.getDisplayContent();
2765 final ActivityStack primarySplitTask = display.getRootSplitScreenPrimaryTask();
2766 if (primarySplitTask == null) {
2767 throw new IllegalStateException("Can't enter split without associated organized task");
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002768 }
Louis Changa009c762020-02-26 11:21:31 +08002769
2770 if (toTop) {
2771 display.positionStackAt(POSITION_TOP, primarySplitTask, false /* includingParents */);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002772 }
2773 WindowContainerTransaction wct = new WindowContainerTransaction();
Louis Changa009c762020-02-26 11:21:31 +08002774 wct.reparent(task.getStack().mRemoteToken, primarySplitTask.mRemoteToken, toTop);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07002775 mWindowOrganizerController.applyTransaction(wct);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002776 }
2777
2778 /**
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002779 * Removes stacks in the input windowing modes from the system if they are of activity type
2780 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2781 */
2782 @Override
2783 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002784 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002785 "removeStacksInWindowingModes()");
2786
2787 synchronized (mGlobalLock) {
2788 final long ident = Binder.clearCallingIdentity();
2789 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002790 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002791 } finally {
2792 Binder.restoreCallingIdentity(ident);
2793 }
2794 }
2795 }
2796
2797 @Override
2798 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002799 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002800 "removeStacksWithActivityTypes()");
2801
2802 synchronized (mGlobalLock) {
2803 final long ident = Binder.clearCallingIdentity();
2804 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002805 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002806 } finally {
2807 Binder.restoreCallingIdentity(ident);
2808 }
2809 }
2810 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002811
2812 @Override
2813 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2814 int userId) {
2815 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002816 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2817 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002818 callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002819 synchronized (mGlobalLock) {
Winson Chung66b08f02020-03-03 14:32:35 -08002820 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, userId, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002821 }
2822 }
2823
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002824 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002825 @Override
2826 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002827 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002828 long ident = Binder.clearCallingIdentity();
2829 try {
2830 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002831 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002832 }
2833 } finally {
2834 Binder.restoreCallingIdentity(ident);
2835 }
2836 }
2837
2838 @Override
2839 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002840 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002841 long ident = Binder.clearCallingIdentity();
2842 try {
2843 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002844 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002845 }
2846 } finally {
2847 Binder.restoreCallingIdentity(ident);
2848 }
2849 }
2850
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002851 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002852 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002853 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2854 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2855 long ident = Binder.clearCallingIdentity();
2856 try {
2857 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002858 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002859 }
2860 } finally {
2861 Binder.restoreCallingIdentity(ident);
2862 }
2863 }
2864
2865 @Override
2866 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2867 int displayId) {
2868 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2869 long ident = Binder.clearCallingIdentity();
2870 try {
2871 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002872 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002873 }
2874 } finally {
2875 Binder.restoreCallingIdentity(ident);
2876 }
2877 }
2878
2879 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002881 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002882 final long callingUid = Binder.getCallingUid();
2883 final long origId = Binder.clearCallingIdentity();
2884 try {
2885 synchronized (mGlobalLock) {
2886 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002887 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002888 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2889 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2890 }
2891 } finally {
2892 Binder.restoreCallingIdentity(origId);
2893 }
2894 }
2895
2896 @Override
2897 public void startLockTaskModeByToken(IBinder token) {
2898 synchronized (mGlobalLock) {
2899 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2900 if (r == null) {
2901 return;
2902 }
Louis Changcdec0802019-11-11 11:45:07 +08002903 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002904 }
2905 }
2906
2907 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002908 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002909 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002910 // This makes inner call to look as if it was initiated by system.
2911 long ident = Binder.clearCallingIdentity();
2912 try {
2913 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002914 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002915 MATCH_TASK_IN_STACKS_ONLY);
2916 if (task == null) {
2917 return;
2918 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002919
2920 // When starting lock task mode the stack must be in front and focused
2921 task.getStack().moveToFront("startSystemLockTaskMode");
2922 startLockTaskModeLocked(task, true /* isSystemCaller */);
2923 }
2924 } finally {
2925 Binder.restoreCallingIdentity(ident);
2926 }
2927 }
2928
2929 @Override
2930 public void stopLockTaskModeByToken(IBinder token) {
2931 synchronized (mGlobalLock) {
2932 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2933 if (r == null) {
2934 return;
2935 }
Louis Changcdec0802019-11-11 11:45:07 +08002936 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002937 }
2938 }
2939
2940 /**
2941 * This API should be called by SystemUI only when user perform certain action to dismiss
2942 * lock task mode. We should only dismiss pinned lock task mode in this case.
2943 */
2944 @Override
2945 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002946 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002947 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2948 }
2949
Louis Changcdec0802019-11-11 11:45:07 +08002950 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002951 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2952 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2953 return;
2954 }
2955
Louis Chang149d5c82019-12-30 09:47:39 +08002956 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002957 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002958 throw new IllegalArgumentException("Invalid task, not in foreground");
2959 }
2960
2961 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2962 // system or a specific app.
2963 // * System-initiated requests will only start the pinned mode (screen pinning)
2964 // * App-initiated requests
2965 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2966 // - will start the pinned mode, otherwise
2967 final int callingUid = Binder.getCallingUid();
2968 long ident = Binder.clearCallingIdentity();
2969 try {
2970 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002971 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002972
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002973 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002974 } finally {
2975 Binder.restoreCallingIdentity(ident);
2976 }
2977 }
2978
Louis Changcdec0802019-11-11 11:45:07 +08002979 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002980 final int callingUid = Binder.getCallingUid();
2981 long ident = Binder.clearCallingIdentity();
2982 try {
2983 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002984 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002985 }
2986 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2987 // task and jumping straight into a call in the case of emergency call back.
2988 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2989 if (tm != null) {
2990 tm.showInCallScreen(false);
2991 }
2992 } finally {
2993 Binder.restoreCallingIdentity(ident);
2994 }
2995 }
2996
2997 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002998 public void updateLockTaskPackages(int userId, String[] packages) {
2999 final int callingUid = Binder.getCallingUid();
3000 if (callingUid != 0 && callingUid != SYSTEM_UID) {
3001 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
3002 "updateLockTaskPackages()");
3003 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08003004 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003005 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
3006 + Arrays.toString(packages));
3007 getLockTaskController().updateLockTaskPackages(userId, packages);
3008 }
3009 }
3010
3011 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003012 public boolean isInLockTaskMode() {
3013 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3014 }
3015
3016 @Override
3017 public int getLockTaskModeState() {
3018 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003019 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003020 }
3021 }
3022
3023 @Override
3024 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3025 synchronized (mGlobalLock) {
3026 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3027 if (r != null) {
3028 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003029 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003030 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003031 }
3032 }
3033 }
3034
3035 @Override
3036 public Bundle getActivityOptions(IBinder token) {
3037 final long origId = Binder.clearCallingIdentity();
3038 try {
3039 synchronized (mGlobalLock) {
3040 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3041 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003042 final ActivityOptions activityOptions = r.takeOptionsLocked(
3043 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003044 return activityOptions == null ? null : activityOptions.toBundle();
3045 }
3046 return null;
3047 }
3048 } finally {
3049 Binder.restoreCallingIdentity(origId);
3050 }
3051 }
3052
3053 @Override
3054 public List<IBinder> getAppTasks(String callingPackage) {
3055 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003056 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003057 long ident = Binder.clearCallingIdentity();
3058 try {
3059 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003060 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003061 }
3062 } finally {
3063 Binder.restoreCallingIdentity(ident);
3064 }
3065 }
3066
3067 @Override
3068 public void finishVoiceTask(IVoiceInteractionSession session) {
3069 synchronized (mGlobalLock) {
3070 final long origId = Binder.clearCallingIdentity();
3071 try {
3072 // TODO: VI Consider treating local voice interactions and voice tasks
3073 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003074 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003075 } finally {
3076 Binder.restoreCallingIdentity(origId);
3077 }
3078 }
3079
3080 }
3081
3082 @Override
3083 public boolean isTopOfTask(IBinder token) {
3084 synchronized (mGlobalLock) {
3085 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003086 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003087 }
3088 }
3089
3090 @Override
3091 public void notifyLaunchTaskBehindComplete(IBinder token) {
3092 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3093 }
3094
3095 @Override
3096 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003097 mH.post(() -> {
3098 synchronized (mGlobalLock) {
3099 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003100 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003101 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003102 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003103 } catch (RemoteException e) {
3104 }
3105 }
3106 }
3107
3108 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003109 }
3110
3111 /** Called from an app when assist data is ready. */
3112 @Override
3113 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3114 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003115 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003116 synchronized (pae) {
3117 pae.result = extras;
3118 pae.structure = structure;
3119 pae.content = content;
3120 if (referrer != null) {
3121 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3122 }
3123 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003124 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003125 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003126 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003127 structure.setHomeActivity(pae.isHome);
3128 }
3129 pae.haveResult = true;
3130 pae.notifyAll();
3131 if (pae.intent == null && pae.receiver == null) {
3132 // Caller is just waiting for the result.
3133 return;
3134 }
3135 }
3136 // We are now ready to launch the assist activity.
3137 IAssistDataReceiver sendReceiver = null;
3138 Bundle sendBundle = null;
3139 synchronized (mGlobalLock) {
3140 buildAssistBundleLocked(pae, extras);
3141 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003142 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003143 if (!exists) {
3144 // Timed out.
3145 return;
3146 }
3147
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003148 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003149 // Caller wants result sent back to them.
3150 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003151 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003152 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003153 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3154 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003155 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3156 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3157 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3158 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3159 }
3160 }
3161 if (sendReceiver != null) {
3162 try {
3163 sendReceiver.onHandleAssistData(sendBundle);
3164 } catch (RemoteException e) {
3165 }
3166 return;
3167 }
3168
3169 final long ident = Binder.clearCallingIdentity();
3170 try {
3171 if (TextUtils.equals(pae.intent.getAction(),
3172 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003173 // Start voice interaction through VoiceInteractionManagerService.
3174 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3175 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003176 } else {
3177 pae.intent.replaceExtras(pae.extras);
3178 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3179 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3180 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003181 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003182
3183 try {
3184 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3185 } catch (ActivityNotFoundException e) {
3186 Slog.w(TAG, "No activity to handle assist action.", e);
3187 }
3188 }
3189 } finally {
3190 Binder.restoreCallingIdentity(ident);
3191 }
3192 }
3193
3194 @Override
3195 public int addAppTask(IBinder activityToken, Intent intent,
3196 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3197 final int callingUid = Binder.getCallingUid();
3198 final long callingIdent = Binder.clearCallingIdentity();
3199
3200 try {
3201 synchronized (mGlobalLock) {
3202 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3203 if (r == null) {
3204 throw new IllegalArgumentException("Activity does not exist; token="
3205 + activityToken);
3206 }
3207 ComponentName comp = intent.getComponent();
3208 if (comp == null) {
3209 throw new IllegalArgumentException("Intent " + intent
3210 + " must specify explicit component");
3211 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003212 if (thumbnail.getWidth() != mThumbnailWidth
3213 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003214 throw new IllegalArgumentException("Bad thumbnail size: got "
3215 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003216 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003217 }
3218 if (intent.getSelector() != null) {
3219 intent.setSelector(null);
3220 }
3221 if (intent.getSourceBounds() != null) {
3222 intent.setSourceBounds(null);
3223 }
3224 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3225 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3226 // The caller has added this as an auto-remove task... that makes no
3227 // sense, so turn off auto-remove.
3228 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3229 }
3230 }
3231 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3232 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3233 if (ainfo.applicationInfo.uid != callingUid) {
3234 throw new SecurityException(
3235 "Can't add task for another application: target uid="
3236 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3237 }
3238
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003239 final ActivityStack stack = r.getRootTask();
Wale Ogunwale0d465192020-01-23 19:14:44 -08003240 final Task task = stack.getDisplay().createStack(stack.getWindowingMode(),
Louis Changa009c762020-02-26 11:21:31 +08003241 stack.getActivityType(), !ON_TOP, ainfo, intent,
3242 false /* createdByOrganizer */);
Wale Ogunwale0d465192020-01-23 19:14:44 -08003243
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003244 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003245 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003246 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003247 return INVALID_TASK_ID;
3248 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003249 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003250
3251 // TODO: Send the thumbnail to WM to store it.
3252
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003253 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003254 }
3255 } finally {
3256 Binder.restoreCallingIdentity(callingIdent);
3257 }
3258 }
3259
3260 @Override
3261 public Point getAppTaskThumbnailSize() {
3262 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003263 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003264 }
3265 }
3266
3267 @Override
3268 public void setTaskResizeable(int taskId, int resizeableMode) {
3269 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003270 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003271 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3272 if (task == null) {
3273 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3274 return;
3275 }
3276 task.setResizeMode(resizeableMode);
3277 }
3278 }
3279
3280 @Override
3281 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003282 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003283 long ident = Binder.clearCallingIdentity();
3284 try {
3285 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003286 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003287 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003288 if (task == null) {
3289 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3290 return;
3291 }
3292 // Place the task in the right stack if it isn't there already based on
3293 // the requested bounds.
3294 // The stack transition logic is:
3295 // - a null bounds on a freeform task moves that task to fullscreen
3296 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3297 // that task to freeform
3298 // - otherwise the task is not moved
3299 ActivityStack stack = task.getStack();
3300 if (!task.getWindowConfiguration().canResizeTask()) {
3301 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3302 }
3303 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3304 stack = stack.getDisplay().getOrCreateStack(
3305 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3306 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3307 stack = stack.getDisplay().getOrCreateStack(
3308 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3309 }
3310
3311 // Reparent the task to the right stack if necessary
3312 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3313 if (stack != task.getStack()) {
3314 // Defer resume until the task is resized below
3315 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3316 DEFER_RESUME, "resizeTask");
3317 preserveWindow = false;
3318 }
3319
3320 // After reparenting (which only resizes the task to the stack bounds), resize the
3321 // task to the actual bounds provided
3322 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3323 }
3324 } finally {
3325 Binder.restoreCallingIdentity(ident);
3326 }
3327 }
3328
3329 @Override
3330 public boolean releaseActivityInstance(IBinder token) {
3331 synchronized (mGlobalLock) {
3332 final long origId = Binder.clearCallingIdentity();
3333 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003334 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3335 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003336 return false;
3337 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003338 r.destroyImmediately(true /* removeFromApp */, "app-req");
3339 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003340 } finally {
3341 Binder.restoreCallingIdentity(origId);
3342 }
3343 }
3344 }
3345
3346 @Override
3347 public void releaseSomeActivities(IApplicationThread appInt) {
3348 synchronized (mGlobalLock) {
3349 final long origId = Binder.clearCallingIdentity();
3350 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003351 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003352 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003353 } finally {
3354 Binder.restoreCallingIdentity(origId);
3355 }
3356 }
3357 }
3358
3359 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003360 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003361 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003362 != PackageManager.PERMISSION_GRANTED) {
3363 throw new SecurityException("Requires permission "
3364 + android.Manifest.permission.DEVICE_POWER);
3365 }
3366
3367 synchronized (mGlobalLock) {
3368 long ident = Binder.clearCallingIdentity();
3369 if (mKeyguardShown != keyguardShowing) {
3370 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003371 final Message msg = PooledLambda.obtainMessage(
3372 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3373 keyguardShowing);
3374 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003375 }
3376 try {
wilsonshih177261f2019-02-22 12:02:18 +08003377 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378 } finally {
3379 Binder.restoreCallingIdentity(ident);
3380 }
3381 }
3382
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003383 mH.post(() -> {
3384 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3385 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3386 }
3387 });
3388 }
3389
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003390 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003391 mH.post(() -> {
3392 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3393 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3394 }
3395 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003396 }
3397
3398 @Override
3399 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003400 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3401 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003402
3403 final File passedIconFile = new File(filePath);
3404 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3405 passedIconFile.getName());
3406 if (!legitIconFile.getPath().equals(filePath)
3407 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3408 throw new IllegalArgumentException("Bad file path: " + filePath
3409 + " passed for userId " + userId);
3410 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003411 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 }
3413
3414 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003415 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003416 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003417 synchronized (mGlobalLock) {
3418 final long ident = Binder.clearCallingIdentity();
3419 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003420 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003421 if (stack == null) {
3422 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3423 return;
3424 }
3425 if (!stack.isActivityTypeStandardOrUndefined()) {
3426 throw new IllegalArgumentException(
3427 "Removing non-standard stack is not allowed.");
3428 }
3429 mStackSupervisor.removeStack(stack);
3430 } finally {
3431 Binder.restoreCallingIdentity(ident);
3432 }
3433 }
3434 }
3435
3436 @Override
3437 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003438 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003439
3440 synchronized (mGlobalLock) {
3441 final long ident = Binder.clearCallingIdentity();
3442 try {
3443 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3444 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003445 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003446 } finally {
3447 Binder.restoreCallingIdentity(ident);
3448 }
3449 }
3450 }
3451
3452 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003453 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003454 synchronized (mGlobalLock) {
3455 long ident = Binder.clearCallingIdentity();
3456 try {
3457 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3458 if (r == null) {
3459 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003460 "toggleFreeformWindowingMode: No activity record matching token="
3461 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003462 }
3463
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003464 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003465 if (stack == null) {
3466 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3467 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003468 }
3469
Yunfan Chend967af82019-01-17 18:30:18 +09003470 if (!stack.inFreeformWindowingMode()
3471 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3472 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3473 + "toggle between fullscreen and freeform.");
3474 }
3475
3476 if (stack.inFreeformWindowingMode()) {
3477 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003478 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003479 throw new IllegalStateException("Size-compat windows are currently not"
3480 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003481 } else if (stack.getParent().inFreeformWindowingMode()) {
3482 // If the window is on a freeform display, set it to undefined. It will be
3483 // resolved to freeform and it can adjust windowing mode when the display mode
3484 // changes in runtime.
3485 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003486 } else {
3487 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3488 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003489 } finally {
3490 Binder.restoreCallingIdentity(ident);
3491 }
3492 }
3493 }
3494
3495 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3496 @Override
3497 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003498 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003499 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003500 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003501 }
3502
3503 /** Unregister a task stack listener so that it stops receiving callbacks. */
3504 @Override
3505 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003506 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003507 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003508 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003509 }
3510
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003511 @Override
3512 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3513 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3514 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3515 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3516 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3517 }
3518
3519 @Override
3520 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3521 IBinder activityToken, int flags) {
3522 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3523 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3524 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3525 }
3526
3527 @Override
3528 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3529 Bundle args) {
3530 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3531 true /* focused */, true /* newSessionId */, userHandle, args,
3532 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3533 }
3534
3535 @Override
3536 public Bundle getAssistContextExtras(int requestType) {
3537 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3538 null, null, true /* focused */, true /* newSessionId */,
3539 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3540 if (pae == null) {
3541 return null;
3542 }
3543 synchronized (pae) {
3544 while (!pae.haveResult) {
3545 try {
3546 pae.wait();
3547 } catch (InterruptedException e) {
3548 }
3549 }
3550 }
3551 synchronized (mGlobalLock) {
3552 buildAssistBundleLocked(pae, pae.result);
3553 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003554 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003555 }
3556 return pae.extras;
3557 }
3558
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003559 /**
3560 * Binder IPC calls go through the public entry point.
3561 * This can be called with or without the global lock held.
3562 */
3563 private static int checkCallingPermission(String permission) {
3564 return checkPermission(
3565 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3566 }
3567
3568 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003569 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003570 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3571 mAmInternal.enforceCallingPermission(permission, func);
3572 }
3573 }
3574
3575 @VisibleForTesting
3576 int checkGetTasksPermission(String permission, int pid, int uid) {
3577 return checkPermission(permission, pid, uid);
3578 }
3579
3580 static int checkPermission(String permission, int pid, int uid) {
3581 if (permission == null) {
3582 return PackageManager.PERMISSION_DENIED;
3583 }
3584 return checkComponentPermission(permission, pid, uid, -1, true);
3585 }
3586
Wale Ogunwale214f3482018-10-04 11:00:47 -07003587 public static int checkComponentPermission(String permission, int pid, int uid,
3588 int owningUid, boolean exported) {
3589 return ActivityManagerService.checkComponentPermission(
3590 permission, pid, uid, owningUid, exported);
3591 }
3592
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003593 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3594 if (getRecentTasks().isCallerRecents(callingUid)) {
3595 // Always allow the recents component to get tasks
3596 return true;
3597 }
3598
3599 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3600 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3601 if (!allowed) {
3602 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3603 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3604 // Temporary compatibility: some existing apps on the system image may
3605 // still be requesting the old permission and not switched to the new
3606 // one; if so, we'll still allow them full access. This means we need
3607 // to see if they are holding the old permission and are a system app.
3608 try {
3609 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3610 allowed = true;
3611 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3612 + " is using old GET_TASKS but privileged; allowing");
3613 }
3614 } catch (RemoteException e) {
3615 }
3616 }
3617 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3618 + " does not hold REAL_GET_TASKS; limiting output");
3619 }
3620 return allowed;
3621 }
3622
Nicholas Sauer0259e532019-08-30 08:24:55 -07003623 boolean isCrossUserAllowed(int pid, int uid) {
3624 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3625 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3626 }
3627
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003628 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3629 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3630 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3631 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003632 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003633 "enqueueAssistContext()");
3634
3635 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08003636 final ActivityStack stack = getTopDisplayFocusedStack();
3637 ActivityRecord activity = stack != null ? stack.getTopNonFinishingActivity() : null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003638 if (activity == null) {
3639 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3640 return null;
3641 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003642 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003643 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3644 return null;
3645 }
3646 if (focused) {
3647 if (activityToken != null) {
3648 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3649 if (activity != caller) {
3650 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3651 + " is not current top " + activity);
3652 return null;
3653 }
3654 }
3655 } else {
3656 activity = ActivityRecord.forTokenLocked(activityToken);
3657 if (activity == null) {
3658 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3659 + " couldn't be found");
3660 return null;
3661 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003662 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003663 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3664 return null;
3665 }
3666 }
3667
3668 PendingAssistExtras pae;
3669 Bundle extras = new Bundle();
3670 if (args != null) {
3671 extras.putAll(args);
3672 }
3673 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003674 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003675
3676 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3677 userHandle);
3678 pae.isHome = activity.isActivityTypeHome();
3679
3680 // Increment the sessionId if necessary
3681 if (newSessionId) {
3682 mViSessionId++;
3683 }
3684 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003685 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3686 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003687 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003688 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003689 } catch (RemoteException e) {
3690 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3691 return null;
3692 }
3693 return pae;
3694 }
3695 }
3696
3697 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3698 if (result != null) {
3699 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3700 }
3701 if (pae.hint != null) {
3702 pae.extras.putBoolean(pae.hint, true);
3703 }
3704 }
3705
3706 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3707 IAssistDataReceiver receiver;
3708 synchronized (mGlobalLock) {
3709 mPendingAssistExtras.remove(pae);
3710 receiver = pae.receiver;
3711 }
3712 if (receiver != null) {
3713 // Caller wants result sent back to them.
3714 Bundle sendBundle = new Bundle();
3715 // At least return the receiver extras
3716 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3717 try {
3718 pae.receiver.onHandleAssistData(sendBundle);
3719 } catch (RemoteException e) {
3720 }
3721 }
3722 }
3723
3724 public class PendingAssistExtras extends Binder implements Runnable {
3725 public final ActivityRecord activity;
3726 public boolean isHome;
3727 public final Bundle extras;
3728 public final Intent intent;
3729 public final String hint;
3730 public final IAssistDataReceiver receiver;
3731 public final int userHandle;
3732 public boolean haveResult = false;
3733 public Bundle result = null;
3734 public AssistStructure structure = null;
3735 public AssistContent content = null;
3736 public Bundle receiverExtras;
3737
3738 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3739 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3740 int _userHandle) {
3741 activity = _activity;
3742 extras = _extras;
3743 intent = _intent;
3744 hint = _hint;
3745 receiver = _receiver;
3746 receiverExtras = _receiverExtras;
3747 userHandle = _userHandle;
3748 }
3749
3750 @Override
3751 public void run() {
3752 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3753 synchronized (this) {
3754 haveResult = true;
3755 notifyAll();
3756 }
3757 pendingAssistExtrasTimedOut(this);
3758 }
3759 }
3760
3761 @Override
3762 public boolean isAssistDataAllowedOnCurrentActivity() {
3763 int userId;
3764 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003765 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003766 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3767 return false;
3768 }
3769
Wale Ogunwale21e06482019-11-18 05:14:15 -08003770 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003771 if (activity == null) {
3772 return false;
3773 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003774 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003775 }
3776 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3777 }
3778
3779 @Override
3780 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3781 long ident = Binder.clearCallingIdentity();
3782 try {
3783 synchronized (mGlobalLock) {
3784 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003785 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003786 if (top != caller) {
3787 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3788 + " is not current top " + top);
3789 return false;
3790 }
3791 if (!top.nowVisible) {
3792 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3793 + " is not visible");
3794 return false;
3795 }
3796 }
3797 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3798 token);
3799 } finally {
3800 Binder.restoreCallingIdentity(ident);
3801 }
3802 }
3803
3804 @Override
3805 public boolean isRootVoiceInteraction(IBinder token) {
3806 synchronized (mGlobalLock) {
3807 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3808 if (r == null) {
3809 return false;
3810 }
3811 return r.rootVoiceInteraction;
3812 }
3813 }
3814
Wale Ogunwalef6733932018-06-27 05:14:34 -07003815 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3816 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3817 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3818 if (activityToCallback == null) return;
3819 activityToCallback.setVoiceSessionLocked(voiceSession);
3820
3821 // Inform the activity
3822 try {
3823 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3824 voiceInteractor);
3825 long token = Binder.clearCallingIdentity();
3826 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003827 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003828 } finally {
3829 Binder.restoreCallingIdentity(token);
3830 }
3831 // TODO: VI Should we cache the activity so that it's easier to find later
3832 // rather than scan through all the stacks and activities?
3833 } catch (RemoteException re) {
3834 activityToCallback.clearVoiceSessionLocked();
3835 // TODO: VI Should this terminate the voice session?
3836 }
3837 }
3838
3839 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3840 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3841 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3842 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3843 boolean wasRunningVoice = mRunningVoice != null;
3844 mRunningVoice = session;
3845 if (!wasRunningVoice) {
3846 mVoiceWakeLock.acquire();
3847 updateSleepIfNeededLocked();
3848 }
3849 }
3850 }
3851
3852 void finishRunningVoiceLocked() {
3853 if (mRunningVoice != null) {
3854 mRunningVoice = null;
3855 mVoiceWakeLock.release();
3856 updateSleepIfNeededLocked();
3857 }
3858 }
3859
3860 @Override
3861 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3862 synchronized (mGlobalLock) {
3863 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3864 if (keepAwake) {
3865 mVoiceWakeLock.acquire();
3866 } else {
3867 mVoiceWakeLock.release();
3868 }
3869 }
3870 }
3871 }
3872
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003873 @Override
3874 public ComponentName getActivityClassForToken(IBinder token) {
3875 synchronized (mGlobalLock) {
3876 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3877 if (r == null) {
3878 return null;
3879 }
3880 return r.intent.getComponent();
3881 }
3882 }
3883
3884 @Override
3885 public String getPackageForToken(IBinder token) {
3886 synchronized (mGlobalLock) {
3887 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3888 if (r == null) {
3889 return null;
3890 }
3891 return r.packageName;
3892 }
3893 }
3894
3895 @Override
3896 public void showLockTaskEscapeMessage(IBinder token) {
3897 synchronized (mGlobalLock) {
3898 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3899 if (r == null) {
3900 return;
3901 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003902 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003903 }
3904 }
3905
3906 @Override
3907 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003908 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003909 final long token = Binder.clearCallingIdentity();
3910 try {
3911 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003912 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003913 }
3914 } finally {
3915 Binder.restoreCallingIdentity(token);
3916 }
3917 }
3918
3919 /**
3920 * Try to place task to provided position. The final position might be different depending on
3921 * current user and stacks state. The task will be moved to target stack if it's currently in
3922 * different stack.
3923 */
3924 @Override
3925 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003926 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003927 synchronized (mGlobalLock) {
3928 long ident = Binder.clearCallingIdentity();
3929 try {
3930 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3931 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003932 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003933 if (task == null) {
3934 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3935 + taskId);
3936 }
3937
Louis Chang149d5c82019-12-30 09:47:39 +08003938 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003939
3940 if (stack == null) {
3941 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3942 + stackId);
3943 }
3944 if (!stack.isActivityTypeStandardOrUndefined()) {
3945 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3946 + " the position of task " + taskId + " in/to non-standard stack");
3947 }
3948
3949 // TODO: Have the callers of this API call a separate reparent method if that is
3950 // what they intended to do vs. having this method also do reparenting.
3951 if (task.getStack() == stack) {
3952 // Change position in current stack.
3953 stack.positionChildAt(task, position);
3954 } else {
3955 // Reparent to new stack.
3956 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3957 !DEFER_RESUME, "positionTaskInStack");
3958 }
3959 } finally {
3960 Binder.restoreCallingIdentity(ident);
3961 }
3962 }
3963 }
3964
3965 @Override
3966 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3967 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3968 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003969 + Arrays.toString(horizontalSizeConfiguration) + " "
3970 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003971 synchronized (mGlobalLock) {
3972 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3973 if (record == null) {
3974 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3975 + "found for: " + token);
3976 }
3977 record.setSizeConfigurations(horizontalSizeConfiguration,
3978 verticalSizeConfigurations, smallestSizeConfigurations);
3979 }
3980 }
3981
3982 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003983 * Dismisses Pip
3984 * @param animate True if the dismissal should be animated.
3985 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3986 * default animation duration should be used.
3987 */
3988 @Override
3989 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003990 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003991 final long ident = Binder.clearCallingIdentity();
3992 try {
3993 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003994 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08003995 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003996 if (stack == null) {
3997 Slog.w(TAG, "dismissPip: pinned stack not found.");
3998 return;
3999 }
4000 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4001 throw new IllegalArgumentException("Stack: " + stack
4002 + " doesn't support animated resize.");
4003 }
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004004 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004005 }
4006 } finally {
4007 Binder.restoreCallingIdentity(ident);
4008 }
4009 }
4010
4011 @Override
4012 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004013 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004014 synchronized (mGlobalLock) {
4015 mSuppressResizeConfigChanges = suppress;
4016 }
4017 }
4018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004019 @Override
4020 // TODO: API should just be about changing windowing modes...
4021 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004022 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004023 "moveTasksToFullscreenStack()");
4024 synchronized (mGlobalLock) {
4025 final long origId = Binder.clearCallingIdentity();
4026 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004027 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004028 if (stack != null){
4029 if (!stack.isActivityTypeStandardOrUndefined()) {
4030 throw new IllegalArgumentException(
4031 "You can't move tasks from non-standard stacks.");
4032 }
4033 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4034 }
4035 } finally {
4036 Binder.restoreCallingIdentity(origId);
4037 }
4038 }
4039 }
4040
4041 /**
4042 * Moves the top activity in the input stackId to the pinned stack.
4043 *
4044 * @param stackId Id of stack to move the top activity to pinned stack.
4045 * @param bounds Bounds to use for pinned stack.
4046 *
4047 * @return True if the top activity of the input stack was successfully moved to the pinned
4048 * stack.
4049 */
4050 @Override
4051 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004052 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004053 "moveTopActivityToPinnedStack()");
4054 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004055 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004056 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4057 + "Device doesn't support picture-in-picture mode");
4058 }
4059
4060 long ident = Binder.clearCallingIdentity();
4061 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004062 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004063 } finally {
4064 Binder.restoreCallingIdentity(ident);
4065 }
4066 }
4067 }
4068
4069 @Override
4070 public boolean isInMultiWindowMode(IBinder token) {
4071 final long origId = Binder.clearCallingIdentity();
4072 try {
4073 synchronized (mGlobalLock) {
4074 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4075 if (r == null) {
4076 return false;
4077 }
4078 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4079 return r.inMultiWindowMode();
4080 }
4081 } finally {
4082 Binder.restoreCallingIdentity(origId);
4083 }
4084 }
4085
4086 @Override
4087 public boolean isInPictureInPictureMode(IBinder token) {
4088 final long origId = Binder.clearCallingIdentity();
4089 try {
4090 synchronized (mGlobalLock) {
4091 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4092 }
4093 } finally {
4094 Binder.restoreCallingIdentity(origId);
4095 }
4096 }
4097
4098 private boolean isInPictureInPictureMode(ActivityRecord r) {
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004099 return r != null
4100 && r.getRootTask() != null
4101 && r.inPinnedWindowingMode()
4102 && r.getRootTask().isInStackLocked(r) != null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004103 }
4104
4105 @Override
4106 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4107 final long origId = Binder.clearCallingIdentity();
4108 try {
4109 synchronized (mGlobalLock) {
4110 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4111 "enterPictureInPictureMode", token, params);
4112
4113 // If the activity is already in picture in picture mode, then just return early
4114 if (isInPictureInPictureMode(r)) {
4115 return true;
4116 }
4117
4118 // Activity supports picture-in-picture, now check that we can enter PiP at this
4119 // point, if it is
4120 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4121 false /* beforeStopping */)) {
4122 return false;
4123 }
4124
4125 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004126 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004127 if (r.getParent() == null) {
4128 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4129 return;
4130 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004131 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004132 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004133 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4134 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4135 // Adjust the source bounds by the insets for the transition down
4136 final Rect sourceBounds = new Rect(
4137 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004138 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004139 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004140 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004141 stack.setPictureInPictureAspectRatio(aspectRatio);
4142 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004143 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4144 r.info.applicationInfo.uid, r.shortComponentName,
4145 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004146 logPictureInPictureArgs(params);
4147 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004148 };
4149
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004150 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004151 // If the keyguard is showing or occluded, then try and dismiss it before
4152 // entering picture-in-picture (this will prompt the user to authenticate if the
4153 // device is currently locked).
4154 dismissKeyguard(token, new KeyguardDismissCallback() {
4155 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004156 public void onDismissSucceeded() {
4157 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004158 }
4159 }, null /* message */);
4160 } else {
4161 // Enter picture in picture immediately otherwise
4162 enterPipRunnable.run();
4163 }
4164 return true;
4165 }
4166 } finally {
4167 Binder.restoreCallingIdentity(origId);
4168 }
4169 }
4170
4171 @Override
4172 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4173 final long origId = Binder.clearCallingIdentity();
4174 try {
4175 synchronized (mGlobalLock) {
4176 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4177 "setPictureInPictureParams", token, params);
4178
4179 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004180 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004181 if (r.inPinnedWindowingMode()) {
4182 // If the activity is already in picture-in-picture, update the pinned stack now
4183 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4184 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004185 final ActivityStack stack = r.getRootTask();
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004186 stack.setPictureInPictureAspectRatio(
4187 r.pictureInPictureArgs.getAspectRatio());
4188 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004189 }
4190 logPictureInPictureArgs(params);
4191 }
4192 } finally {
4193 Binder.restoreCallingIdentity(origId);
4194 }
4195 }
4196
4197 @Override
4198 public int getMaxNumPictureInPictureActions(IBinder token) {
4199 // Currently, this is a static constant, but later, we may change this to be dependent on
4200 // the context of the activity
4201 return 3;
4202 }
4203
4204 private void logPictureInPictureArgs(PictureInPictureParams params) {
4205 if (params.hasSetActions()) {
4206 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4207 params.getActions().size());
4208 }
4209 if (params.hasSetAspectRatio()) {
4210 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4211 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4212 MetricsLogger.action(lm);
4213 }
4214 }
4215
4216 /**
4217 * Checks the state of the system and the activity associated with the given {@param token} to
4218 * verify that picture-in-picture is supported for that activity.
4219 *
4220 * @return the activity record for the given {@param token} if all the checks pass.
4221 */
4222 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4223 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004224 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004225 throw new IllegalStateException(caller
4226 + ": Device doesn't support picture-in-picture mode.");
4227 }
4228
4229 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4230 if (r == null) {
4231 throw new IllegalStateException(caller
4232 + ": Can't find activity for token=" + token);
4233 }
4234
4235 if (!r.supportsPictureInPicture()) {
4236 throw new IllegalStateException(caller
4237 + ": Current activity does not support picture-in-picture.");
4238 }
4239
4240 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004241 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004242 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004243 final float minAspectRatio = mContext.getResources().getFloat(
4244 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4245 final float maxAspectRatio = mContext.getResources().getFloat(
4246 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4247 throw new IllegalArgumentException(String.format(caller
4248 + ": Aspect ratio is too extreme (must be between %f and %f).",
4249 minAspectRatio, maxAspectRatio));
4250 }
4251
4252 // Truncate the number of actions if necessary
4253 params.truncateActions(getMaxNumPictureInPictureActions(token));
4254
4255 return r;
4256 }
4257
4258 @Override
4259 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004260 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004261 synchronized (mGlobalLock) {
4262 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4263 if (r == null) {
4264 throw new IllegalArgumentException("Activity does not exist; token="
4265 + activityToken);
4266 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004267 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004268 }
4269 }
4270
Evan Rosky73a7fe92019-11-18 18:28:01 -08004271 // TODO(b/149338177): remove when CTS no-longer requires it
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004272 @Override
4273 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4274 Rect tempDockedTaskInsetBounds,
4275 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004276 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004277 long ident = Binder.clearCallingIdentity();
4278 try {
4279 synchronized (mGlobalLock) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08004280 final DisplayContent dc = mRootWindowContainer.getDefaultDisplay();
Louis Changa009c762020-02-26 11:21:31 +08004281 final Task primary = dc.getRootSplitScreenPrimaryTask();
4282 final Task secondary = dc.getTask(t -> t.mCreatedByOrganizer && t.isRootTask()
4283 && t.inSplitScreenSecondaryWindowingMode());
Evan Rosky73a7fe92019-11-18 18:28:01 -08004284 if (primary == null || secondary == null) {
4285 return;
4286 }
4287 final WindowContainerTransaction wct = new WindowContainerTransaction();
4288 final Rect primaryRect =
4289 tempDockedTaskInsetBounds != null ? tempDockedTaskInsetBounds
4290 : (tempDockedTaskBounds != null ? tempDockedTaskBounds
4291 : dockedBounds);
4292 wct.setBounds(primary.mRemoteToken, primaryRect);
4293 Rect otherRect = tempOtherTaskInsetBounds != null ? tempOtherTaskInsetBounds
4294 : tempOtherTaskBounds;
4295 if (otherRect == null) {
4296 // Temporary estimation... again this is just for tests.
4297 otherRect = new Rect(secondary.getBounds());
4298 if (dc.getBounds().width() > dc.getBounds().height()) {
4299 otherRect.left = primaryRect.right + 6;
4300 } else {
4301 otherRect.top = primaryRect.bottom + 6;
4302 }
4303 }
4304 wct.setBounds(secondary.mRemoteToken, otherRect);
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004305 mWindowOrganizerController.applyTransaction(wct);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004306 }
4307 } finally {
4308 Binder.restoreCallingIdentity(ident);
4309 }
4310 }
4311
4312 @Override
4313 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004314 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004315 final long ident = Binder.clearCallingIdentity();
4316 try {
4317 synchronized (mGlobalLock) {
4318 mStackSupervisor.setSplitScreenResizing(resizing);
4319 }
4320 } finally {
4321 Binder.restoreCallingIdentity(ident);
4322 }
4323 }
4324
Evan Rosky0037e5f2019-11-05 10:26:24 -08004325 @Override
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004326 public IWindowOrganizerController getWindowOrganizerController() {
Evan Rosky0037e5f2019-11-05 10:26:24 -08004327 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale568f9f412020-03-21 22:27:35 -07004328 "getWindowOrganizerController()");
4329 return mWindowOrganizerController;
Evan Rosky0037e5f2019-11-05 10:26:24 -08004330 }
4331
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004332 /**
4333 * Check that we have the features required for VR-related API calls, and throw an exception if
4334 * not.
4335 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004336 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004337 if (!mContext.getPackageManager().hasSystemFeature(
4338 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4339 throw new UnsupportedOperationException("VR mode not supported on this device!");
4340 }
4341 }
4342
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004343 @Override
4344 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004345 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004346
4347 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4348
4349 ActivityRecord r;
4350 synchronized (mGlobalLock) {
4351 r = ActivityRecord.isInStackLocked(token);
4352 }
4353
4354 if (r == null) {
4355 throw new IllegalArgumentException();
4356 }
4357
4358 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004359 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004360 VrManagerInternal.NO_ERROR) {
4361 return err;
4362 }
4363
4364 // Clear the binder calling uid since this path may call moveToTask().
4365 final long callingId = Binder.clearCallingIdentity();
4366 try {
4367 synchronized (mGlobalLock) {
4368 r.requestedVrComponent = (enabled) ? packageName : null;
4369
4370 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004371 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004372 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373 }
4374 return 0;
4375 }
4376 } finally {
4377 Binder.restoreCallingIdentity(callingId);
4378 }
4379 }
4380
4381 @Override
4382 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4383 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4384 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004385 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4387 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4388 }
Louis Changcdec0802019-11-11 11:45:07 +08004389 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004390 || activity.voiceSession != null) {
4391 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4392 return;
4393 }
4394 if (activity.pendingVoiceInteractionStart) {
4395 Slog.w(TAG, "Pending start of voice interaction already.");
4396 return;
4397 }
4398 activity.pendingVoiceInteractionStart = true;
4399 }
4400 LocalServices.getService(VoiceInteractionManagerInternal.class)
4401 .startLocalVoiceInteraction(callingActivity, options);
4402 }
4403
4404 @Override
4405 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4406 LocalServices.getService(VoiceInteractionManagerInternal.class)
4407 .stopLocalVoiceInteraction(callingActivity);
4408 }
4409
4410 @Override
4411 public boolean supportsLocalVoiceInteraction() {
4412 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4413 .supportsLocalVoiceInteraction();
4414 }
4415
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004416 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004417 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004418 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004419
4420 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004421 if (mWindowManager == null) {
4422 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4423 return false;
4424 }
4425
4426 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004427 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004428 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004429 }
4430
Riddle Hsua0022cd2019-09-09 21:12:41 +08004431 mH.sendMessage(PooledLambda.obtainMessage(
4432 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4433 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004434
4435 final long origId = Binder.clearCallingIdentity();
4436 try {
4437 if (values != null) {
4438 Settings.System.clearConfiguration(values);
4439 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004440 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004441 UserHandle.USER_NULL, false /* deferResume */,
4442 mTmpUpdateConfigurationResult);
4443 return mTmpUpdateConfigurationResult.changes != 0;
4444 } finally {
4445 Binder.restoreCallingIdentity(origId);
4446 }
4447 }
4448 }
4449
4450 @Override
4451 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4452 CharSequence message) {
4453 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004454 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004455 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4456 }
4457 final long callingId = Binder.clearCallingIdentity();
4458 try {
4459 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004460 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004461 }
4462 } finally {
4463 Binder.restoreCallingIdentity(callingId);
4464 }
4465 }
4466
4467 @Override
4468 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004469 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004470 "cancelTaskWindowTransition()");
4471 final long ident = Binder.clearCallingIdentity();
4472 try {
4473 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004474 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004475 MATCH_TASK_IN_STACKS_ONLY);
4476 if (task == null) {
4477 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4478 return;
4479 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004480 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004481 }
4482 } finally {
4483 Binder.restoreCallingIdentity(ident);
4484 }
4485 }
4486
4487 @Override
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004488 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004489 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004490 final long ident = Binder.clearCallingIdentity();
4491 try {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004492 return getTaskSnapshot(taskId, isLowResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004493 } finally {
4494 Binder.restoreCallingIdentity(ident);
4495 }
4496 }
4497
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004498 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004499 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004500 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004501 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004502 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004503 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4504 if (task == null) {
4505 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4506 return null;
4507 }
4508 }
4509 // Don't call this while holding the lock as this operation might hit the disk.
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004510 return task.getSnapshot(isLowResolution, restoreFromDisk);
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004511 }
4512
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004513 @Override
4514 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4515 synchronized (mGlobalLock) {
4516 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4517 if (r == null) {
4518 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4519 + token);
4520 return;
4521 }
4522 final long origId = Binder.clearCallingIdentity();
4523 try {
4524 r.setDisablePreviewScreenshots(disable);
4525 } finally {
4526 Binder.restoreCallingIdentity(origId);
4527 }
4528 }
4529 }
4530
Riddle Hsu440f88b2019-11-06 22:17:35 +08004531 @Override
4532 public void invalidateHomeTaskSnapshot(IBinder token) {
4533 synchronized (mGlobalLock) {
4534 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4535 if (r == null || !r.isActivityTypeHome()) {
4536 return;
4537 }
4538 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4539 }
4540 }
4541
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004542 /** Return the user id of the last resumed activity. */
4543 @Override
4544 public @UserIdInt
4545 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004546 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004547 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4548 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004549 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004550 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004551 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004552 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004553 }
4554 }
4555
4556 @Override
4557 public void updateLockTaskFeatures(int userId, int flags) {
4558 final int callingUid = Binder.getCallingUid();
4559 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004560 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004561 "updateLockTaskFeatures()");
4562 }
4563 synchronized (mGlobalLock) {
4564 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4565 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004566 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004567 }
4568 }
4569
4570 @Override
4571 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4572 synchronized (mGlobalLock) {
4573 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4574 if (r == null) {
4575 return;
4576 }
4577 final long origId = Binder.clearCallingIdentity();
4578 try {
4579 r.setShowWhenLocked(showWhenLocked);
4580 } finally {
4581 Binder.restoreCallingIdentity(origId);
4582 }
4583 }
4584 }
4585
4586 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004587 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4588 synchronized (mGlobalLock) {
4589 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4590 if (r == null) {
4591 return;
4592 }
4593 final long origId = Binder.clearCallingIdentity();
4594 try {
4595 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4596 } finally {
4597 Binder.restoreCallingIdentity(origId);
4598 }
4599 }
4600 }
4601
4602 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004603 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4604 synchronized (mGlobalLock) {
4605 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4606 if (r == null) {
4607 return;
4608 }
4609 final long origId = Binder.clearCallingIdentity();
4610 try {
4611 r.setTurnScreenOn(turnScreenOn);
4612 } finally {
4613 Binder.restoreCallingIdentity(origId);
4614 }
4615 }
4616 }
4617
4618 @Override
4619 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004620 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004621 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004622 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004623 synchronized (mGlobalLock) {
4624 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4625 if (r == null) {
4626 return;
4627 }
4628 final long origId = Binder.clearCallingIdentity();
4629 try {
4630 r.registerRemoteAnimations(definition);
4631 } finally {
4632 Binder.restoreCallingIdentity(origId);
4633 }
4634 }
4635 }
4636
4637 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004638 public void unregisterRemoteAnimations(IBinder token) {
4639 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4640 "unregisterRemoteAnimations");
4641 synchronized (mGlobalLock) {
4642 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4643 if (r == null) {
4644 return;
4645 }
4646 final long origId = Binder.clearCallingIdentity();
4647 try {
4648 r.unregisterRemoteAnimations();
4649 } finally {
4650 Binder.restoreCallingIdentity(origId);
4651 }
4652 }
4653 }
4654
4655 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004656 public void registerRemoteAnimationForNextActivityStart(String packageName,
4657 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004658 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004659 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004660 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004661 synchronized (mGlobalLock) {
4662 final long origId = Binder.clearCallingIdentity();
4663 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004664 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004665 packageName, adapter);
4666 } finally {
4667 Binder.restoreCallingIdentity(origId);
4668 }
4669 }
4670 }
4671
Evan Rosky966759f2019-01-15 10:33:58 -08004672 @Override
4673 public void registerRemoteAnimationsForDisplay(int displayId,
4674 RemoteAnimationDefinition definition) {
4675 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4676 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004677 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004678 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004679 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004680 if (display == null) {
4681 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4682 return;
4683 }
4684 final long origId = Binder.clearCallingIdentity();
4685 try {
4686 display.mDisplayContent.registerRemoteAnimations(definition);
4687 } finally {
4688 Binder.restoreCallingIdentity(origId);
4689 }
4690 }
4691 }
4692
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004693 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4694 @Override
4695 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4696 synchronized (mGlobalLock) {
4697 final long origId = Binder.clearCallingIdentity();
4698 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004699 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004700 } finally {
4701 Binder.restoreCallingIdentity(origId);
4702 }
4703 }
4704 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004705
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004706 @Override
4707 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004708 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004709 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004710 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004711 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004712 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004713 }
4714 }
4715
4716 @Override
4717 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004718 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004719 != PERMISSION_GRANTED) {
4720 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4721 + Binder.getCallingPid()
4722 + ", uid=" + Binder.getCallingUid()
4723 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4724 Slog.w(TAG, msg);
4725 throw new SecurityException(msg);
4726 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004727 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004728 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004729 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004730 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004731 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004732 }
4733 }
4734
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004735 @Override
4736 public void stopAppSwitches() {
4737 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4738 synchronized (mGlobalLock) {
4739 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004740 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004741 mDidAppSwitch = false;
4742 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4743 }
4744 }
4745
4746 @Override
4747 public void resumeAppSwitches() {
4748 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4749 synchronized (mGlobalLock) {
4750 // Note that we don't execute any pending app switches... we will
4751 // let those wait until either the timeout, or the next start
4752 // activity request.
4753 mAppSwitchesAllowedTime = 0;
4754 }
4755 }
4756
Ricky Wai906af482019-06-03 17:25:28 +01004757 long getLastStopAppSwitchesTime() {
4758 return mLastStopAppSwitchesTime;
4759 }
4760
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004761 void onStartActivitySetDidAppSwitch() {
4762 if (mDidAppSwitch) {
4763 // This is the second allowed switch since we stopped switches, so now just generally
4764 // allow switches. Use case:
4765 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4766 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4767 // anyone to switch again).
4768 mAppSwitchesAllowedTime = 0;
4769 } else {
4770 mDidAppSwitch = true;
4771 }
4772 }
4773
4774 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004775 boolean shouldDisableNonVrUiLocked() {
4776 return mVrController.shouldDisableNonVrUiLocked();
4777 }
4778
Wale Ogunwale53783742018-09-16 10:21:51 -07004779 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004780 // 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 +00004781 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004782 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004783 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4784 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004785 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004786 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004787 }
4788 mH.post(() -> {
4789 if (!mVrController.onVrModeChanged(r)) {
4790 return;
4791 }
4792 synchronized (mGlobalLock) {
4793 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4794 mWindowManager.disableNonVrUi(disableNonVrUi);
4795 if (disableNonVrUi) {
4796 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4797 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004798 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004799 }
4800 }
4801 });
4802 }
4803
Wale Ogunwale53783742018-09-16 10:21:51 -07004804 @Override
4805 public int getPackageScreenCompatMode(String packageName) {
4806 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4807 synchronized (mGlobalLock) {
4808 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4809 }
4810 }
4811
4812 @Override
4813 public void setPackageScreenCompatMode(String packageName, int mode) {
4814 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4815 "setPackageScreenCompatMode");
4816 synchronized (mGlobalLock) {
4817 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4818 }
4819 }
4820
4821 @Override
4822 public boolean getPackageAskScreenCompat(String packageName) {
4823 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4824 synchronized (mGlobalLock) {
4825 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4826 }
4827 }
4828
4829 @Override
4830 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4831 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4832 "setPackageAskScreenCompat");
4833 synchronized (mGlobalLock) {
4834 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4835 }
4836 }
4837
Wale Ogunwale64258362018-10-16 15:13:37 -07004838 public static String relaunchReasonToString(int relaunchReason) {
4839 switch (relaunchReason) {
4840 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4841 return "window_resize";
4842 case RELAUNCH_REASON_FREE_RESIZE:
4843 return "free_resize";
4844 default:
4845 return null;
4846 }
4847 }
4848
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004849 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004850 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004851 }
4852
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004853 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004854 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004855 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4856 }
4857
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004858 boolean isKeyguardLocked() {
4859 return mKeyguardController.isKeyguardLocked();
4860 }
4861
Garfield Tan01548632018-11-27 10:15:48 -08004862 /**
4863 * Clears launch params for the given package.
4864 * @param packageNames the names of the packages of which the launch params are to be cleared
4865 */
4866 @Override
4867 public void clearLaunchParamsForPackages(List<String> packageNames) {
4868 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4869 "clearLaunchParamsForPackages");
4870 synchronized (mGlobalLock) {
4871 for (int i = 0; i < packageNames.size(); ++i) {
4872 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4873 }
4874 }
4875 }
4876
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004877 /**
4878 * Makes the display with the given id a single task instance display. I.e the display can only
4879 * contain one task.
4880 */
4881 @Override
4882 public void setDisplayToSingleTaskInstance(int displayId) {
4883 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4884 "setDisplayToSingleTaskInstance");
4885 final long origId = Binder.clearCallingIdentity();
4886 try {
Louis Chang677921f2019-12-06 16:44:24 +08004887 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004888 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004889 if (display != null) {
4890 display.setDisplayToSingleTaskInstance();
4891 }
4892 } finally {
4893 Binder.restoreCallingIdentity(origId);
4894 }
4895 }
4896
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004897 /**
4898 * Requests that an activity should enter picture-in-picture mode if possible.
4899 */
4900 @Override
4901 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4902 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4903 "requestPictureInPictureMode");
4904 final long origId = Binder.clearCallingIdentity();
4905 try {
4906 synchronized (mGlobalLock) {
4907 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4908 if (activity == null) {
4909 return;
4910 }
4911
4912 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4913 "requestPictureInPictureMode", /* beforeStopping */ false);
4914 if (!canEnterPictureInPicture) {
4915 throw new IllegalStateException(
4916 "Requested PIP on an activity that doesn't support it");
4917 }
4918
4919 try {
4920 final ClientTransaction transaction = ClientTransaction.obtain(
4921 activity.app.getThread(),
4922 activity.token);
4923 transaction.addCallback(EnterPipRequestedItem.obtain());
4924 getLifecycleManager().scheduleTransaction(transaction);
4925 } catch (Exception e) {
4926 Slog.w(TAG, "Failed to send enter pip requested item: "
4927 + activity.intent.getComponent(), e);
4928 }
4929 }
4930 } finally {
4931 Binder.restoreCallingIdentity(origId);
4932 }
4933 }
4934
Wale Ogunwale31913b52018-10-13 08:29:31 -07004935 void dumpLastANRLocked(PrintWriter pw) {
4936 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4937 if (mLastANRState == null) {
4938 pw.println(" <no ANR has occurred since boot>");
4939 } else {
4940 pw.println(mLastANRState);
4941 }
4942 }
4943
4944 void dumpLastANRTracesLocked(PrintWriter pw) {
4945 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4946
4947 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4948 if (ArrayUtils.isEmpty(files)) {
4949 pw.println(" <no ANR has occurred since boot>");
4950 return;
4951 }
4952 // Find the latest file.
4953 File latest = null;
4954 for (File f : files) {
4955 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4956 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004957 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004958 }
4959 pw.print("File: ");
4960 pw.print(latest.getName());
4961 pw.println();
4962 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4963 String line;
4964 while ((line = in.readLine()) != null) {
4965 pw.println(line);
4966 }
4967 } catch (IOException e) {
4968 pw.print("Unable to read: ");
4969 pw.print(e);
4970 pw.println();
4971 }
4972 }
4973
4974 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4975 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4976 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4977 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4978 }
4979
4980 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4981 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4982 pw.println(header);
4983
Louis Chang149d5c82019-12-30 09:47:39 +08004984 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004985 dumpPackage);
4986 boolean needSep = printedAnything;
4987
4988 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08004989 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004990 " ResumedActivity: ");
4991 if (printed) {
4992 printedAnything = true;
4993 needSep = false;
4994 }
4995
4996 if (dumpPackage == null) {
4997 if (needSep) {
4998 pw.println();
4999 }
5000 printedAnything = true;
5001 mStackSupervisor.dump(pw, " ");
5002 }
5003
5004 if (!printedAnything) {
5005 pw.println(" (nothing)");
5006 }
5007 }
5008
5009 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005010 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005011 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005012 pw.println(" ");
5013 }
5014
5015 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5016 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5017 getActivityStartController().dump(pw, "", dumpPackage);
5018 }
5019
5020 /**
5021 * There are three things that cmd can be:
5022 * - a flattened component name that matches an existing activity
5023 * - the cmd arg isn't the flattened component name of an existing activity:
5024 * dump all activity whose component contains the cmd as a substring
5025 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005026 * <p>
5027 * The caller should not hold lock when calling this method because it will wait for the
5028 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005029 *
5030 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5031 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5032 */
5033 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5034 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5035 ArrayList<ActivityRecord> activities;
5036
5037 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005038 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005039 dumpFocusedStackOnly);
5040 }
5041
5042 if (activities.size() <= 0) {
5043 return false;
5044 }
5045
5046 String[] newArgs = new String[args.length - opti];
5047 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5048
Louis Changcdec0802019-11-11 11:45:07 +08005049 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005050 boolean needSep = false;
5051 for (int i = activities.size() - 1; i >= 0; i--) {
5052 ActivityRecord r = activities.get(i);
5053 if (needSep) {
5054 pw.println();
5055 }
5056 needSep = true;
5057 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005058 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005059 if (lastTask != task) {
5060 lastTask = task;
5061 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005062 pw.print(" id="); pw.print(lastTask.mTaskId);
5063 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005064 if (dumpAll) {
5065 lastTask.dump(pw, " ");
5066 }
5067 }
5068 }
5069 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5070 }
5071 return true;
5072 }
5073
5074 /**
5075 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5076 * there is a thread associated with the activity.
5077 */
5078 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5079 final ActivityRecord r, String[] args, boolean dumpAll) {
5080 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005081 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005082 synchronized (mGlobalLock) {
5083 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5084 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5085 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005086 if (r.hasProcess()) {
5087 pw.println(r.app.getPid());
5088 appThread = r.app.getThread();
5089 } else {
5090 pw.println("(not running)");
5091 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005092 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005093 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005094 }
5095 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005096 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005097 // flush anything that is already in the PrintWriter since the thread is going
5098 // to write to the file descriptor directly
5099 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005100 try (TransferPipe tp = new TransferPipe()) {
5101 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5102 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005103 } catch (IOException e) {
5104 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5105 } catch (RemoteException e) {
5106 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5107 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005108 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005109 }
5110
sanryhuang498e77e2018-12-06 14:57:01 +08005111 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5112 boolean testPssMode) {
5113 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5114 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5115 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005116 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005117 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5118 st.toString());
5119 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005120 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5121 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5122 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005123 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5124 testPssMode);
5125 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005126 }
5127
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005128 int getCurrentUserId() {
5129 return mAmInternal.getCurrentUserId();
5130 }
5131
5132 private void enforceNotIsolatedCaller(String caller) {
5133 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5134 throw new SecurityException("Isolated process not allowed to call " + caller);
5135 }
5136 }
5137
Wale Ogunwalef6733932018-06-27 05:14:34 -07005138 public Configuration getConfiguration() {
5139 Configuration ci;
5140 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005141 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005142 ci.userSetLocale = false;
5143 }
5144 return ci;
5145 }
5146
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005147 /**
5148 * Current global configuration information. Contains general settings for the entire system,
5149 * also corresponds to the merged configuration of the default display.
5150 */
5151 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005152 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005153 // while initializing process record for system, see {@link
5154 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005155 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005156 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005157 }
5158
5159 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5160 boolean initLocale) {
5161 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5162 }
5163
5164 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5165 boolean initLocale, boolean deferResume) {
5166 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5167 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5168 UserHandle.USER_NULL, deferResume);
5169 }
5170
Wale Ogunwale59507092018-10-29 09:00:30 -07005171 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005172 final long origId = Binder.clearCallingIdentity();
5173 try {
5174 synchronized (mGlobalLock) {
5175 updateConfigurationLocked(values, null, false, true, userId,
5176 false /* deferResume */);
5177 }
5178 } finally {
5179 Binder.restoreCallingIdentity(origId);
5180 }
5181 }
5182
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005183 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5184 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5185 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5186 deferResume, null /* result */);
5187 }
5188
5189 /**
5190 * Do either or both things: (1) change the current configuration, and (2)
5191 * make sure the given activity is running with the (now) current
5192 * configuration. Returns true if the activity has been left running, or
5193 * false if <var>starting</var> is being destroyed to match the new
5194 * configuration.
5195 *
5196 * @param userId is only used when persistent parameter is set to true to persist configuration
5197 * for that particular user
5198 */
5199 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5200 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5201 ActivityTaskManagerService.UpdateConfigurationResult result) {
5202 int changes = 0;
5203 boolean kept = true;
5204
Riddle Hsua0022cd2019-09-09 21:12:41 +08005205 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005206 try {
5207 if (values != null) {
5208 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5209 deferResume);
5210 }
5211
5212 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5213 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005214 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005215 }
5216
5217 if (result != null) {
5218 result.changes = changes;
5219 result.activityRelaunched = !kept;
5220 }
5221 return kept;
5222 }
5223
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005224 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005225 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005226 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005227
Louis Chang677921f2019-12-06 16:44:24 +08005228 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005229 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005230
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005231 mTempConfig.setTo(getGlobalConfiguration());
5232 final int changes = mTempConfig.updateFrom(values);
5233 if (changes == 0) {
5234 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5235 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5236 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5237 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005238 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005239 return 0;
5240 }
5241
5242 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5243 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005244 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005245 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005246 values.colorMode,
5247 values.densityDpi,
5248 values.fontScale,
5249 values.hardKeyboardHidden,
5250 values.keyboard,
5251 values.keyboardHidden,
5252 values.mcc,
5253 values.mnc,
5254 values.navigation,
5255 values.navigationHidden,
5256 values.orientation,
5257 values.screenHeightDp,
5258 values.screenLayout,
5259 values.screenWidthDp,
5260 values.smallestScreenWidthDp,
5261 values.touchscreen,
5262 values.uiMode);
5263
5264
5265 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5266 final LocaleList locales = values.getLocales();
5267 int bestLocaleIndex = 0;
5268 if (locales.size() > 1) {
5269 if (mSupportedSystemLocales == null) {
5270 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5271 }
5272 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5273 }
5274 SystemProperties.set("persist.sys.locale",
5275 locales.get(bestLocaleIndex).toLanguageTag());
5276 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005277
5278 final Message m = PooledLambda.obtainMessage(
5279 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5280 locales.get(bestLocaleIndex));
5281 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005282 }
5283
Yunfan Chen75157d72018-07-27 14:47:21 +09005284 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005285
5286 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005287 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005288
5289 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5290 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005291 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005292
5293 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005294 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005295
5296 AttributeCache ac = AttributeCache.instance();
5297 if (ac != null) {
5298 ac.updateConfiguration(mTempConfig);
5299 }
5300
5301 // Make sure all resources in our process are updated right now, so that anyone who is going
5302 // to retrieve resource values after we return will be sure to get the new ones. This is
5303 // especially important during boot, where the first config change needs to guarantee all
5304 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005305 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005306
5307 // We need another copy of global config because we're scheduling some calls instead of
5308 // running them in place. We need to be sure that object we send will be handled unchanged.
5309 final Configuration configCopy = new Configuration(mTempConfig);
5310 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005311 final Message msg = PooledLambda.obtainMessage(
5312 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5313 this, userId, configCopy);
5314 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005315 }
5316
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005317 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5318 for (int i = pidMap.size() - 1; i >= 0; i--) {
5319 final int pid = pidMap.keyAt(i);
5320 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005321 if (DEBUG_CONFIGURATION) {
5322 Slog.v(TAG_CONFIGURATION, "Update process config of "
5323 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005324 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005325 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005326 }
5327
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005328 final Message msg = PooledLambda.obtainMessage(
5329 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5330 mAmInternal, changes, initLocale);
5331 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005332
5333 // Override configuration of the default display duplicates global config, so we need to
5334 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005335 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005336 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005337
5338 return changes;
5339 }
5340
Riddle Hsua0022cd2019-09-09 21:12:41 +08005341 /** @see WindowSurfacePlacer#deferLayout */
5342 void deferWindowLayout() {
5343 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5344 // Reset the reasons at the first entrance because we only care about the changes in the
5345 // deferred scope.
5346 mLayoutReasons = 0;
5347 }
5348
5349 mWindowManager.mWindowPlacerLocked.deferLayout();
5350 }
5351
5352 /** @see WindowSurfacePlacer#continueLayout */
5353 void continueWindowLayout() {
5354 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5355 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5356 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5357 }
5358 }
5359
5360 /**
5361 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5362 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5363 * defer count is gone.
5364 */
5365 void addWindowLayoutReasons(@LayoutReason int reasons) {
5366 mLayoutReasons |= reasons;
5367 }
5368
Wale Ogunwalef6733932018-06-27 05:14:34 -07005369 private void updateEventDispatchingLocked(boolean booted) {
5370 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5371 }
5372
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005373 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5374 final ContentResolver resolver = mContext.getContentResolver();
5375 Settings.System.putConfigurationForUser(resolver, config, userId);
5376 }
5377
5378 private void sendLocaleToMountDaemonMsg(Locale l) {
5379 try {
5380 IBinder service = ServiceManager.getService("mount");
5381 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5382 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5383 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5384 } catch (RemoteException e) {
5385 Log.e(TAG, "Error storing locale for decryption UI", e);
5386 }
5387 }
5388
Alison Cichowlas3e340502018-08-07 17:15:01 -04005389 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5390 mStartActivitySources.remove(permissionToken);
5391 mExpiredStartAsCallerTokens.add(permissionToken);
5392 }
5393
5394 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5395 mExpiredStartAsCallerTokens.remove(permissionToken);
5396 }
5397
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005398 boolean isActivityStartsLoggingEnabled() {
5399 return mAmInternal.isActivityStartsLoggingEnabled();
5400 }
5401
Michal Karpinski8596ded2018-11-14 14:43:48 +00005402 boolean isBackgroundActivityStartsEnabled() {
5403 return mAmInternal.isBackgroundActivityStartsEnabled();
5404 }
5405
Wale Ogunwalef6733932018-06-27 05:14:34 -07005406 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005407 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005408 mWindowManager.enableScreenAfterBoot();
5409
5410 synchronized (mGlobalLock) {
5411 updateEventDispatchingLocked(booted);
5412 }
5413 }
5414
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005415 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5416 if (r == null || !r.hasProcess()) {
5417 return KEY_DISPATCHING_TIMEOUT_MS;
5418 }
5419 return getInputDispatchingTimeoutLocked(r.app);
5420 }
5421
5422 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005423 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005424 }
5425
Wale Ogunwalef6733932018-06-27 05:14:34 -07005426 /**
5427 * Decide based on the configuration whether we should show the ANR,
5428 * crash, etc dialogs. The idea is that if there is no affordance to
5429 * press the on-screen buttons, or the user experience would be more
5430 * greatly impacted than the crash itself, we shouldn't show the dialog.
5431 *
5432 * A thought: SystemUI might also want to get told about this, the Power
5433 * dialog / global actions also might want different behaviors.
5434 */
5435 private void updateShouldShowDialogsLocked(Configuration config) {
5436 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5437 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5438 && config.navigation == Configuration.NAVIGATION_NONAV);
5439 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5440 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5441 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5442 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5443 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5444 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5445 HIDE_ERROR_DIALOGS, 0) != 0;
5446 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5447 }
5448
5449 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5450 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5451 FONT_SCALE, 1.0f, userId);
5452
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005453 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005454 if (getGlobalConfiguration().fontScale == scaleFactor) {
5455 return;
5456 }
5457
5458 final Configuration configuration
5459 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5460 configuration.fontScale = scaleFactor;
5461 updatePersistentConfiguration(configuration, userId);
5462 }
5463 }
5464
5465 // Actually is sleeping or shutting down or whatever else in the future
5466 // is an inactive state.
5467 boolean isSleepingOrShuttingDownLocked() {
5468 return isSleepingLocked() || mShuttingDown;
5469 }
5470
5471 boolean isSleepingLocked() {
5472 return mSleeping;
5473 }
5474
Riddle Hsu16567132018-08-16 21:37:47 +08005475 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005476 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005477 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005478 if (task.isActivityTypeStandard()) {
5479 if (mCurAppTimeTracker != r.appTimeTracker) {
5480 // We are switching app tracking. Complete the current one.
5481 if (mCurAppTimeTracker != null) {
5482 mCurAppTimeTracker.stop();
5483 mH.obtainMessage(
5484 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005485 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005486 mCurAppTimeTracker = null;
5487 }
5488 if (r.appTimeTracker != null) {
5489 mCurAppTimeTracker = r.appTimeTracker;
5490 startTimeTrackingFocusedActivityLocked();
5491 }
5492 } else {
5493 startTimeTrackingFocusedActivityLocked();
5494 }
5495 } else {
5496 r.appTimeTracker = null;
5497 }
5498 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5499 // TODO: Probably not, because we don't want to resume voice on switching
5500 // back to this activity
5501 if (task.voiceInteractor != null) {
5502 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5503 } else {
5504 finishRunningVoiceLocked();
5505
5506 if (mLastResumedActivity != null) {
5507 final IVoiceInteractionSession session;
5508
Louis Changcdec0802019-11-11 11:45:07 +08005509 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005510 if (lastResumedActivityTask != null
5511 && lastResumedActivityTask.voiceSession != null) {
5512 session = lastResumedActivityTask.voiceSession;
5513 } else {
5514 session = mLastResumedActivity.voiceSession;
5515 }
5516
5517 if (session != null) {
5518 // We had been in a voice interaction session, but now focused has
5519 // move to something different. Just finish the session, we can't
5520 // return to it and retain the proper state and synchronization with
5521 // the voice interaction service.
5522 finishVoiceTask(session);
5523 }
5524 }
5525 }
5526
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005527 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5528 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005529 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005530 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5531
Wale Ogunwalef6733932018-06-27 05:14:34 -07005532 updateResumedAppTrace(r);
5533 mLastResumedActivity = r;
5534
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005535 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005536
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005537 if (prevTask == null || task != prevTask) {
5538 if (prevTask != null) {
5539 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5540 }
5541 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5542 }
5543
Wale Ogunwalef6733932018-06-27 05:14:34 -07005544 applyUpdateLockStateLocked(r);
5545 applyUpdateVrModeLocked(r);
5546
Jeff Changd136e772019-11-05 20:33:52 +08005547 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005548 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005549 r == null ? "NULL" : r.shortComponentName,
5550 reason);
5551 }
5552
5553 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5554 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005555 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005556 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005557 updateSleepIfNeededLocked();
5558 return token;
5559 }
5560 }
5561
5562 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005563 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005564 final boolean wasSleeping = mSleeping;
5565 boolean updateOomAdj = false;
5566
5567 if (!shouldSleep) {
5568 // If wasSleeping is true, we need to wake up activity manager state from when
5569 // we started sleeping. In either case, we need to apply the sleep tokens, which
5570 // will wake up stacks or put them to sleep as appropriate.
5571 if (wasSleeping) {
5572 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005573 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5574 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005575 startTimeTrackingFocusedActivityLocked();
5576 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005577 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005578 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5579 }
Louis Chang149d5c82019-12-30 09:47:39 +08005580 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005581 if (wasSleeping) {
5582 updateOomAdj = true;
5583 }
5584 } else if (!mSleeping && shouldSleep) {
5585 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005586 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5587 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005588 if (mCurAppTimeTracker != null) {
5589 mCurAppTimeTracker.stop();
5590 }
5591 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005592 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005593 mStackSupervisor.goingToSleepLocked();
5594 updateResumedAppTrace(null /* resumed */);
5595 updateOomAdj = true;
5596 }
5597 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005598 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005599 }
5600 }
5601
5602 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005603 mH.removeCallbacks(mUpdateOomAdjRunnable);
5604 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005605 }
5606
Wale Ogunwale53783742018-09-16 10:21:51 -07005607 void updateCpuStats() {
5608 mH.post(mAmInternal::updateCpuStats);
5609 }
5610
Hui Yu03d12402018-12-06 18:00:37 -08005611 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5612 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005613 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5614 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005615 mH.sendMessage(m);
5616 }
5617
Hui Yu03d12402018-12-06 18:00:37 -08005618 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005619 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005620 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005621 if (task != null) {
5622 final ActivityRecord rootActivity = task.getRootActivity();
5623 if (rootActivity != null) {
5624 taskRoot = rootActivity.mActivityComponent;
5625 }
5626 }
5627
Hui Yu03d12402018-12-06 18:00:37 -08005628 final Message m = PooledLambda.obtainMessage(
5629 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005630 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005631 mH.sendMessage(m);
5632 }
5633
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005634 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5635 String hostingType) {
5636 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005637 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5638 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005639 + activity.processName);
5640 }
5641 // Post message to start process to avoid possible deadlock of calling into AMS with the
5642 // ATMS lock held.
5643 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5644 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5645 isTop, hostingType, activity.intent.getComponent());
5646 mH.sendMessage(m);
5647 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005648 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005649 }
5650 }
5651
Wale Ogunwale53783742018-09-16 10:21:51 -07005652 void setBooting(boolean booting) {
5653 mAmInternal.setBooting(booting);
5654 }
5655
5656 boolean isBooting() {
5657 return mAmInternal.isBooting();
5658 }
5659
5660 void setBooted(boolean booted) {
5661 mAmInternal.setBooted(booted);
5662 }
5663
5664 boolean isBooted() {
5665 return mAmInternal.isBooted();
5666 }
5667
5668 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5669 mH.post(() -> {
5670 if (finishBooting) {
5671 mAmInternal.finishBooting();
5672 }
5673 if (enableScreen) {
5674 mInternal.enableScreenAfterBoot(isBooted());
5675 }
5676 });
5677 }
5678
5679 void setHeavyWeightProcess(ActivityRecord root) {
5680 mHeavyWeightProcess = root.app;
5681 final Message m = PooledLambda.obtainMessage(
5682 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005683 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005684 mH.sendMessage(m);
5685 }
5686
5687 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5688 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5689 return;
5690 }
5691
5692 mHeavyWeightProcess = null;
5693 final Message m = PooledLambda.obtainMessage(
5694 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5695 proc.mUserId);
5696 mH.sendMessage(m);
5697 }
5698
5699 private void cancelHeavyWeightProcessNotification(int userId) {
5700 final INotificationManager inm = NotificationManager.getService();
5701 if (inm == null) {
5702 return;
5703 }
5704 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005705 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005706 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5707 } catch (RuntimeException e) {
5708 Slog.w(TAG, "Error canceling notification for service", e);
5709 } catch (RemoteException e) {
5710 }
5711
5712 }
5713
5714 private void postHeavyWeightProcessNotification(
5715 WindowProcessController proc, Intent intent, int userId) {
5716 if (proc == null) {
5717 return;
5718 }
5719
5720 final INotificationManager inm = NotificationManager.getService();
5721 if (inm == null) {
5722 return;
5723 }
5724
5725 try {
5726 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5727 String text = mContext.getString(R.string.heavy_weight_notification,
5728 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5729 Notification notification =
5730 new Notification.Builder(context,
5731 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5732 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5733 .setWhen(0)
5734 .setOngoing(true)
5735 .setTicker(text)
5736 .setColor(mContext.getColor(
5737 com.android.internal.R.color.system_notification_accent_color))
5738 .setContentTitle(text)
5739 .setContentText(
5740 mContext.getText(R.string.heavy_weight_notification_detail))
5741 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5742 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5743 new UserHandle(userId)))
5744 .build();
5745 try {
5746 inm.enqueueNotificationWithTag("android", "android", null,
5747 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5748 } catch (RuntimeException e) {
5749 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5750 } catch (RemoteException e) {
5751 }
5752 } catch (PackageManager.NameNotFoundException e) {
5753 Slog.w(TAG, "Unable to create context for heavy notification", e);
5754 }
5755
5756 }
5757
Philip P. Moltmannee295092020-02-10 08:46:26 -08005758 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5759 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5760 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005761
5762 ActivityRecord activity = null;
5763 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5764 activity = ActivityRecord.isInStackLocked(token);
5765 if (activity == null) {
5766 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5767 return null;
5768 }
5769 if (activity.finishing) {
5770 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5771 return null;
5772 }
5773 }
5774
5775 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005776 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5777 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005778 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5779 if (noCreate) {
5780 return rec;
5781 }
5782 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5783 if (activity.pendingResults == null) {
5784 activity.pendingResults = new HashSet<>();
5785 }
5786 activity.pendingResults.add(rec.ref);
5787 }
5788 return rec;
5789 }
5790
Andrii Kulian52d255c2018-07-13 11:32:19 -07005791 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005792 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005793 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005794 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5795 mCurAppTimeTracker.start(resumedActivity.packageName);
5796 }
5797 }
5798
5799 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5800 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005801 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005802 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5803 }
5804 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005805 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005806 constructResumedTraceName(resumed.packageName), 0);
5807 }
5808 mTracedResumedActivity = resumed;
5809 }
5810
5811 private String constructResumedTraceName(String packageName) {
5812 return "focused app: " + packageName;
5813 }
5814
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005815 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005816 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005817 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005818 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005819 // mainStack is null during startup.
5820 if (mainStack != null) {
5821 if (changes != 0 && starting == null) {
5822 // If the configuration changed, and the caller is not already
5823 // in the process of starting an activity, then find the top
5824 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005825 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005826 }
5827
5828 if (starting != null) {
5829 kept = starting.ensureActivityConfiguration(changes,
5830 false /* preserveWindow */);
5831 // And we need to make sure at this point that all other activities
5832 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005833 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005834 !PRESERVE_WINDOWS);
5835 }
5836 }
5837
5838 return kept;
5839 }
5840
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005841 void scheduleAppGcsLocked() {
5842 mH.post(() -> mAmInternal.scheduleAppGcs());
5843 }
5844
Wale Ogunwale53783742018-09-16 10:21:51 -07005845 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5846 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5847 }
5848
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005849 /**
5850 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5851 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5852 * on demand.
5853 */
5854 IPackageManager getPackageManager() {
5855 return AppGlobals.getPackageManager();
5856 }
5857
5858 PackageManagerInternal getPackageManagerInternalLocked() {
5859 if (mPmInternal == null) {
5860 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5861 }
5862 return mPmInternal;
5863 }
5864
Darryl L Johnsona0982222020-02-18 18:21:51 -08005865 ComponentName getSysUiServiceComponentLocked() {
5866 if (mSysUiServiceComponent == null) {
5867 final PackageManagerInternal pm = getPackageManagerInternalLocked();
5868 mSysUiServiceComponent = pm.getSystemUiServiceComponent();
5869 }
5870 return mSysUiServiceComponent;
5871 }
5872
Hai Zhangf4da9be2019-05-01 13:46:06 +08005873 PermissionPolicyInternal getPermissionPolicyInternal() {
5874 if (mPermissionPolicyInternal == null) {
5875 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5876 }
5877 return mPermissionPolicyInternal;
5878 }
5879
Wale Ogunwale008163e2018-07-23 23:11:08 -07005880 AppWarnings getAppWarningsLocked() {
5881 return mAppWarnings;
5882 }
5883
Wale Ogunwale214f3482018-10-04 11:00:47 -07005884 Intent getHomeIntent() {
5885 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5886 intent.setComponent(mTopComponent);
5887 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5888 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5889 intent.addCategory(Intent.CATEGORY_HOME);
5890 }
5891 return intent;
5892 }
5893
Chilun2ef71f72018-11-16 17:57:15 +08005894 /**
5895 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5896 * activities.
5897 *
Chilun939b05c2020-02-19 14:50:59 +08005898 * @param preferredPackage Specify a preferred package name, otherwise use the package name
5899 * defined in config_secondaryHomePackage.
Chilun2ef71f72018-11-16 17:57:15 +08005900 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5901 */
5902 Intent getSecondaryHomeIntent(String preferredPackage) {
5903 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005904 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5905 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5906 if (preferredPackage == null || useSystemProvidedLauncher) {
Chilun939b05c2020-02-19 14:50:59 +08005907 // Using the package name stored in config if no preferred package name or forced.
5908 final String secondaryHomePackage = mContext.getResources().getString(
5909 com.android.internal.R.string.config_secondaryHomePackage);
5910 intent.setPackage(secondaryHomePackage);
Chilun2ef71f72018-11-16 17:57:15 +08005911 } else {
5912 intent.setPackage(preferredPackage);
5913 }
5914 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5915 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5916 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5917 }
5918 return intent;
5919 }
5920
Wale Ogunwale214f3482018-10-04 11:00:47 -07005921 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5922 if (info == null) return null;
5923 ApplicationInfo newInfo = new ApplicationInfo(info);
5924 newInfo.initForUser(userId);
5925 return newInfo;
5926 }
5927
Wale Ogunwale9c103022018-10-18 07:44:54 -07005928 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005929 if (uid == SYSTEM_UID) {
5930 // The system gets to run in any process. If there are multiple processes with the same
5931 // uid, just pick the first (this should never happen).
5932 final SparseArray<WindowProcessController> procs =
5933 mProcessNames.getMap().get(processName);
5934 if (procs == null) return null;
5935 final int procCount = procs.size();
5936 for (int i = 0; i < procCount; i++) {
5937 final int procUid = procs.keyAt(i);
5938 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5939 // Don't use an app process or different user process for system component.
5940 continue;
5941 }
5942 return procs.valueAt(i);
5943 }
5944 }
5945
5946 return mProcessNames.get(processName, uid);
5947 }
5948
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005949 WindowProcessController getProcessController(IApplicationThread thread) {
5950 if (thread == null) {
5951 return null;
5952 }
5953
5954 final IBinder threadBinder = thread.asBinder();
5955 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5956 for (int i = pmap.size()-1; i >= 0; i--) {
5957 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5958 for (int j = procs.size() - 1; j >= 0; j--) {
5959 final WindowProcessController proc = procs.valueAt(j);
5960 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5961 return proc;
5962 }
5963 }
5964 }
5965
5966 return null;
5967 }
5968
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005969 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005970 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005971 if (proc == null) return null;
5972 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5973 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005974 }
5975 return null;
5976 }
5977
Riddle Hsua0536432019-02-16 00:38:59 +08005978 int getUidState(int uid) {
5979 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005980 }
5981
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005982 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005983 // A uid is considered to be foreground if it has a visible non-toast window.
5984 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005985 }
5986
Ricky Wai96f5c352019-04-10 18:40:17 +01005987 boolean isDeviceOwner(int uid) {
5988 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005989 }
5990
Ricky Wai96f5c352019-04-10 18:40:17 +01005991 void setDeviceOwnerUid(int uid) {
5992 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005993 }
5994
Wale Ogunwale9de19442018-10-18 19:05:03 -07005995 /**
5996 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5997 * the whitelist
5998 */
5999 String getPendingTempWhitelistTagForUidLocked(int uid) {
6000 return mPendingTempWhitelist.get(uid);
6001 }
6002
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006003 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6004 if (true || Build.IS_USER) {
6005 return;
6006 }
6007
6008 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6009 StrictMode.allowThreadDiskWrites();
6010 try {
6011 File tracesDir = new File("/data/anr");
6012 File tracesFile = null;
6013 try {
6014 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6015
6016 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006017 String timeString =
6018 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6019 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006020 sb.append(": ");
6021 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6022 sb.append(" since ");
6023 sb.append(msg);
6024 FileOutputStream fos = new FileOutputStream(tracesFile);
6025 fos.write(sb.toString().getBytes());
6026 if (app == null) {
6027 fos.write("\n*** No application process!".getBytes());
6028 }
6029 fos.close();
6030 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6031 } catch (IOException e) {
6032 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6033 return;
6034 }
6035
6036 if (app != null && app.getPid() > 0) {
6037 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6038 firstPids.add(app.getPid());
6039 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6040 }
6041
6042 File lastTracesFile = null;
6043 File curTracesFile = null;
6044 for (int i=9; i>=0; i--) {
6045 String name = String.format(Locale.US, "slow%02d.txt", i);
6046 curTracesFile = new File(tracesDir, name);
6047 if (curTracesFile.exists()) {
6048 if (lastTracesFile != null) {
6049 curTracesFile.renameTo(lastTracesFile);
6050 } else {
6051 curTracesFile.delete();
6052 }
6053 }
6054 lastTracesFile = curTracesFile;
6055 }
6056 tracesFile.renameTo(curTracesFile);
6057 } finally {
6058 StrictMode.setThreadPolicy(oldPolicy);
6059 }
6060 }
6061
Michal Karpinskida34cd42019-04-02 19:46:52 +01006062 boolean isAssociatedCompanionApp(int userId, int uid) {
6063 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6064 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006065 return false;
6066 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006067 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006068 }
6069
Issei Suzuki734bc942019-06-05 13:59:52 +02006070 void notifySingleTaskDisplayEmpty(int displayId) {
6071 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6072 }
6073
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006074 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006075 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006076
6077
Wale Ogunwale98875612018-10-12 07:53:02 -07006078 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6079 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006080
Riddle Hsud93a6c42018-11-29 21:50:06 +08006081 H(Looper looper) {
6082 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006083 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006084
6085 @Override
6086 public void handleMessage(Message msg) {
6087 switch (msg.what) {
6088 case REPORT_TIME_TRACKER_MSG: {
6089 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6090 tracker.deliverResult(mContext);
6091 } break;
6092 }
6093 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006094 }
6095
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006096 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006097 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006098
6099 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006100 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006101 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006102
6103 @Override
6104 public void handleMessage(Message msg) {
6105 switch (msg.what) {
6106 case DISMISS_DIALOG_UI_MSG: {
6107 final Dialog d = (Dialog) msg.obj;
6108 d.dismiss();
6109 break;
6110 }
6111 }
6112 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006113 }
6114
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006115 final class LocalService extends ActivityTaskManagerInternal {
6116 @Override
6117 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006118 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006119 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006120 }
6121
6122 @Override
6123 public ComponentName getHomeActivityForUser(int userId) {
6124 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006125 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006126 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006127 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006128 }
6129 }
6130
6131 @Override
6132 public void onLocalVoiceInteractionStarted(IBinder activity,
6133 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6134 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006135 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006136 }
6137 }
6138
6139 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006140 public void notifySingleTaskDisplayDrawn(int displayId) {
6141 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6142 }
6143
6144 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006145 public void notifyAppTransitionFinished() {
6146 synchronized (mGlobalLock) {
6147 mStackSupervisor.notifyAppTransitionDone();
6148 }
6149 }
6150
6151 @Override
6152 public void notifyAppTransitionCancelled() {
6153 synchronized (mGlobalLock) {
6154 mStackSupervisor.notifyAppTransitionDone();
6155 }
6156 }
6157
6158 @Override
6159 public List<IBinder> getTopVisibleActivities() {
6160 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006161 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006162 }
6163 }
6164
6165 @Override
Bernardo Rufinoe6cb3102020-03-06 20:33:11 +00006166 public boolean hasResumedActivity(int uid) {
6167 synchronized (mGlobalLock) {
6168 final ArraySet<WindowProcessController> processes = mProcessMap.getProcesses(uid);
6169 for (int i = 0, n = processes.size(); i < n; i++) {
6170 final WindowProcessController process = processes.valueAt(i);
6171 if (process.hasResumedActivity()) {
6172 return true;
6173 }
6174 }
6175 }
6176 return false;
6177 }
6178
6179 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006180 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6181 int userId, Intent[] intents, Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006182 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006183 final String[] resolvedTypes = new String[intents.length];
6184
6185 // UID of the package on user userId.
6186 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6187 // packageUid may not be initialized.
6188 int packageUid = 0;
6189 final long ident = Binder.clearCallingIdentity();
6190
6191 try {
6192 for (int i = 0; i < intents.length; i++) {
6193 resolvedTypes[i] =
6194 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6195 }
6196
6197 packageUid = AppGlobals.getPackageManager().getPackageUid(
6198 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6199 } catch (RemoteException e) {
6200 // Shouldn't happen.
6201 } finally {
6202 Binder.restoreCallingIdentity(ident);
6203 }
6204
Riddle Hsu591bf612019-02-14 17:55:31 +08006205 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006206 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006207 intents, resolvedTypes, null /* resultTo */,
6208 SafeActivityOptions.fromBundle(bOptions), userId,
6209 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6210 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006211 }
6212
6213 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006214 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006215 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6216 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6217 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006218 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006219 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006220 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006221 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006222 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6223 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006224 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006225 }
6226 }
6227
6228 @Override
6229 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006230 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6231 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6232 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6233 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006234 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006235 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006236 synchronized (mGlobalLock) {
6237 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006238 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6239 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6240 reason, validateIncomingUser, originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006241 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006242 }
6243 }
6244
6245 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006246 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006247 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6248 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006249 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006250 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006251 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006252 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006253 false /*validateIncomingUser*/);
6254 }
6255
6256 @Override
lumark588a3e82018-07-20 18:53:54 +08006257 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006258 synchronized (mGlobalLock) {
6259
6260 // We might change the visibilities here, so prepare an empty app transition which
6261 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006262 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006263 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006264 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006265 return;
6266 }
Louis Chang677921f2019-12-06 16:44:24 +08006267 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006268 final boolean wasTransitionSet =
6269 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006270 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006271 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006272 }
Louis Chang149d5c82019-12-30 09:47:39 +08006273 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006274
6275 // If there was a transition set already we don't want to interfere with it as we
6276 // might be starting it too early.
6277 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006278 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006279 }
6280 }
6281 if (callback != null) {
6282 callback.run();
6283 }
6284 }
6285
6286 @Override
6287 public void notifyKeyguardTrustedChanged() {
6288 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006289 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006290 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006291 }
6292 }
6293 }
6294
6295 /**
6296 * Called after virtual display Id is updated by
6297 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6298 * {@param vrVr2dDisplayId}.
6299 */
6300 @Override
6301 public void setVr2dDisplayId(int vr2dDisplayId) {
6302 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6303 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006304 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006305 }
6306 }
6307
6308 @Override
6309 public void setFocusedActivity(IBinder token) {
6310 synchronized (mGlobalLock) {
6311 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6312 if (r == null) {
6313 throw new IllegalArgumentException(
6314 "setFocusedActivity: No activity record matching token=" + token);
6315 }
Louis Chang19443452018-10-09 12:10:21 +08006316 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006317 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006318 }
6319 }
6320 }
6321
6322 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006323 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006324 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006325 }
6326
6327 @Override
6328 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006329 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006330 }
6331
6332 @Override
6333 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006334 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006335 }
6336
6337 @Override
6338 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6339 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6340 }
6341
6342 @Override
6343 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006344 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006345 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006346
6347 @Override
6348 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6349 synchronized (mGlobalLock) {
6350 mActiveVoiceInteractionServiceComponent = component;
6351 }
6352 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006353
6354 @Override
6355 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6356 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6357 return;
6358 }
6359 synchronized (mGlobalLock) {
6360 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6361 if (types == null) {
6362 if (uid < 0) {
6363 return;
6364 }
6365 types = new ArrayMap<>();
6366 mAllowAppSwitchUids.put(userId, types);
6367 }
6368 if (uid < 0) {
6369 types.remove(type);
6370 } else {
6371 types.put(type, uid);
6372 }
6373 }
6374 }
6375
6376 @Override
6377 public void onUserStopped(int userId) {
6378 synchronized (mGlobalLock) {
6379 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6380 mAllowAppSwitchUids.remove(userId);
6381 }
6382 }
6383
6384 @Override
6385 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6386 synchronized (mGlobalLock) {
6387 return ActivityTaskManagerService.this.isGetTasksAllowed(
6388 caller, callingPid, callingUid);
6389 }
6390 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006391
Riddle Hsua0536432019-02-16 00:38:59 +08006392 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006393 @Override
6394 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006395 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006396 mProcessNames.put(proc.mName, proc.mUid, proc);
6397 }
6398 }
6399
Riddle Hsua0536432019-02-16 00:38:59 +08006400 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006401 @Override
6402 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006403 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006404 mProcessNames.remove(name, uid);
6405 }
6406 }
6407
Riddle Hsua0536432019-02-16 00:38:59 +08006408 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006409 @Override
6410 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006411 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006412 if (proc == mHomeProcess) {
6413 mHomeProcess = null;
6414 }
6415 if (proc == mPreviousProcess) {
6416 mPreviousProcess = null;
6417 }
6418 }
6419 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006420
Riddle Hsua0536432019-02-16 00:38:59 +08006421 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006422 @Override
6423 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006424 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006425 return mTopProcessState;
6426 }
6427 }
6428
Riddle Hsua0536432019-02-16 00:38:59 +08006429 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006430 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006431 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006432 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006433 return proc == mHeavyWeightProcess;
6434 }
6435 }
6436
Riddle Hsua0536432019-02-16 00:38:59 +08006437 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006438 @Override
6439 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006440 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006441 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6442 }
6443 }
6444
6445 @Override
6446 public void finishHeavyWeightApp() {
6447 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006448 if (mHeavyWeightProcess != null) {
6449 mHeavyWeightProcess.finishActivities();
6450 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006451 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6452 mHeavyWeightProcess);
6453 }
6454 }
6455
Riddle Hsua0536432019-02-16 00:38:59 +08006456 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006457 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006458 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006459 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006460 return isSleepingLocked();
6461 }
6462 }
6463
6464 @Override
6465 public boolean isShuttingDown() {
6466 synchronized (mGlobalLock) {
6467 return mShuttingDown;
6468 }
6469 }
6470
6471 @Override
6472 public boolean shuttingDown(boolean booted, int timeout) {
6473 synchronized (mGlobalLock) {
6474 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006475 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006476 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006477 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006478 return mStackSupervisor.shutdownLocked(timeout);
6479 }
6480 }
6481
6482 @Override
6483 public void enableScreenAfterBoot(boolean booted) {
6484 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006485 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006486 mWindowManager.enableScreenAfterBoot();
6487 updateEventDispatchingLocked(booted);
6488 }
6489 }
6490
6491 @Override
6492 public boolean showStrictModeViolationDialog() {
6493 synchronized (mGlobalLock) {
6494 return mShowDialogs && !mSleeping && !mShuttingDown;
6495 }
6496 }
6497
6498 @Override
6499 public void showSystemReadyErrorDialogsIfNeeded() {
6500 synchronized (mGlobalLock) {
6501 try {
6502 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6503 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6504 + " data partition or your device will be unstable.");
6505 mUiHandler.post(() -> {
6506 if (mShowDialogs) {
6507 AlertDialog d = new BaseErrorDialog(mUiContext);
6508 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6509 d.setCancelable(false);
6510 d.setTitle(mUiContext.getText(R.string.android_system_label));
6511 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6512 d.setButton(DialogInterface.BUTTON_POSITIVE,
6513 mUiContext.getText(R.string.ok),
6514 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6515 d.show();
6516 }
6517 });
6518 }
6519 } catch (RemoteException e) {
6520 }
6521
6522 if (!Build.isBuildConsistent()) {
6523 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6524 mUiHandler.post(() -> {
6525 if (mShowDialogs) {
6526 AlertDialog d = new BaseErrorDialog(mUiContext);
6527 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6528 d.setCancelable(false);
6529 d.setTitle(mUiContext.getText(R.string.android_system_label));
6530 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6531 d.setButton(DialogInterface.BUTTON_POSITIVE,
6532 mUiContext.getText(R.string.ok),
6533 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6534 d.show();
6535 }
6536 });
6537 }
6538 }
6539 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006540
6541 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006542 public void onProcessMapped(int pid, WindowProcessController proc) {
6543 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006544 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006545 }
6546 }
6547
6548 @Override
6549 public void onProcessUnMapped(int pid) {
6550 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006551 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006552 }
6553 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006554
6555 @Override
6556 public void onPackageDataCleared(String name) {
6557 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006558 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006559 mAppWarnings.onPackageDataCleared(name);
6560 }
6561 }
6562
6563 @Override
6564 public void onPackageUninstalled(String name) {
6565 synchronized (mGlobalLock) {
6566 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006567 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006568 }
6569 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006570
6571 @Override
6572 public void onPackageAdded(String name, boolean replacing) {
6573 synchronized (mGlobalLock) {
6574 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6575 }
6576 }
6577
6578 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006579 public void onPackageReplaced(ApplicationInfo aInfo) {
6580 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006581 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006582 }
6583 }
6584
6585 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006586 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6587 synchronized (mGlobalLock) {
6588 return compatibilityInfoForPackageLocked(ai);
6589 }
6590 }
6591
Yunfan Chen75157d72018-07-27 14:47:21 +09006592 /**
6593 * Set the corresponding display information for the process global configuration. To be
6594 * called when we need to show IME on a different display.
6595 *
6596 * @param pid The process id associated with the IME window.
6597 * @param displayId The ID of the display showing the IME.
6598 */
6599 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006600 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006601 // Don't update process-level configuration for Multi-Client IME process since other
6602 // IMEs on other displays will also receive this configuration change due to IME
6603 // services use the same application config/context.
6604 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006605
Yunfan Chen75157d72018-07-27 14:47:21 +09006606 if (pid == MY_PID || pid < 0) {
6607 if (DEBUG_CONFIGURATION) {
6608 Slog.w(TAG,
6609 "Trying to update display configuration for system/invalid process.");
6610 }
6611 return;
6612 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006613 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006614 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006615 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006616 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006617 // Call might come when display is not yet added or has been removed.
6618 if (DEBUG_CONFIGURATION) {
6619 Slog.w(TAG, "Trying to update display configuration for non-existing "
6620 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006621 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006622 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006623 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006624 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006625 if (process == null) {
6626 if (DEBUG_CONFIGURATION) {
6627 Slog.w(TAG, "Trying to update display configuration for invalid "
6628 + "process, pid=" + pid);
6629 }
6630 return;
6631 }
lumarkddc77fb2019-06-27 22:22:23 +08006632 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006633 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006634 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006635 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006636
6637 @Override
6638 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006639 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006640 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006641 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006642 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006643 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006644 }
6645 }
6646 }
6647
6648 @Override
6649 public void clearPendingResultForActivity(IBinder activityToken,
6650 WeakReference<PendingIntentRecord> pir) {
6651 synchronized (mGlobalLock) {
6652 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6653 if (r != null && r.pendingResults != null) {
6654 r.pendingResults.remove(pir);
6655 }
6656 }
6657 }
6658
6659 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006660 public ActivityTokens getTopActivityForTask(int taskId) {
6661 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006662 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006663 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006664 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6665 + " Requested task not found");
6666 return null;
6667 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006668 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006669 if (activity == null) {
6670 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6671 + " Requested activity not found");
6672 return null;
6673 }
6674 if (!activity.attachedToProcess()) {
6675 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6676 + activity);
6677 return null;
6678 }
6679 return new ActivityTokens(activity.appToken, activity.assistToken,
6680 activity.app.getThread());
6681 }
6682 }
6683
6684 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006685 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006686 @Nullable String featureId, int callingUid, int userId, IBinder token,
6687 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6688 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006689 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006690 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6691 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006692 }
6693 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006694
6695 @Override
6696 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6697 synchronized (mGlobalLock) {
6698 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6699 if (r == null) {
6700 return null;
6701 }
6702 if (r.mServiceConnectionsHolder == null) {
6703 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6704 ActivityTaskManagerService.this, r);
6705 }
6706
6707 return r.mServiceConnectionsHolder;
6708 }
6709 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006710
6711 @Override
6712 public Intent getHomeIntent() {
6713 synchronized (mGlobalLock) {
6714 return ActivityTaskManagerService.this.getHomeIntent();
6715 }
6716 }
6717
6718 @Override
6719 public boolean startHomeActivity(int userId, String reason) {
6720 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006721 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006722 }
6723 }
6724
6725 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006726 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006727 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006728 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006729 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006730 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006731 }
Chilun8b1f1be2019-03-13 17:14:36 +08006732 }
6733
6734 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006735 public boolean startHomeOnAllDisplays(int userId, String reason) {
6736 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006737 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006738 }
6739 }
6740
Riddle Hsua0536432019-02-16 00:38:59 +08006741 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006742 @Override
6743 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006744 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006745 if (mFactoryTest == FACTORY_TEST_OFF) {
6746 return false;
6747 }
6748 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6749 && wpc.mName.equals(mTopComponent.getPackageName())) {
6750 return true;
6751 }
6752 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6753 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6754 }
6755 }
6756
6757 @Override
6758 public void updateTopComponentForFactoryTest() {
6759 synchronized (mGlobalLock) {
6760 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6761 return;
6762 }
6763 final ResolveInfo ri = mContext.getPackageManager()
6764 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6765 final CharSequence errorMsg;
6766 if (ri != null) {
6767 final ActivityInfo ai = ri.activityInfo;
6768 final ApplicationInfo app = ai.applicationInfo;
6769 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6770 mTopAction = Intent.ACTION_FACTORY_TEST;
6771 mTopData = null;
6772 mTopComponent = new ComponentName(app.packageName, ai.name);
6773 errorMsg = null;
6774 } else {
6775 errorMsg = mContext.getResources().getText(
6776 com.android.internal.R.string.factorytest_not_system);
6777 }
6778 } else {
6779 errorMsg = mContext.getResources().getText(
6780 com.android.internal.R.string.factorytest_no_action);
6781 }
6782 if (errorMsg == null) {
6783 return;
6784 }
6785
6786 mTopAction = null;
6787 mTopData = null;
6788 mTopComponent = null;
6789 mUiHandler.post(() -> {
6790 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6791 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006792 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006793 });
6794 }
6795 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006796
Riddle Hsua0536432019-02-16 00:38:59 +08006797 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006798 @Override
6799 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6800 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006801 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006802 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006803 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006804
6805 wpc.clearRecentTasks();
6806 wpc.clearActivities();
6807
6808 if (wpc.isInstrumenting()) {
6809 finishInstrumentationCallback.run();
6810 }
6811
Jorim Jaggid0752812018-10-16 16:07:20 +02006812 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006813 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006814 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006815 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006816 // If there was nothing to resume, and we are not already restarting
6817 // this process, but there is a visible activity that is hosted by the
6818 // process...then make sure all visible activities are running, taking
6819 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006820 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006821 !PRESERVE_WINDOWS);
6822 }
6823 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006824 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006825 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006826 }
6827 }
6828 }
6829
6830 @Override
6831 public void closeSystemDialogs(String reason) {
6832 enforceNotIsolatedCaller("closeSystemDialogs");
6833
6834 final int pid = Binder.getCallingPid();
6835 final int uid = Binder.getCallingUid();
6836 final long origId = Binder.clearCallingIdentity();
6837 try {
6838 synchronized (mGlobalLock) {
6839 // Only allow this from foreground processes, so that background
6840 // applications can't abuse it to prevent system UI from being shown.
6841 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006842 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006843 if (!proc.isPerceptible()) {
6844 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6845 + " from background process " + proc);
6846 return;
6847 }
6848 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006849 mWindowManager.closeSystemDialogs(reason);
6850
Louis Chang149d5c82019-12-30 09:47:39 +08006851 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006852 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006853 // Call into AM outside the synchronized block.
6854 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006855 } finally {
6856 Binder.restoreCallingIdentity(origId);
6857 }
6858 }
6859
6860 @Override
6861 public void cleanupDisabledPackageComponents(
6862 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6863 synchronized (mGlobalLock) {
6864 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006865 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006866 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006867 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006868 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006869 }
6870
6871 // Clean-up disabled tasks
6872 getRecentTasks().cleanupDisabledPackageTasksLocked(
6873 packageName, disabledClasses, userId);
6874 }
6875 }
6876
6877 @Override
6878 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6879 int userId) {
6880 synchronized (mGlobalLock) {
6881
6882 boolean didSomething =
6883 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006884 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006885 null, doit, evenPersistent, userId);
6886 return didSomething;
6887 }
6888 }
6889
6890 @Override
6891 public void resumeTopActivities(boolean scheduleIdle) {
6892 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006893 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006894 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006895 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006896 }
6897 }
6898 }
6899
Riddle Hsua0536432019-02-16 00:38:59 +08006900 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006901 @Override
6902 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006903 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006904 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6905 }
6906 }
6907
Riddle Hsua0536432019-02-16 00:38:59 +08006908 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006909 @Override
6910 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006911 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006912 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6913 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6914 }
6915 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006916 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006917 } finally {
6918 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6919 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006920 }
6921 }
6922
6923 @Override
6924 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6925 try {
6926 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6927 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6928 }
6929 } catch (RemoteException ex) {
6930 throw new SecurityException("Fail to check is caller a privileged app", ex);
6931 }
6932
6933 synchronized (mGlobalLock) {
6934 final long ident = Binder.clearCallingIdentity();
6935 try {
6936 if (mAmInternal.shouldConfirmCredentials(userId)) {
6937 if (mKeyguardController.isKeyguardLocked()) {
6938 // Showing launcher to avoid user entering credential twice.
6939 startHomeActivity(currentUserId, "notifyLockedProfile");
6940 }
Louis Chang149d5c82019-12-30 09:47:39 +08006941 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006942 }
6943 } finally {
6944 Binder.restoreCallingIdentity(ident);
6945 }
6946 }
6947 }
6948
6949 @Override
6950 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6951 mAmInternal.enforceCallingPermission(
6952 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6953
6954 synchronized (mGlobalLock) {
6955 final long ident = Binder.clearCallingIdentity();
6956 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006957 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6958 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006959 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006960 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6961 UserHandle.CURRENT);
6962 } finally {
6963 Binder.restoreCallingIdentity(ident);
6964 }
6965 }
6966 }
6967
6968 @Override
6969 public void writeActivitiesToProto(ProtoOutputStream proto) {
6970 synchronized (mGlobalLock) {
6971 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006972 mRootWindowContainer.dumpDebug(
6973 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006974 }
6975 }
6976
6977 @Override
6978 public void saveANRState(String reason) {
6979 synchronized (mGlobalLock) {
6980 final StringWriter sw = new StringWriter();
6981 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6982 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6983 if (reason != null) {
6984 pw.println(" Reason: " + reason);
6985 }
6986 pw.println();
6987 getActivityStartController().dump(pw, " ", null);
6988 pw.println();
6989 pw.println("-------------------------------------------------------------------------------");
6990 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6991 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6992 "" /* header */);
6993 pw.println();
6994 pw.close();
6995
6996 mLastANRState = sw.toString();
6997 }
6998 }
6999
7000 @Override
7001 public void clearSavedANRState() {
7002 synchronized (mGlobalLock) {
7003 mLastANRState = null;
7004 }
7005 }
7006
7007 @Override
7008 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7009 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7010 synchronized (mGlobalLock) {
7011 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7012 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7013 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7014 dumpLastANRLocked(pw);
7015 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7016 dumpLastANRTracesLocked(pw);
7017 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7018 dumpActivityStarterLocked(pw, dumpPackage);
7019 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7020 dumpActivityContainersLocked(pw);
7021 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7022 if (getRecentTasks() != null) {
7023 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7024 }
7025 }
7026 }
7027 }
7028
7029 @Override
7030 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7031 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7032 int wakefulness) {
7033 synchronized (mGlobalLock) {
7034 if (mHomeProcess != null && (dumpPackage == null
7035 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7036 if (needSep) {
7037 pw.println();
7038 needSep = false;
7039 }
7040 pw.println(" mHomeProcess: " + mHomeProcess);
7041 }
7042 if (mPreviousProcess != null && (dumpPackage == null
7043 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7044 if (needSep) {
7045 pw.println();
7046 needSep = false;
7047 }
7048 pw.println(" mPreviousProcess: " + mPreviousProcess);
7049 }
7050 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7051 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7052 StringBuilder sb = new StringBuilder(128);
7053 sb.append(" mPreviousProcessVisibleTime: ");
7054 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7055 pw.println(sb);
7056 }
7057 if (mHeavyWeightProcess != null && (dumpPackage == null
7058 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7059 if (needSep) {
7060 pw.println();
7061 needSep = false;
7062 }
7063 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7064 }
7065 if (dumpPackage == null) {
7066 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007067 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007068 }
7069 if (dumpAll) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007070 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7071 if (dumpPackage == null && topFocusedStack != null) {
7072 pw.println(" mConfigWillChange: " + topFocusedStack.mConfigWillChange);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007073 }
7074 if (mCompatModePackages.getPackages().size() > 0) {
7075 boolean printed = false;
7076 for (Map.Entry<String, Integer> entry
7077 : mCompatModePackages.getPackages().entrySet()) {
7078 String pkg = entry.getKey();
7079 int mode = entry.getValue();
7080 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7081 continue;
7082 }
7083 if (!printed) {
7084 pw.println(" mScreenCompatPackages:");
7085 printed = true;
7086 }
7087 pw.println(" " + pkg + ": " + mode);
7088 }
7089 }
7090 }
7091
7092 if (dumpPackage == null) {
7093 pw.println(" mWakefulness="
7094 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007095 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007096 if (mRunningVoice != null) {
7097 pw.println(" mRunningVoice=" + mRunningVoice);
7098 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7099 }
7100 pw.println(" mSleeping=" + mSleeping);
7101 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7102 pw.println(" mVrController=" + mVrController);
7103 }
7104 if (mCurAppTimeTracker != null) {
7105 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7106 }
7107 if (mAllowAppSwitchUids.size() > 0) {
7108 boolean printed = false;
7109 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7110 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7111 for (int j = 0; j < types.size(); j++) {
7112 if (dumpPackage == null ||
7113 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7114 if (needSep) {
7115 pw.println();
7116 needSep = false;
7117 }
7118 if (!printed) {
7119 pw.println(" mAllowAppSwitchUids:");
7120 printed = true;
7121 }
7122 pw.print(" User ");
7123 pw.print(mAllowAppSwitchUids.keyAt(i));
7124 pw.print(": Type ");
7125 pw.print(types.keyAt(j));
7126 pw.print(" = ");
7127 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7128 pw.println();
7129 }
7130 }
7131 }
7132 }
7133 if (dumpPackage == null) {
7134 if (mController != null) {
7135 pw.println(" mController=" + mController
7136 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7137 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007138 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7139 pw.println(" mLaunchingActivityWakeLock="
7140 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007141 }
7142
7143 return needSep;
7144 }
7145 }
7146
7147 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007148 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7149 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007150 synchronized (mGlobalLock) {
7151 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007152 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007153 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7154 if (topFocusedStack != null) {
7155 proto.write(CONFIG_WILL_CHANGE, topFocusedStack.mConfigWillChange);
7156 }
sanryhuang498e77e2018-12-06 14:57:01 +08007157 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7158 if (mRunningVoice != null) {
7159 final long vrToken = proto.start(
7160 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7161 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7162 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007163 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007164 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7165 proto.end(vrToken);
7166 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007167 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007168 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007169 if (mController != null) {
7170 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007171 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7172 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007173 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7174 proto.end(token);
7175 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007176 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7177 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007178 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007179 }
7180
7181 if (mHomeProcess != null && (dumpPackage == null
7182 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007183 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007184 }
7185
7186 if (mPreviousProcess != null && (dumpPackage == null
7187 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007188 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007189 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7190 }
7191
7192 if (mHeavyWeightProcess != null && (dumpPackage == null
7193 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007194 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007195 }
7196
7197 for (Map.Entry<String, Integer> entry
7198 : mCompatModePackages.getPackages().entrySet()) {
7199 String pkg = entry.getKey();
7200 int mode = entry.getValue();
7201 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7202 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7203 proto.write(PACKAGE, pkg);
7204 proto.write(MODE, mode);
7205 proto.end(compatToken);
7206 }
7207 }
7208
7209 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007210 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007211 }
7212
7213 }
7214 }
7215
7216 @Override
7217 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7218 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7219 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007220 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7221 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007222 }
7223
7224 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007225 public void dumpForOom(PrintWriter pw) {
7226 synchronized (mGlobalLock) {
7227 pw.println(" mHomeProcess: " + mHomeProcess);
7228 pw.println(" mPreviousProcess: " + mPreviousProcess);
7229 if (mHeavyWeightProcess != null) {
7230 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7231 }
7232 }
7233 }
7234
7235 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007236 public boolean canGcNow() {
7237 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007238 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007239 }
7240 }
7241
Riddle Hsua0536432019-02-16 00:38:59 +08007242 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007243 @Override
7244 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007245 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007246 if (mRootWindowContainer == null) {
7247 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007248 // oomadj after AMS created.
7249 return null;
7250 }
Louis Chang149d5c82019-12-30 09:47:39 +08007251 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007252 return top != null ? top.app : null;
7253 }
7254 }
7255
Riddle Hsua0536432019-02-16 00:38:59 +08007256 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007257 @Override
7258 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007259 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007260 if (mRootWindowContainer != null) {
7261 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007262 }
7263 }
7264 }
7265
7266 @Override
7267 public void scheduleDestroyAllActivities(String reason) {
7268 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007269 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007270 }
7271 }
7272
7273 @Override
7274 public void removeUser(int userId) {
7275 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007276 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007277 }
7278 }
7279
7280 @Override
7281 public boolean switchUser(int userId, UserState userState) {
7282 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007283 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007284 }
7285 }
7286
7287 @Override
7288 public void onHandleAppCrash(WindowProcessController wpc) {
7289 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007290 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007291 }
7292 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007293
7294 @Override
7295 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7296 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007297 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007298 }
7299 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007300
Riddle Hsua0536432019-02-16 00:38:59 +08007301 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007302 @Override
7303 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007304 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007305 }
7306
Riddle Hsua0536432019-02-16 00:38:59 +08007307 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007308 @Override
7309 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007310 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007311 }
7312
Riddle Hsua0536432019-02-16 00:38:59 +08007313 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007314 @Override
7315 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007316 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007317 }
7318
Riddle Hsua0536432019-02-16 00:38:59 +08007319 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007320 @Override
7321 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007322 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007323 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007324
7325 @Override
7326 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007327 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007328 mPendingTempWhitelist.put(uid, tag);
7329 }
7330 }
7331
7332 @Override
7333 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007334 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007335 mPendingTempWhitelist.remove(uid);
7336 }
7337 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007338
7339 @Override
7340 public boolean handleAppCrashInActivityController(String processName, int pid,
7341 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7342 Runnable killCrashingAppCallback) {
7343 synchronized (mGlobalLock) {
7344 if (mController == null) {
7345 return false;
7346 }
7347
7348 try {
7349 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7350 stackTrace)) {
7351 killCrashingAppCallback.run();
7352 return true;
7353 }
7354 } catch (RemoteException e) {
7355 mController = null;
7356 Watchdog.getInstance().setActivityController(null);
7357 }
7358 return false;
7359 }
7360 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007361
7362 @Override
7363 public void removeRecentTasksByPackageName(String packageName, int userId) {
7364 synchronized (mGlobalLock) {
7365 mRecentTasks.removeTasksByPackageName(packageName, userId);
7366 }
7367 }
7368
7369 @Override
7370 public void cleanupRecentTasksForUser(int userId) {
7371 synchronized (mGlobalLock) {
7372 mRecentTasks.cleanupLocked(userId);
7373 }
7374 }
7375
7376 @Override
7377 public void loadRecentTasksForUser(int userId) {
7378 synchronized (mGlobalLock) {
7379 mRecentTasks.loadUserRecentsLocked(userId);
7380 }
7381 }
7382
7383 @Override
7384 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7385 synchronized (mGlobalLock) {
7386 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7387 }
7388 }
7389
7390 @Override
7391 public void flushRecentTasks() {
7392 mRecentTasks.flush();
7393 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007394
7395 @Override
7396 public WindowProcessController getHomeProcess() {
7397 synchronized (mGlobalLock) {
7398 return mHomeProcess;
7399 }
7400 }
7401
7402 @Override
7403 public WindowProcessController getPreviousProcess() {
7404 synchronized (mGlobalLock) {
7405 return mPreviousProcess;
7406 }
7407 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007408
7409 @Override
7410 public void clearLockedTasks(String reason) {
7411 synchronized (mGlobalLock) {
7412 getLockTaskController().clearLockedTasks(reason);
7413 }
7414 }
7415
7416 @Override
7417 public void updateUserConfiguration() {
7418 synchronized (mGlobalLock) {
7419 final Configuration configuration = new Configuration(getGlobalConfiguration());
7420 final int currentUserId = mAmInternal.getCurrentUserId();
7421 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7422 configuration, currentUserId, Settings.System.canWrite(mContext));
7423 updateConfigurationLocked(configuration, null /* starting */,
7424 false /* initLocale */, false /* persistent */, currentUserId,
7425 false /* deferResume */);
7426 }
7427 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007428
7429 @Override
7430 public boolean canShowErrorDialogs() {
7431 synchronized (mGlobalLock) {
7432 return mShowDialogs && !mSleeping && !mShuttingDown
7433 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7434 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7435 mAmInternal.getCurrentUserId())
7436 && !(UserManager.isDeviceInDemoMode(mContext)
7437 && mAmInternal.getCurrentUser().isDemo());
7438 }
7439 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007440
7441 @Override
7442 public void setProfileApp(String profileApp) {
7443 synchronized (mGlobalLock) {
7444 mProfileApp = profileApp;
7445 }
7446 }
7447
7448 @Override
7449 public void setProfileProc(WindowProcessController wpc) {
7450 synchronized (mGlobalLock) {
7451 mProfileProc = wpc;
7452 }
7453 }
7454
7455 @Override
7456 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7457 synchronized (mGlobalLock) {
7458 mProfilerInfo = profilerInfo;
7459 }
7460 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007461
7462 @Override
7463 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7464 synchronized (mGlobalLock) {
7465 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7466 }
7467 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007468
7469 @Override
Zak Cohen84b43182020-03-09 14:36:01 -07007470 public ActivityManager.TaskSnapshot getTaskSnapshotBlocking(
7471 int taskId, boolean isLowResolution) {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08007472 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution,
Zak Cohen84b43182020-03-09 14:36:01 -07007473 true /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007474 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007475
7476 @Override
7477 public boolean isUidForeground(int uid) {
7478 synchronized (mGlobalLock) {
7479 return ActivityTaskManagerService.this.isUidForeground(uid);
7480 }
7481 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007482
7483 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007484 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007485 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007486 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007487 }
7488 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007489
7490 @Override
7491 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007492 // Translate package names into UIDs
7493 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007494 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007495 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7496 if (uid >= 0) {
7497 result.add(uid);
7498 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007499 }
7500 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007501 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007502 }
7503 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007504 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007505}