blob: d6e707795d50ddb7ab527c435d731a29cbc3eacf [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.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080055import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070067
Yunfan Chen79b96062018-10-17 12:45:23 -070068import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
69import static com.android.server.am.ActivityManagerService.MY_PID;
70import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
71import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Jeff Changd136e772019-11-05 20:33:52 +080086import static com.android.server.am.EventLogTags.writeBootProgressEnableScreen;
87import static com.android.server.am.EventLogTags.writeConfigurationChanged;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070088import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
89import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Louis Chang149d5c82019-12-30 09:47:39 +0800120import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
Louis Changcdec0802019-11-11 11:45:07 +0800122import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800127import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700128import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.annotation.Nullable;
130import android.annotation.UserIdInt;
131import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700132import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700133import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.ActivityOptions;
135import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700136import android.app.ActivityThread;
137import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700138import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100139import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700140import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700141import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700142import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.IApplicationThread;
144import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400146import android.app.IRequestFinishCallback;
Evan Rosky0037e5f2019-11-05 10:26:24 -0800147import android.app.ITaskOrganizerController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700149import android.app.Notification;
150import android.app.NotificationManager;
151import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700152import android.app.PictureInPictureParams;
153import android.app.ProfilerInfo;
154import android.app.RemoteAction;
155import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700156import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.app.admin.DevicePolicyCache;
158import android.app.assist.AssistContent;
159import android.app.assist.AssistStructure;
jorgegil@google.com06bc3232019-10-31 14:51:22 -0700160import android.app.servertransaction.ClientTransaction;
161import android.app.servertransaction.EnterPipRequestedItem;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700162import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700163import android.content.ActivityNotFoundException;
164import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700166import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.IIntentSender;
169import android.content.Intent;
170import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700171import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900172import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700173import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700174import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.content.pm.ParceledListSlice;
177import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700178import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700180import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700181import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.graphics.Bitmap;
183import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700184import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700185import android.metrics.LogMaker;
186import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700187import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700189import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700190import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700191import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700192import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700193import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700194import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700195import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800196import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700197import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700200import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100201import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700204import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700205import android.os.SystemClock;
206import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700207import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700208import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700210import android.os.UserManager;
211import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700212import android.os.storage.IStorageManager;
213import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700214import android.provider.Settings;
215import android.service.voice.IVoiceInteractionSession;
216import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900217import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700218import android.telecom.TelecomManager;
219import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100220import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700222import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700223import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700224import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700225import android.util.SparseArray;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700226import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700227import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700228import android.view.IRecentsAnimationRunner;
229import android.view.RemoteAnimationAdapter;
230import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700231import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700232
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700234import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700236import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700238import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700241import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
242import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700244import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700245import com.android.internal.policy.IKeyguardDismissCallback;
246import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700247import com.android.internal.util.ArrayUtils;
248import com.android.internal.util.FastPrintWriter;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800249import com.android.internal.util.FrameworkStatsLog;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800250import com.android.internal.util.function.pooled.PooledConsumer;
251import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700252import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700253import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.LocalServices;
255import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700256import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800257import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700258import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700259import com.android.server.am.ActivityManagerService;
260import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
261import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
262import com.android.server.am.AppTimeTracker;
263import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700264import com.android.server.am.PendingIntentController;
265import com.android.server.am.PendingIntentRecord;
266import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900267import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700268import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700269import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700270import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800271import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700272import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700276import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700278import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700280import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700281import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700282import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800283import java.lang.annotation.ElementType;
284import java.lang.annotation.Retention;
285import java.lang.annotation.RetentionPolicy;
286import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700287import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700288import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700290import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700291import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400292import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700293import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700295import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700296import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000297import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700298import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700299
300/**
301 * System service for managing activities and their containers (task, stacks, displays,... ).
302 *
303 * {@hide}
304 */
305public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700306 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800307 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000308 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700309 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
310 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
311 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
312 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700313 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700314
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700316 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700318 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100319 // How long we permit background activity starts after an activity in the process
320 // started or finished.
321 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700322
Wale Ogunwale98875612018-10-12 07:53:02 -0700323 /** Used to indicate that an app transition should be animated. */
324 static final boolean ANIMATE = true;
325
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700326 /** Hardware-reported OpenGLES version. */
327 final int GL_ES_VERSION;
328
Wale Ogunwale31913b52018-10-13 08:29:31 -0700329 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
330 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
331 public static final String DUMP_LASTANR_CMD = "lastanr" ;
332 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
333 public static final String DUMP_STARTER_CMD = "starter" ;
334 public static final String DUMP_CONTAINERS_CMD = "containers" ;
335 public static final String DUMP_RECENTS_CMD = "recents" ;
336 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
337
Wale Ogunwale64258362018-10-16 15:13:37 -0700338 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
339 public static final int RELAUNCH_REASON_NONE = 0;
340 /** This activity is being relaunched due to windowing mode change. */
341 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
342 /** This activity is being relaunched due to a free-resize operation. */
343 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
344
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700345 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700346
Wale Ogunwalef6733932018-06-27 05:14:34 -0700347 /**
348 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
349 * change at runtime. Use mContext for non-UI purposes.
350 */
351 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700352 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700353 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700354 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700355 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700356 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700357 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800358 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800359 @VisibleForTesting
360 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700361 PowerManagerInternal mPowerManagerInternal;
362 private UsageStatsManagerInternal mUsageStatsInternal;
363
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700364 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700365 IntentFirewall mIntentFirewall;
366
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700367 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800368 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800369 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700370 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800371 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
372 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
373 *
374 * @see WindowManagerThreadPriorityBooster
375 */
376 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700377 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800378 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700379 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700380 private UserManagerService mUserManager;
381 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700382 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800383 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700384 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700385 /** All processes currently running that might have a window organized by name. */
386 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100387 /** All processes we currently have running mapped by pid and uid */
388 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700389 /** This is the process holding what we currently consider to be the "home" activity. */
390 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700391 /** The currently running heavy-weight process, if any. */
392 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700393 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700394 /**
395 * This is the process holding the activity the user last visited that is in a different process
396 * from the one they are currently in.
397 */
398 WindowProcessController mPreviousProcess;
399 /** The time at which the previous process was last visible. */
400 long mPreviousProcessVisibleTime;
401
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700402 /** List of intents that were used to start the most recent tasks. */
403 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700404 /** State of external calls telling us if the device is awake or asleep. */
405 private boolean mKeyguardShown = false;
406
407 // Wrapper around VoiceInteractionServiceManager
408 private AssistUtils mAssistUtils;
409
410 // VoiceInteraction session ID that changes for each new request except when
411 // being called for multi-window assist in a single session.
412 private int mViSessionId = 1000;
413
414 // How long to wait in getAssistContextExtras for the activity and foreground services
415 // to respond with the result.
416 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
417
418 // How long top wait when going through the modern assist (which doesn't need to block
419 // on getting this result before starting to launch its UI).
420 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
421
422 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
423 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
424
Alison Cichowlas3e340502018-08-07 17:15:01 -0400425 // Permission tokens are used to temporarily granted a trusted app the ability to call
426 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
427 // showing any appropriate error messages to the user.
428 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
429 10 * MINUTE_IN_MILLIS;
430
431 // How long before the service actually expires a token. This is slightly longer than
432 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
433 // expiration exception.
434 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
435 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
436
437 // How long the service will remember expired tokens, for the purpose of providing error
438 // messaging when a client uses an expired token.
439 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
440 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
441
442 // Activity tokens of system activities that are delegating their call to
443 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
444 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
445
446 // Permission tokens that have expired, but we remember for error reporting.
447 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
448
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700449 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
450
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700451 // Keeps track of the active voice interaction service component, notified from
452 // VoiceInteractionManagerService
453 ComponentName mActiveVoiceInteractionServiceComponent;
454
Michal Karpinskida34cd42019-04-02 19:46:52 +0100455 // A map userId and all its companion app uids
456 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000457
Wale Ogunwalee2172292018-10-25 10:11:10 -0700458 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700459 KeyguardController mKeyguardController;
460 private final ClientLifecycleManager mLifecycleManager;
461 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700462 /** The controller for all operations related to locktask. */
463 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700464 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700465
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700466 boolean mSuppressResizeConfigChanges;
467
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700468 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700469 new UpdateConfigurationResult();
470
471 static final class UpdateConfigurationResult {
472 // Configuration changes that were updated.
473 int changes;
474 // If the activity was relaunched to match the new configuration.
475 boolean activityRelaunched;
476
477 void reset() {
478 changes = 0;
479 activityRelaunched = false;
480 }
481 }
482
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700483 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700484 private int mConfigurationSeq;
485 // To cache the list of supported system locales
486 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700487
488 /**
489 * Temp object used when global and/or display override configuration is updated. It is also
490 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
491 * anyone...
492 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700493 private Configuration mTempConfig = new Configuration();
494
Wale Ogunwalef6733932018-06-27 05:14:34 -0700495 /** Temporary to avoid allocations. */
496 final StringBuilder mStringBuilder = new StringBuilder(256);
497
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700498 // Amount of time after a call to stopAppSwitches() during which we will
499 // prevent further untrusted switches from happening.
500 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
501
502 /**
503 * The time at which we will allow normal application switches again,
504 * after a call to {@link #stopAppSwitches()}.
505 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700506 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700507 /**
508 * This is set to true after the first switch after mAppSwitchesAllowedTime
509 * is set; any switches after that will clear the time.
510 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700511 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700512
Ricky Wai906af482019-06-03 17:25:28 +0100513 /**
514 * Last stop app switches time, apps finished before this time cannot start background activity
515 * even if they are in grace period.
516 */
517 private long mLastStopAppSwitchesTime;
518
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700519 IActivityController mController = null;
520 boolean mControllerIsAMonkey = false;
521
Wale Ogunwale214f3482018-10-04 11:00:47 -0700522 final int mFactoryTest;
523
524 /** Used to control how we initialize the service. */
525 ComponentName mTopComponent;
526 String mTopAction = Intent.ACTION_MAIN;
527 String mTopData;
528
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800529 /** Profiling app information. */
530 String mProfileApp = null;
531 WindowProcessController mProfileProc = null;
532 ProfilerInfo mProfilerInfo = null;
533
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700534 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700535 * Dump of the activity state at the time of the last ANR. Cleared after
536 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
537 */
538 String mLastANRState;
539
540 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700541 * Used to retain an update lock when the foreground activity is in
542 * immersive mode.
543 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700544 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700545
546 /**
547 * Packages that are being allowed to perform unrestricted app switches. Mapping is
548 * User -> Type -> uid.
549 */
550 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
551
552 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700553 private int mThumbnailWidth;
554 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700555
556 /**
557 * Flag that indicates if multi-window is enabled.
558 *
559 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
560 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
561 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
562 * At least one of the forms of multi-window must be enabled in order for this flag to be
563 * initialized to 'true'.
564 *
565 * @see #mSupportsSplitScreenMultiWindow
566 * @see #mSupportsFreeformWindowManagement
567 * @see #mSupportsPictureInPicture
568 * @see #mSupportsMultiDisplay
569 */
570 boolean mSupportsMultiWindow;
571 boolean mSupportsSplitScreenMultiWindow;
572 boolean mSupportsFreeformWindowManagement;
573 boolean mSupportsPictureInPicture;
574 boolean mSupportsMultiDisplay;
575 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700576 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700577
578 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
579
580 // VR Vr2d Display Id.
581 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700582
Wale Ogunwalef6733932018-06-27 05:14:34 -0700583 /**
584 * Set while we are wanting to sleep, to prevent any
585 * activities from being started/resumed.
586 *
587 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
588 *
589 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
590 * while in the sleep state until there is a pending transition out of sleep, in which case
591 * mSleeping is set to false, and remains false while awake.
592 *
593 * Whether mSleeping can quickly toggled between true/false without the device actually
594 * display changing states is undefined.
595 */
596 private boolean mSleeping = false;
597
598 /**
599 * The process state used for processes that are running the top activities.
600 * This changes between TOP and TOP_SLEEPING to following mSleeping.
601 */
602 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
603
Riddle Hsua0022cd2019-09-09 21:12:41 +0800604 @Retention(RetentionPolicy.SOURCE)
605 @IntDef({
606 LAYOUT_REASON_CONFIG_CHANGED,
607 LAYOUT_REASON_VISIBILITY_CHANGED,
608 })
609 @interface LayoutReason {}
610 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
611 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
612
613 /** The reasons to perform surface placement. */
614 @LayoutReason
615 private int mLayoutReasons;
616
Wale Ogunwalef6733932018-06-27 05:14:34 -0700617 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
618 // automatically. Important for devices without direct input devices.
619 private boolean mShowDialogs = true;
620
621 /** Set if we are shutting down the system, similar to sleeping. */
622 boolean mShuttingDown = false;
623
624 /**
625 * We want to hold a wake lock while running a voice interaction session, since
626 * this may happen with the screen off and we need to keep the CPU running to
627 * be able to continue to interact with the user.
628 */
629 PowerManager.WakeLock mVoiceWakeLock;
630
631 /**
632 * Set while we are running a voice interaction. This overrides sleeping while it is active.
633 */
634 IVoiceInteractionSession mRunningVoice;
635
636 /**
637 * The last resumed activity. This is identical to the current resumed activity most
638 * of the time but could be different when we're pausing one activity before we resume
639 * another activity.
640 */
641 ActivityRecord mLastResumedActivity;
642
643 /**
644 * The activity that is currently being traced as the active resumed activity.
645 *
646 * @see #updateResumedAppTrace
647 */
648 private @Nullable ActivityRecord mTracedResumedActivity;
649
650 /** If non-null, we are tracking the time the user spends in the currently focused app. */
651 AppTimeTracker mCurAppTimeTracker;
652
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700653 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700654
Wale Ogunwale53783742018-09-16 10:21:51 -0700655 /**
656 * Packages that the user has asked to have run in screen size
657 * compatibility mode instead of filling the screen.
658 */
659 CompatModePackages mCompatModePackages;
660
Wale Ogunwalef6733932018-06-27 05:14:34 -0700661 private FontScaleSettingObserver mFontScaleSettingObserver;
662
Robert Carr8a2f9132019-11-11 15:03:15 -0800663 /**
664 * Stores the registration and state of TaskOrganizers in use.
665 */
Evan Rosky0037e5f2019-11-05 10:26:24 -0800666 TaskOrganizerController mTaskOrganizerController = new TaskOrganizerController(this);
Robert Carr8a2f9132019-11-11 15:03:15 -0800667
Ricky Wai96f5c352019-04-10 18:40:17 +0100668 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000669
Wale Ogunwalef6733932018-06-27 05:14:34 -0700670 private final class FontScaleSettingObserver extends ContentObserver {
671 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
672 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
673
674 public FontScaleSettingObserver() {
675 super(mH);
676 final ContentResolver resolver = mContext.getContentResolver();
677 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
678 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
679 UserHandle.USER_ALL);
680 }
681
682 @Override
683 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
684 if (mFontScaleUri.equals(uri)) {
685 updateFontScaleIfNeeded(userId);
686 } else if (mHideErrorDialogsUri.equals(uri)) {
687 synchronized (mGlobalLock) {
688 updateShouldShowDialogsLocked(getGlobalConfiguration());
689 }
690 }
691 }
692 }
693
Riddle Hsua0536432019-02-16 00:38:59 +0800694 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
695 @Target(ElementType.METHOD)
696 @Retention(RetentionPolicy.SOURCE)
697 @interface HotPath {
698 int NONE = 0;
699 int OOM_ADJUSTMENT = 1;
700 int LRU_UPDATE = 2;
701 int PROCESS_CHANGE = 3;
702 int caller() default NONE;
703 }
704
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800705 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
706 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900707 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800708 mAmInternal.updateOomAdj();
709 }
710 };
711
Charles Chen8d98dd22018-12-26 17:36:54 +0800712 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
713 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700714 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700715 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700716 mSystemThread = ActivityThread.currentActivityThread();
717 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700718 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800719 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700720 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700721 }
722
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700723 public void onSystemReady() {
724 synchronized (mGlobalLock) {
725 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
726 PackageManager.FEATURE_CANT_SAVE_STATE);
727 mAssistUtils = new AssistUtils(mContext);
728 mVrController.onSystemReady();
729 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700730 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700731 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700732 }
733
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700734 public void onInitPowerManagement() {
735 synchronized (mGlobalLock) {
736 mStackSupervisor.initPowerManagement();
737 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
738 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
739 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
740 mVoiceWakeLock.setReferenceCounted(false);
741 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700742 }
743
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700744 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700745 mFontScaleSettingObserver = new FontScaleSettingObserver();
746 }
747
Wale Ogunwale59507092018-10-29 09:00:30 -0700748 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700749 final boolean freeformWindowManagement =
750 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
751 || Settings.Global.getInt(
752 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
753
754 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
755 final boolean supportsPictureInPicture = supportsMultiWindow &&
756 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
757 final boolean supportsSplitScreenMultiWindow =
758 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
759 final boolean supportsMultiDisplay = mContext.getPackageManager()
760 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700761 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
762 final boolean forceResizable = Settings.Global.getInt(
763 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700764 final boolean sizeCompatFreeform = Settings.Global.getInt(
765 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700766
767 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900768 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700769
770 final Configuration configuration = new Configuration();
771 Settings.System.getConfiguration(resolver, configuration);
772 if (forceRtl) {
773 // This will take care of setting the correct layout direction flags
774 configuration.setLayoutDirection(configuration.locale);
775 }
776
777 synchronized (mGlobalLock) {
778 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700779 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700780 final boolean multiWindowFormEnabled = freeformWindowManagement
781 || supportsSplitScreenMultiWindow
782 || supportsPictureInPicture
783 || supportsMultiDisplay;
784 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
785 mSupportsMultiWindow = true;
786 mSupportsFreeformWindowManagement = freeformWindowManagement;
787 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
788 mSupportsPictureInPicture = supportsPictureInPicture;
789 mSupportsMultiDisplay = supportsMultiDisplay;
790 } else {
791 mSupportsMultiWindow = false;
792 mSupportsFreeformWindowManagement = false;
793 mSupportsSplitScreenMultiWindow = false;
794 mSupportsPictureInPicture = false;
795 mSupportsMultiDisplay = false;
796 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700797 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700798 // This happens before any activities are started, so we can change global configuration
799 // in-place.
800 updateConfigurationLocked(configuration, null, true);
801 final Configuration globalConfig = getGlobalConfiguration();
802 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
803
804 // Load resources only after the current configuration has been set.
805 final Resources res = mContext.getResources();
806 mThumbnailWidth = res.getDimensionPixelSize(
807 com.android.internal.R.dimen.thumbnail_width);
808 mThumbnailHeight = res.getDimensionPixelSize(
809 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700810 }
811 }
812
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800813 public WindowManagerGlobalLock getGlobalLock() {
814 return mGlobalLock;
815 }
816
Yunfan Chen585f2932019-01-29 16:04:45 +0900817 /** For test purpose only. */
818 @VisibleForTesting
819 public ActivityTaskManagerInternal getAtmInternal() {
820 return mInternal;
821 }
822
Riddle Hsud93a6c42018-11-29 21:50:06 +0800823 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
824 Looper looper) {
825 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700826 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700827 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700828 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800829 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700830 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700831 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700832 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700833
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700834 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700835 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700836 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700837 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700838 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700839 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700840 mKeyguardController = mStackSupervisor.getKeyguardController();
841 }
842
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700843 public void onActivityManagerInternalAdded() {
844 synchronized (mGlobalLock) {
845 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
846 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
847 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700848 }
849
Yunfan Chen75157d72018-07-27 14:47:21 +0900850 int increaseConfigurationSeqLocked() {
851 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
852 return mConfigurationSeq;
853 }
854
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700855 protected ActivityStackSupervisor createStackSupervisor() {
856 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
857 supervisor.initialize();
858 return supervisor;
859 }
860
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800861 protected AppWarnings createAppWarnings(
862 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
863 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
864 }
865
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700866 public void setWindowManager(WindowManagerService wm) {
867 synchronized (mGlobalLock) {
868 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800869 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800870 mTempConfig.setToDefaults();
871 mTempConfig.setLocales(LocaleList.getDefault());
872 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800873 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700874 mLockTaskController.setWindowManager(wm);
875 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800876 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700877 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700878 }
879
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700880 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
881 synchronized (mGlobalLock) {
882 mUsageStatsInternal = usageStatsManager;
883 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700884 }
885
Wale Ogunwalef6733932018-06-27 05:14:34 -0700886 UserManagerService getUserManager() {
887 if (mUserManager == null) {
888 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
889 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
890 }
891 return mUserManager;
892 }
893
894 AppOpsService getAppOpsService() {
895 if (mAppOpsService == null) {
896 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
897 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
898 }
899 return mAppOpsService;
900 }
901
902 boolean hasUserRestriction(String restriction, int userId) {
903 return getUserManager().hasUserRestriction(restriction, userId);
904 }
905
Michal Karpinski15486842019-04-25 17:33:42 +0100906 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
907 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmannda554e42019-12-20 11:21:02 -0800908 callingUid, callingPackage, /* featureId */ null, false, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100909 if (mode == AppOpsManager.MODE_DEFAULT) {
910 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
911 == PERMISSION_GRANTED;
912 }
913 return mode == AppOpsManager.MODE_ALLOWED;
914 }
915
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700916 @VisibleForTesting
917 protected void setRecentTasks(RecentTasks recentTasks) {
918 mRecentTasks = recentTasks;
919 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700920 }
921
922 RecentTasks getRecentTasks() {
923 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700924 }
925
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700926 ClientLifecycleManager getLifecycleManager() {
927 return mLifecycleManager;
928 }
929
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700930 ActivityStartController getActivityStartController() {
931 return mActivityStartController;
932 }
933
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700934 TaskChangeNotificationController getTaskChangeNotificationController() {
935 return mTaskChangeNotificationController;
936 }
937
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700938 LockTaskController getLockTaskController() {
939 return mLockTaskController;
940 }
941
Yunfan Chen75157d72018-07-27 14:47:21 +0900942 /**
943 * Return the global configuration used by the process corresponding to the input pid. This is
944 * usually the global configuration with some overrides specific to that process.
945 */
946 Configuration getGlobalConfigurationForCallingPid() {
947 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800948 return getGlobalConfigurationForPid(pid);
949 }
950
951 /**
952 * Return the global configuration used by the process corresponding to the given pid.
953 */
954 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900955 if (pid == MY_PID || pid < 0) {
956 return getGlobalConfiguration();
957 }
958 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100959 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900960 return app != null ? app.getConfiguration() : getGlobalConfiguration();
961 }
962 }
963
964 /**
965 * Return the device configuration info used by the process corresponding to the input pid.
966 * The value is consistent with the global configuration for the process.
967 */
968 @Override
969 public ConfigurationInfo getDeviceConfigurationInfo() {
970 ConfigurationInfo config = new ConfigurationInfo();
971 synchronized (mGlobalLock) {
972 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
973 config.reqTouchScreen = globalConfig.touchscreen;
974 config.reqKeyboardType = globalConfig.keyboard;
975 config.reqNavigation = globalConfig.navigation;
976 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
977 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
978 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
979 }
980 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
981 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
982 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
983 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700984 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900985 }
986 return config;
987 }
988
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700989 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700990 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700991 }
992
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700993 public static final class Lifecycle extends SystemService {
994 private final ActivityTaskManagerService mService;
995
996 public Lifecycle(Context context) {
997 super(context);
998 mService = new ActivityTaskManagerService(context);
999 }
1000
1001 @Override
1002 public void onStart() {
1003 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001004 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001005 }
1006
Garfield Tan891146c2018-10-09 12:14:00 -07001007 @Override
1008 public void onUnlockUser(int userId) {
1009 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001010 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001011 }
1012 }
1013
1014 @Override
1015 public void onCleanupUser(int userId) {
1016 synchronized (mService.getGlobalLock()) {
1017 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1018 }
1019 }
1020
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001021 public ActivityTaskManagerService getService() {
1022 return mService;
1023 }
1024 }
1025
1026 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001027 public final int startActivity(IApplicationThread caller, String callingPackage,
1028 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1029 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1030 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1031 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1032 UserHandle.getCallingUserId());
1033 }
1034
1035 @Override
1036 public final int startActivities(IApplicationThread caller, String callingPackage,
1037 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1038 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001039 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001041 enforceNotIsolatedCaller(reason);
1042 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001044 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1045 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1046 reason, null /* originatingPendingIntent */,
1047 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001048 }
1049
1050 @Override
1051 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1052 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1053 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1054 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1055 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1056 true /*validateIncomingUser*/);
1057 }
1058
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001059 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1061 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1062 boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001063 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001064 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001065
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001066 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001067 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1068
1069 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001070 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001071 .setCaller(caller)
1072 .setCallingPackage(callingPackage)
1073 .setResolvedType(resolvedType)
1074 .setResultTo(resultTo)
1075 .setResultWho(resultWho)
1076 .setRequestCode(requestCode)
1077 .setStartFlags(startFlags)
1078 .setProfilerInfo(profilerInfo)
1079 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001080 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001081 .execute();
1082
1083 }
1084
1085 @Override
1086 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1087 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001088 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1089 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001090 // Refuse possible leaked file descriptors
1091 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1092 throw new IllegalArgumentException("File descriptors passed in Intent");
1093 }
1094
1095 if (!(target instanceof PendingIntentRecord)) {
1096 throw new IllegalArgumentException("Bad PendingIntent object");
1097 }
1098
1099 PendingIntentRecord pir = (PendingIntentRecord)target;
1100
1101 synchronized (mGlobalLock) {
1102 // If this is coming from the currently resumed activity, it is
1103 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001104 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001105 if (stack.mResumedActivity != null &&
1106 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001107 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001108 }
1109 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001110 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001111 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001112 }
1113
1114 @Override
1115 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1116 Bundle bOptions) {
1117 // Refuse possible leaked file descriptors
1118 if (intent != null && intent.hasFileDescriptors()) {
1119 throw new IllegalArgumentException("File descriptors passed in Intent");
1120 }
1121 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1122
1123 synchronized (mGlobalLock) {
1124 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1125 if (r == null) {
1126 SafeActivityOptions.abort(options);
1127 return false;
1128 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001129 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001130 // The caller is not running... d'oh!
1131 SafeActivityOptions.abort(options);
1132 return false;
1133 }
1134 intent = new Intent(intent);
1135 // The caller is not allowed to change the data.
1136 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1137 // And we are resetting to find the next component...
1138 intent.setComponent(null);
1139
1140 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1141
1142 ActivityInfo aInfo = null;
1143 try {
1144 List<ResolveInfo> resolves =
1145 AppGlobals.getPackageManager().queryIntentActivities(
1146 intent, r.resolvedType,
1147 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1148 UserHandle.getCallingUserId()).getList();
1149
1150 // Look for the original activity in the list...
1151 final int N = resolves != null ? resolves.size() : 0;
1152 for (int i=0; i<N; i++) {
1153 ResolveInfo rInfo = resolves.get(i);
1154 if (rInfo.activityInfo.packageName.equals(r.packageName)
1155 && rInfo.activityInfo.name.equals(r.info.name)) {
1156 // We found the current one... the next matching is
1157 // after it.
1158 i++;
1159 if (i<N) {
1160 aInfo = resolves.get(i).activityInfo;
1161 }
1162 if (debug) {
1163 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1164 + "/" + r.info.name);
1165 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1166 ? "null" : aInfo.packageName + "/" + aInfo.name));
1167 }
1168 break;
1169 }
1170 }
1171 } catch (RemoteException e) {
1172 }
1173
1174 if (aInfo == null) {
1175 // Nobody who is next!
1176 SafeActivityOptions.abort(options);
1177 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1178 return false;
1179 }
1180
1181 intent.setComponent(new ComponentName(
1182 aInfo.applicationInfo.packageName, aInfo.name));
1183 intent.setFlags(intent.getFlags()&~(
1184 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1185 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1186 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1187 FLAG_ACTIVITY_NEW_TASK));
1188
1189 // Okay now we need to start the new activity, replacing the currently running activity.
1190 // This is a little tricky because we want to start the new one as if the current one is
1191 // finished, but not finish the current one first so that there is no flicker.
1192 // And thus...
1193 final boolean wasFinishing = r.finishing;
1194 r.finishing = true;
1195
1196 // Propagate reply information over to the new activity.
1197 final ActivityRecord resultTo = r.resultTo;
1198 final String resultWho = r.resultWho;
1199 final int requestCode = r.requestCode;
1200 r.resultTo = null;
1201 if (resultTo != null) {
1202 resultTo.removeResultsLocked(r, resultWho, requestCode);
1203 }
1204
1205 final long origId = Binder.clearCallingIdentity();
1206 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001207 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001208 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001209 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001210 .setResolvedType(r.resolvedType)
1211 .setActivityInfo(aInfo)
1212 .setResultTo(resultTo != null ? resultTo.appToken : null)
1213 .setResultWho(resultWho)
1214 .setRequestCode(requestCode)
1215 .setCallingPid(-1)
1216 .setCallingUid(r.launchedFromUid)
1217 .setCallingPackage(r.launchedFromPackage)
1218 .setRealCallingPid(-1)
1219 .setRealCallingUid(r.launchedFromUid)
1220 .setActivityOptions(options)
1221 .execute();
1222 Binder.restoreCallingIdentity(origId);
1223
1224 r.finishing = wasFinishing;
1225 if (res != ActivityManager.START_SUCCESS) {
1226 return false;
1227 }
1228 return true;
1229 }
1230 }
1231
1232 @Override
1233 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1234 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1235 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001236 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001238 enforceNotIsolatedCaller("startActivityAndWait");
1239 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1240 userId, "startActivityAndWait");
1241 // TODO: Switch to user app stacks here.
1242 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1243 .setCaller(caller)
1244 .setCallingPackage(callingPackage)
1245 .setResolvedType(resolvedType)
1246 .setResultTo(resultTo)
1247 .setResultWho(resultWho)
1248 .setRequestCode(requestCode)
1249 .setStartFlags(startFlags)
1250 .setActivityOptions(bOptions)
1251 .setUserId(userId)
1252 .setProfilerInfo(profilerInfo)
1253 .setWaitResult(res)
1254 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001255 return res;
1256 }
1257
1258 @Override
1259 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1260 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1261 int startFlags, Configuration config, Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001262 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001263 enforceNotIsolatedCaller("startActivityWithConfig");
1264 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1265 "startActivityWithConfig");
1266 // TODO: Switch to user app stacks here.
1267 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1268 .setCaller(caller)
1269 .setCallingPackage(callingPackage)
1270 .setResolvedType(resolvedType)
1271 .setResultTo(resultTo)
1272 .setResultWho(resultWho)
1273 .setRequestCode(requestCode)
1274 .setStartFlags(startFlags)
1275 .setGlobalConfiguration(config)
1276 .setActivityOptions(bOptions)
1277 .setUserId(userId)
1278 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001279 }
1280
Robert Carr8a2f9132019-11-11 15:03:15 -08001281 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001282 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1283 int callingUid = Binder.getCallingUid();
1284 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1285 throw new SecurityException("Only the system process can request a permission token, "
1286 + "received request from uid: " + callingUid);
1287 }
1288 IBinder permissionToken = new Binder();
1289 synchronized (mGlobalLock) {
1290 mStartActivitySources.put(permissionToken, delegatorToken);
1291 }
1292
1293 Message expireMsg = PooledLambda.obtainMessage(
1294 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1295 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1296
1297 Message forgetMsg = PooledLambda.obtainMessage(
1298 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1299 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1300
1301 return permissionToken;
1302 }
1303
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001304 @Override
1305 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1306 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001307 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1308 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001309 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001310 // permission grants) as any app that may launch one of your own activities. So we only
1311 // allow this in two cases:
1312 // 1) The caller is an activity that is part of the core framework, and then only when it
1313 // is running as the system.
1314 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1315 // can only be requested by a system activity, which may then delegate this call to
1316 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001317 final ActivityRecord sourceRecord;
1318 final int targetUid;
1319 final String targetPackage;
1320 final boolean isResolver;
1321 synchronized (mGlobalLock) {
1322 if (resultTo == null) {
1323 throw new SecurityException("Must be called from an activity");
1324 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001325 final IBinder sourceToken;
1326 if (permissionToken != null) {
1327 // To even attempt to use a permissionToken, an app must also have this signature
1328 // permission.
1329 mAmInternal.enforceCallingPermission(
1330 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1331 "startActivityAsCaller");
1332 // If called with a permissionToken, we want the sourceRecord from the delegator
1333 // activity that requested this token.
1334 sourceToken = mStartActivitySources.remove(permissionToken);
1335 if (sourceToken == null) {
1336 // Invalid permissionToken, check if it recently expired.
1337 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1338 throw new SecurityException("Called with expired permission token: "
1339 + permissionToken);
1340 } else {
1341 throw new SecurityException("Called with invalid permission token: "
1342 + permissionToken);
1343 }
1344 }
1345 } else {
1346 // This method was called directly by the source.
1347 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001348 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001349
Louis Chang149d5c82019-12-30 09:47:39 +08001350 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001351 if (sourceRecord == null) {
1352 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001353 }
1354 if (sourceRecord.app == null) {
1355 throw new SecurityException("Called without a process attached to activity");
1356 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001357
1358 // Whether called directly or from a delegate, the source activity must be from the
1359 // android package.
1360 if (!sourceRecord.info.packageName.equals("android")) {
1361 throw new SecurityException("Must be called from an activity that is "
1362 + "declared in the android package");
1363 }
1364
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001365 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001366 // This is still okay, as long as this activity is running under the
1367 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001368 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001369 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001370 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001371 + " must be system uid or original calling uid "
1372 + sourceRecord.launchedFromUid);
1373 }
1374 }
1375 if (ignoreTargetSecurity) {
1376 if (intent.getComponent() == null) {
1377 throw new SecurityException(
1378 "Component must be specified with ignoreTargetSecurity");
1379 }
1380 if (intent.getSelector() != null) {
1381 throw new SecurityException(
1382 "Selector not allowed with ignoreTargetSecurity");
1383 }
1384 }
1385 targetUid = sourceRecord.launchedFromUid;
1386 targetPackage = sourceRecord.launchedFromPackage;
1387 isResolver = sourceRecord.isResolverOrChildActivity();
1388 }
1389
1390 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001391 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001392 }
1393
1394 // TODO: Switch to user app stacks here.
1395 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001396 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001397 .setCallingUid(targetUid)
1398 .setCallingPackage(targetPackage)
1399 .setResolvedType(resolvedType)
1400 .setResultTo(resultTo)
1401 .setResultWho(resultWho)
1402 .setRequestCode(requestCode)
1403 .setStartFlags(startFlags)
1404 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001405 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001406 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1407 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001408 // The target may well be in the background, which would normally prevent it
1409 // from starting an activity. Here we definitely want the start to succeed.
1410 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001411 .execute();
1412 } catch (SecurityException e) {
1413 // XXX need to figure out how to propagate to original app.
1414 // A SecurityException here is generally actually a fault of the original
1415 // calling activity (such as a fairly granting permissions), so propagate it
1416 // back to them.
1417 /*
1418 StringBuilder msg = new StringBuilder();
1419 msg.append("While launching");
1420 msg.append(intent.toString());
1421 msg.append(": ");
1422 msg.append(e.getMessage());
1423 */
1424 throw e;
1425 }
1426 }
1427
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001428 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1429 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001430 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001431 }
1432
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001433 @Override
1434 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1435 Intent intent, String resolvedType, IVoiceInteractionSession session,
1436 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1437 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001438 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001439 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001440 if (session == null || interactor == null) {
1441 throw new NullPointerException("null session or interactor");
1442 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001443 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001444 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001445 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001446 .setCallingUid(callingUid)
1447 .setCallingPackage(callingPackage)
1448 .setResolvedType(resolvedType)
1449 .setVoiceSession(session)
1450 .setVoiceInteractor(interactor)
1451 .setStartFlags(startFlags)
1452 .setProfilerInfo(profilerInfo)
1453 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001454 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001455 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456 .execute();
1457 }
1458
1459 @Override
1460 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1461 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001462 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001463 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1464 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001466 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001467 .setCallingUid(callingUid)
1468 .setCallingPackage(callingPackage)
1469 .setResolvedType(resolvedType)
1470 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001471 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001472 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 .execute();
1474 }
1475
Riddle Hsu609a8e22019-06-27 16:46:29 -06001476 /**
1477 * Start the recents activity to perform the recents animation.
1478 *
1479 * @param intent The intent to start the recents activity.
1480 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1481 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001482 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001483 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1484 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001485 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001486 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001487 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001488 final long origId = Binder.clearCallingIdentity();
1489 try {
1490 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001491 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1492 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001493 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001494
1495 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001496 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001497 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001498 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001499 if (recentsAnimationRunner == null) {
1500 anim.preloadRecentsActivity();
1501 } else {
1502 anim.startRecentsActivity(recentsAnimationRunner);
1503 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001504 }
1505 } finally {
1506 Binder.restoreCallingIdentity(origId);
1507 }
1508 }
1509
1510 @Override
1511 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001512 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001513 "startActivityFromRecents()");
1514
1515 final int callingPid = Binder.getCallingPid();
1516 final int callingUid = Binder.getCallingUid();
1517 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1518 final long origId = Binder.clearCallingIdentity();
1519 try {
1520 synchronized (mGlobalLock) {
1521 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1522 safeOptions);
1523 }
1524 } finally {
1525 Binder.restoreCallingIdentity(origId);
1526 }
1527 }
1528
1529 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001530 * Public API to check if the client is allowed to start an activity on specified display.
1531 *
1532 * If the target display is private or virtual, some restrictions will apply.
1533 *
1534 * @param displayId Target display id.
1535 * @param intent Intent used to launch the activity.
1536 * @param resolvedType The MIME type of the intent.
1537 * @param userId The id of the user for whom the call is made.
1538 * @return {@code true} if a call to start an activity on the target display should succeed and
1539 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1540 */
1541 @Override
1542 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1543 String resolvedType, int userId) {
1544 final int callingUid = Binder.getCallingUid();
1545 final int callingPid = Binder.getCallingPid();
1546 final long origId = Binder.clearCallingIdentity();
1547
1548 try {
1549 // Collect information about the target of the Intent.
1550 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1551 0 /* startFlags */, null /* profilerInfo */, userId,
1552 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1553 UserHandle.USER_NULL));
1554 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1555
1556 synchronized (mGlobalLock) {
1557 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1558 aInfo);
1559 }
1560 } finally {
1561 Binder.restoreCallingIdentity(origId);
1562 }
1563 }
1564
1565 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001566 * This is the internal entry point for handling Activity.finish().
1567 *
1568 * @param token The Binder token referencing the Activity we want to finish.
1569 * @param resultCode Result code, if any, from this Activity.
1570 * @param resultData Result data (Intent), if any, from this Activity.
1571 * @param finishTask Whether to finish the task associated with this Activity.
1572 *
1573 * @return Returns true if the activity successfully finished, or false if it is still running.
1574 */
1575 @Override
1576 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1577 int finishTask) {
1578 // Refuse possible leaked file descriptors
1579 if (resultData != null && resultData.hasFileDescriptors()) {
1580 throw new IllegalArgumentException("File descriptors passed in Intent");
1581 }
1582
1583 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001584 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001585 if (r == null) {
1586 return true;
1587 }
1588 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001589 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001590 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001591 if (rootR == null) {
1592 Slog.w(TAG, "Finishing task with all activities already finished");
1593 }
1594 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1595 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001596 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 return false;
1598 }
1599
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001600 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1601 // We should consolidate.
1602 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001603 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001604 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001605 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001606 if (next != null) {
1607 // ask watcher if this is allowed
1608 boolean resumeOK = true;
1609 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001610 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001611 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001612 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001613 Watchdog.getInstance().setActivityController(null);
1614 }
1615
1616 if (!resumeOK) {
1617 Slog.i(TAG, "Not finishing activity because controller resumed");
1618 return false;
1619 }
1620 }
1621 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001622
1623 // note down that the process has finished an activity and is in background activity
1624 // starts grace period
1625 if (r.app != null) {
1626 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1627 }
1628
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001629 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001630 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001631 try {
1632 boolean res;
1633 final boolean finishWithRootActivity =
1634 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1635 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1636 || (finishWithRootActivity && r == rootR)) {
1637 // If requested, remove the task that is associated to this activity only if it
1638 // was the root activity in the task. The result code and data is ignored
1639 // because we don't support returning them across task boundaries. Also, to
1640 // keep backwards compatibility we remove the task from recents when finishing
1641 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001642 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001643 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001644 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001645 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001646 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001647 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001648 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001649 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001650 if (!res) {
1651 Slog.i(TAG, "Failed to finish by app-request");
1652 }
1653 }
1654 return res;
1655 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001656 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001657 Binder.restoreCallingIdentity(origId);
1658 }
1659 }
1660 }
1661
1662 @Override
1663 public boolean finishActivityAffinity(IBinder token) {
1664 synchronized (mGlobalLock) {
1665 final long origId = Binder.clearCallingIdentity();
1666 try {
1667 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1668 if (r == null) {
1669 return false;
1670 }
1671
1672 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1673 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001674 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001675 return false;
1676 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001677
1678 final PooledFunction p = PooledLambda.obtainFunction(
1679 ActivityRecord::finishIfSameAffinity, r,
1680 PooledLambda.__(ActivityRecord.class));
1681 r.getTask().forAllActivities(
1682 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1683 p.recycle();
1684
Andrii Kuliande93eff2019-07-12 12:21:27 -07001685 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001686 } finally {
1687 Binder.restoreCallingIdentity(origId);
1688 }
1689 }
1690 }
1691
1692 @Override
1693 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1694 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001695 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001696 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001697 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001698 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1699 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001700 return;
1701 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001702 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1703 false /* processPausingActivities */, config);
1704 if (stopProfiling && r.hasProcess()) {
1705 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001706 }
1707 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001708 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001709 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001710 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001711 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001712 }
1713
1714 @Override
1715 public final void activityResumed(IBinder token) {
1716 final long origId = Binder.clearCallingIdentity();
1717 synchronized (mGlobalLock) {
1718 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001719 }
1720 Binder.restoreCallingIdentity(origId);
1721 }
1722
1723 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001724 public final void activityTopResumedStateLost() {
1725 final long origId = Binder.clearCallingIdentity();
1726 synchronized (mGlobalLock) {
1727 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1728 }
1729 Binder.restoreCallingIdentity(origId);
1730 }
1731
1732 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001733 public final void activityPaused(IBinder token) {
1734 final long origId = Binder.clearCallingIdentity();
1735 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001736 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001737 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1738 if (r != null) {
1739 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001740 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001741 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001742 }
1743 Binder.restoreCallingIdentity(origId);
1744 }
1745
1746 @Override
1747 public final void activityStopped(IBinder token, Bundle icicle,
1748 PersistableBundle persistentState, CharSequence description) {
1749 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1750
1751 // Refuse possible leaked file descriptors
1752 if (icicle != null && icicle.hasFileDescriptors()) {
1753 throw new IllegalArgumentException("File descriptors passed in Bundle");
1754 }
1755
1756 final long origId = Binder.clearCallingIdentity();
1757
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001758 String restartingName = null;
1759 int restartingUid = 0;
1760 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001761 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001762 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001763 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001764 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001765 if (r.attachedToProcess()
1766 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1767 // The activity was requested to restart from
1768 // {@link #restartActivityProcessIfVisible}.
1769 restartingName = r.app.mName;
1770 restartingUid = r.app.mUid;
1771 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001772 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001773 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001774 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001775 }
1776
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001777 if (restartingName != null) {
1778 // In order to let the foreground activity can be restarted with its saved state from
1779 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1780 // until the activity reports stopped with the state. And the activity record will be
1781 // kept because the record state is restarting, then the activity will be restarted
1782 // immediately if it is still the top one.
1783 mStackSupervisor.removeRestartTimeouts(r);
1784 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1785 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001786 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001787
1788 Binder.restoreCallingIdentity(origId);
1789 }
1790
1791 @Override
1792 public final void activityDestroyed(IBinder token) {
1793 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1794 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001795 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001796 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001797 try {
1798 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1799 if (activity != null) {
1800 activity.destroyed("activityDestroyed");
1801 }
1802 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001803 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001804 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001805 }
1806 }
1807 }
1808
1809 @Override
1810 public final void activityRelaunched(IBinder token) {
1811 final long origId = Binder.clearCallingIdentity();
1812 synchronized (mGlobalLock) {
1813 mStackSupervisor.activityRelaunchedLocked(token);
1814 }
1815 Binder.restoreCallingIdentity(origId);
1816 }
1817
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001818 @Override
1819 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1820 synchronized (mGlobalLock) {
1821 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1822 if (r == null) {
1823 return;
1824 }
1825 final long origId = Binder.clearCallingIdentity();
1826 try {
1827 r.setRequestedOrientation(requestedOrientation);
1828 } finally {
1829 Binder.restoreCallingIdentity(origId);
1830 }
1831 }
1832 }
1833
1834 @Override
1835 public int getRequestedOrientation(IBinder token) {
1836 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001837 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1838 return (r != null)
1839 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001840 }
1841 }
1842
1843 @Override
1844 public void setImmersive(IBinder token, boolean immersive) {
1845 synchronized (mGlobalLock) {
1846 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1847 if (r == null) {
1848 throw new IllegalArgumentException();
1849 }
1850 r.immersive = immersive;
1851
1852 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001853 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001854 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001855 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001856 }
1857 }
1858 }
1859
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001860 void applyUpdateLockStateLocked(ActivityRecord r) {
1861 // Modifications to the UpdateLock state are done on our handler, outside
1862 // the activity manager's locks. The new state is determined based on the
1863 // state *now* of the relevant activity record. The object is passed to
1864 // the handler solely for logging detail, not to be consulted/modified.
1865 final boolean nextState = r != null && r.immersive;
1866 mH.post(() -> {
1867 if (mUpdateLock.isHeld() != nextState) {
1868 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1869 "Applying new update lock state '" + nextState + "' for " + r);
1870 if (nextState) {
1871 mUpdateLock.acquire();
1872 } else {
1873 mUpdateLock.release();
1874 }
1875 }
1876 });
1877 }
1878
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001879 @Override
1880 public boolean isImmersive(IBinder token) {
1881 synchronized (mGlobalLock) {
1882 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1883 if (r == null) {
1884 throw new IllegalArgumentException();
1885 }
1886 return r.immersive;
1887 }
1888 }
1889
1890 @Override
1891 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001892 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001894 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001895 return (r != null) ? r.immersive : false;
1896 }
1897 }
1898
1899 @Override
1900 public void overridePendingTransition(IBinder token, String packageName,
1901 int enterAnim, int exitAnim) {
1902 synchronized (mGlobalLock) {
1903 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1904 if (self == null) {
1905 return;
1906 }
1907
1908 final long origId = Binder.clearCallingIdentity();
1909
1910 if (self.isState(
1911 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001912 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001913 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001914 }
1915
1916 Binder.restoreCallingIdentity(origId);
1917 }
1918 }
1919
1920 @Override
1921 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001922 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001923 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001924 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001925 if (r == null) {
1926 return ActivityManager.COMPAT_MODE_UNKNOWN;
1927 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001928 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001929 }
1930 }
1931
1932 @Override
1933 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001934 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001936 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001937 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001938 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001939 if (r == null) {
1940 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1941 return;
1942 }
1943 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001944 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 }
1946 }
1947
1948 @Override
1949 public int getLaunchedFromUid(IBinder activityToken) {
1950 ActivityRecord srec;
1951 synchronized (mGlobalLock) {
1952 srec = ActivityRecord.forTokenLocked(activityToken);
1953 }
1954 if (srec == null) {
1955 return -1;
1956 }
1957 return srec.launchedFromUid;
1958 }
1959
1960 @Override
1961 public String getLaunchedFromPackage(IBinder activityToken) {
1962 ActivityRecord srec;
1963 synchronized (mGlobalLock) {
1964 srec = ActivityRecord.forTokenLocked(activityToken);
1965 }
1966 if (srec == null) {
1967 return null;
1968 }
1969 return srec.launchedFromPackage;
1970 }
1971
1972 @Override
1973 public boolean convertFromTranslucent(IBinder token) {
1974 final long origId = Binder.clearCallingIdentity();
1975 try {
1976 synchronized (mGlobalLock) {
1977 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1978 if (r == null) {
1979 return false;
1980 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001981 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001982 }
1983 } finally {
1984 Binder.restoreCallingIdentity(origId);
1985 }
1986 }
1987
1988 @Override
1989 public boolean convertToTranslucent(IBinder token, Bundle options) {
1990 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1991 final long origId = Binder.clearCallingIdentity();
1992 try {
1993 synchronized (mGlobalLock) {
1994 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1995 if (r == null) {
1996 return false;
1997 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001998 final ActivityRecord under = r.getTask().getActivityBelow(r);
1999 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002000 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2001 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002002 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002003 }
2004 } finally {
2005 Binder.restoreCallingIdentity(origId);
2006 }
2007 }
2008
2009 @Override
2010 public void notifyActivityDrawn(IBinder token) {
2011 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2012 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002013 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002014 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002015 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002016 }
2017 }
2018 }
2019
2020 @Override
2021 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2022 synchronized (mGlobalLock) {
2023 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2024 if (r == null) {
2025 return;
2026 }
2027 r.reportFullyDrawnLocked(restoredFromBundle);
2028 }
2029 }
2030
2031 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002032 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002033 synchronized (mGlobalLock) {
2034 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002035 if (stack != null) {
2036 final int displayId = stack.getDisplayId();
2037 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002038 }
2039 return DEFAULT_DISPLAY;
2040 }
2041 }
2042
2043 @Override
2044 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002045 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002046 long ident = Binder.clearCallingIdentity();
2047 try {
2048 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002049 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002050 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002051 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002052 }
2053 return null;
2054 }
2055 } finally {
2056 Binder.restoreCallingIdentity(ident);
2057 }
2058 }
2059
2060 @Override
2061 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002062 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002063 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2064 final long callingId = Binder.clearCallingIdentity();
2065 try {
2066 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002067 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002068 if (stack == null) {
2069 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2070 return;
2071 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002072 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002073 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002074 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002075 }
2076 }
2077 } finally {
2078 Binder.restoreCallingIdentity(callingId);
2079 }
2080 }
2081
2082 @Override
2083 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002084 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2086 final long callingId = Binder.clearCallingIdentity();
2087 try {
2088 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002089 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002090 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002091 if (task == null) {
2092 return;
2093 }
2094 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002095 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002096 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002097 }
2098 }
2099 } finally {
2100 Binder.restoreCallingIdentity(callingId);
2101 }
2102 }
2103
2104 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002105 public void restartActivityProcessIfVisible(IBinder activityToken) {
2106 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2107 final long callingId = Binder.clearCallingIdentity();
2108 try {
2109 synchronized (mGlobalLock) {
2110 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2111 if (r == null) {
2112 return;
2113 }
2114 r.restartProcessIfVisible();
2115 }
2116 } finally {
2117 Binder.restoreCallingIdentity(callingId);
2118 }
2119 }
2120
2121 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002122 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002123 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002124 synchronized (mGlobalLock) {
2125 final long ident = Binder.clearCallingIdentity();
2126 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002127 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002128 "remove-task");
2129 } finally {
2130 Binder.restoreCallingIdentity(ident);
2131 }
2132 }
2133 }
2134
2135 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002136 public void removeAllVisibleRecentTasks() {
2137 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2138 synchronized (mGlobalLock) {
2139 final long ident = Binder.clearCallingIdentity();
2140 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002141 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002142 } finally {
2143 Binder.restoreCallingIdentity(ident);
2144 }
2145 }
2146 }
2147
2148 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002149 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2150 synchronized (mGlobalLock) {
2151 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2152 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002153 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002154 }
2155 }
2156 return false;
2157 }
2158
2159 @Override
2160 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2161 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002162
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002163 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002164 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2165 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002166 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002167 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002168 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002169 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002170 }
2171 }
2172
2173 /**
2174 * Attempts to move a task backwards in z-order (the order of activities within the task is
2175 * unchanged).
2176 *
2177 * There are several possible results of this call:
2178 * - if the task is locked, then we will show the lock toast
2179 * - if there is a task behind the provided task, then that task is made visible and resumed as
2180 * this task is moved to the back
2181 * - otherwise, if there are no other tasks in the stack:
2182 * - if this task is in the pinned stack, then we remove the stack completely, which will
2183 * have the effect of moving the task to the top or bottom of the fullscreen stack
2184 * (depending on whether it is visible)
2185 * - otherwise, we simply return home and hide this task
2186 *
2187 * @param token A reference to the activity we wish to move
2188 * @param nonRoot If false then this only works if the activity is the root
2189 * of a task; if true it will work for any activity in a task.
2190 * @return Returns true if the move completed, false if not.
2191 */
2192 @Override
2193 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002194 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002195 synchronized (mGlobalLock) {
2196 final long origId = Binder.clearCallingIdentity();
2197 try {
2198 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002199 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002200 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002201 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002202 }
2203 } finally {
2204 Binder.restoreCallingIdentity(origId);
2205 }
2206 }
2207 return false;
2208 }
2209
2210 @Override
2211 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002212 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002213 long ident = Binder.clearCallingIdentity();
2214 Rect rect = new Rect();
2215 try {
2216 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002217 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002218 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2219 if (task == null) {
2220 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2221 return rect;
2222 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002223 if (task.getParent() != null) {
2224 rect.set(task.getBounds());
2225 } else if (task.mLastNonFullscreenBounds != null) {
2226 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 }
2228 }
2229 } finally {
2230 Binder.restoreCallingIdentity(ident);
2231 }
2232 return rect;
2233 }
2234
2235 @Override
2236 public ActivityManager.TaskDescription getTaskDescription(int id) {
2237 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002238 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002239 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002240 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002241 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2242 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002243 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002244 }
2245 }
2246 return null;
2247 }
2248
2249 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002250 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2251 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2252 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2253 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2254 return;
2255 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002256 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002257 synchronized (mGlobalLock) {
2258 final long ident = Binder.clearCallingIdentity();
2259 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002260 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002261 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002262 if (task == null) {
2263 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2264 return;
2265 }
2266
2267 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2268 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2269
2270 if (!task.isActivityTypeStandardOrUndefined()) {
2271 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2272 + " non-standard task " + taskId + " to windowing mode="
2273 + windowingMode);
2274 }
2275
2276 final ActivityStack stack = task.getStack();
2277 if (toTop) {
2278 stack.moveToFront("setTaskWindowingMode", task);
2279 }
2280 stack.setWindowingMode(windowingMode);
2281 } finally {
2282 Binder.restoreCallingIdentity(ident);
2283 }
2284 }
2285 }
2286
2287 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002288 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002289 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002290 ActivityRecord r = getCallingRecordLocked(token);
2291 return r != null ? r.info.packageName : null;
2292 }
2293 }
2294
2295 @Override
2296 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002297 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002298 ActivityRecord r = getCallingRecordLocked(token);
2299 return r != null ? r.intent.getComponent() : null;
2300 }
2301 }
2302
2303 private ActivityRecord getCallingRecordLocked(IBinder token) {
2304 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2305 if (r == null) {
2306 return null;
2307 }
2308 return r.resultTo;
2309 }
2310
2311 @Override
2312 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002313 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002314
2315 synchronized (mGlobalLock) {
2316 final long origId = Binder.clearCallingIdentity();
2317 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002318 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002319 } finally {
2320 Binder.restoreCallingIdentity(origId);
2321 }
2322 }
2323 }
2324
Mark Renouf446251d2019-04-26 10:22:41 -04002325 @Override
2326 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2327 synchronized (mGlobalLock) {
2328 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2329 if (r == null) {
2330 return;
2331 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002332 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002333 if (stack != null && stack.isSingleTaskInstance()) {
2334 // Single-task stacks are used for activities which are presented in floating
2335 // windows above full screen activities. Instead of directly finishing the
2336 // task, a task change listener is used to notify SystemUI so the action can be
2337 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002338 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002339 mTaskChangeNotificationController
2340 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2341 } else {
2342 try {
2343 callback.requestFinish();
2344 } catch (RemoteException e) {
2345 Slog.e(TAG, "Failed to invoke request finish callback", e);
2346 }
2347 }
2348 }
2349 }
2350
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002351 /**
2352 * TODO: Add mController hook
2353 */
2354 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002355 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2356 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002357 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002358
2359 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2360 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002361 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2362 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002363 }
2364 }
2365
Ricky Waiaca8a772019-04-04 16:01:06 +01002366 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2367 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002369 final int callingPid = Binder.getCallingPid();
2370 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002371 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002372 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002373 SafeActivityOptions.abort(options);
2374 return;
2375 }
2376 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002377 WindowProcessController callerApp = null;
2378 if (appThread != null) {
2379 callerApp = getProcessController(appThread);
2380 }
2381 final ActivityStarter starter = getActivityStartController().obtainStarter(
2382 null /* intent */, "moveTaskToFront");
2383 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2384 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002385 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002386 return;
2387 }
2388 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002389 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002390 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002391 if (task == null) {
2392 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002393 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002394 return;
2395 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002396 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002397 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002398 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002399 return;
2400 }
2401 ActivityOptions realOptions = options != null
2402 ? options.getOptions(mStackSupervisor)
2403 : null;
2404 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2405 false /* forceNonResizable */);
2406
Wale Ogunwale21e06482019-11-18 05:14:15 -08002407 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002408 if (topActivity != null) {
2409
2410 // We are reshowing a task, use a starting window to hide the initial draw delay
2411 // so the transition can start earlier.
2412 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2413 true /* taskSwitch */, fromRecents);
2414 }
2415 } finally {
2416 Binder.restoreCallingIdentity(origId);
2417 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002418 }
2419
Ricky Waiaca8a772019-04-04 16:01:06 +01002420 /**
2421 * Return true if callingUid is system, or packageName belongs to that callingUid.
2422 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002423 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002424 try {
2425 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2426 if (packageName == null) {
2427 return false;
2428 }
2429 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2430 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2431 UserHandle.getUserId(callingUid));
2432 return UserHandle.isSameApp(callingUid, uid);
2433 }
2434 } catch (RemoteException e) {
2435 // Should not happen
2436 }
2437 return true;
2438 }
2439
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002440 /**
2441 * Checks that the provided package name matches the current calling UID, throws a security
2442 * exception if it doesn't.
2443 */
2444 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2445 final int callingUid = Binder.getCallingUid();
2446 if (isSameApp(callingUid, packageName)) {
2447 return;
2448 }
2449 final String msg = "Permission Denial: package=" + packageName
2450 + " does not belong to uid=" + callingUid;
2451 Slog.w(TAG, msg);
2452 throw new SecurityException(msg);
2453 }
2454
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002455 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2456 int callingPid, int callingUid, String name) {
2457 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2458 return true;
2459 }
2460
2461 if (getRecentTasks().isCallerRecents(sourceUid)) {
2462 return true;
2463 }
2464
2465 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2466 if (perm == PackageManager.PERMISSION_GRANTED) {
2467 return true;
2468 }
2469 if (checkAllowAppSwitchUid(sourceUid)) {
2470 return true;
2471 }
2472
2473 // If the actual IPC caller is different from the logical source, then
2474 // also see if they are allowed to control app switches.
2475 if (callingUid != -1 && callingUid != sourceUid) {
2476 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2477 if (perm == PackageManager.PERMISSION_GRANTED) {
2478 return true;
2479 }
2480 if (checkAllowAppSwitchUid(callingUid)) {
2481 return true;
2482 }
2483 }
2484
2485 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2486 return false;
2487 }
2488
2489 private boolean checkAllowAppSwitchUid(int uid) {
2490 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2491 if (types != null) {
2492 for (int i = types.size() - 1; i >= 0; i--) {
2493 if (types.valueAt(i).intValue() == uid) {
2494 return true;
2495 }
2496 }
2497 }
2498 return false;
2499 }
2500
2501 @Override
2502 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2503 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2504 "setActivityController()");
2505 synchronized (mGlobalLock) {
2506 mController = controller;
2507 mControllerIsAMonkey = imAMonkey;
2508 Watchdog.getInstance().setActivityController(controller);
2509 }
2510 }
2511
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002512 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002513 synchronized (mGlobalLock) {
2514 return mController != null && mControllerIsAMonkey;
2515 }
2516 }
2517
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002518 @Override
2519 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2520 synchronized (mGlobalLock) {
2521 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2522 }
2523 }
2524
2525 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002526 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2527 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2528 }
2529
2530 @Override
2531 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2532 @WindowConfiguration.ActivityType int ignoreActivityType,
2533 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2534 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002535 final int callingPid = Binder.getCallingPid();
2536 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002537 final int[] profileIds = getUserManager().getProfileIds(
2538 UserHandle.getUserId(callingUid), true);
2539 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2540 for (int i = 0; i < profileIds.length; i++) {
2541 callingProfileIds.add(profileIds[i]);
2542 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002543 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2544
2545 synchronized (mGlobalLock) {
2546 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2547
Nicholas Sauer0259e532019-08-30 08:24:55 -07002548 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002549 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002550 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002551 }
2552
2553 return list;
2554 }
2555
2556 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002557 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2558 synchronized (mGlobalLock) {
2559 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002560 try {
2561 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2562 if (r == null) return;
2563
2564 final PooledConsumer c = PooledLambda.obtainConsumer(
2565 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2566 r, resultWho, requestCode);
2567 // TODO: This should probably only loop over the task since you need to be in the
2568 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002569 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002570 c.recycle();
2571
2572 updateOomAdj();
2573 } finally {
2574 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002575 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002576 }
2577 }
2578
2579 @Override
2580 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002581 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002582 ActivityStack stack = ActivityRecord.getStackLocked(token);
2583 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002584 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002585 }
2586 return false;
2587 }
2588 }
2589
2590 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002591 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002592 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002593 synchronized (mGlobalLock) {
2594 final long ident = Binder.clearCallingIdentity();
2595 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002596 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002597 if (task == null) {
2598 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2599 return;
2600 }
2601
2602 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2603 + " to stackId=" + stackId + " toTop=" + toTop);
2604
Louis Chang149d5c82019-12-30 09:47:39 +08002605 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002606 if (stack == null) {
2607 throw new IllegalStateException(
2608 "moveTaskToStack: No stack for stackId=" + stackId);
2609 }
2610 if (!stack.isActivityTypeStandardOrUndefined()) {
2611 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2612 + taskId + " to stack " + stackId);
2613 }
2614 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002615 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002616 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2617 }
2618 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2619 "moveTaskToStack");
2620 } finally {
2621 Binder.restoreCallingIdentity(ident);
2622 }
2623 }
2624 }
2625
2626 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002627 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2628 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002629
2630 final long ident = Binder.clearCallingIdentity();
2631 try {
2632 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002633 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Evan Roskydbe2ce52019-07-18 11:13:17 -07002634 if (stack == null) {
2635 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2636 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002637 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002638 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2639 throw new IllegalArgumentException("Stack: " + stackId
2640 + " doesn't support animated resize.");
2641 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002642 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002643 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002644 }
2645 } finally {
2646 Binder.restoreCallingIdentity(ident);
2647 }
2648 }
2649
wilsonshih5c4cf522019-01-25 09:03:47 +08002650 @Override
2651 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2652 int animationDuration) {
2653 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2654
2655 final long ident = Binder.clearCallingIdentity();
2656 try {
2657 synchronized (mGlobalLock) {
2658 if (xOffset == 0 && yOffset == 0) {
2659 return;
2660 }
Louis Chang149d5c82019-12-30 09:47:39 +08002661 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
wilsonshih5c4cf522019-01-25 09:03:47 +08002662 if (stack == null) {
2663 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2664 return;
2665 }
2666 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2667 throw new IllegalArgumentException("Stack: " + stackId
2668 + " doesn't support animated resize.");
2669 }
2670 final Rect destBounds = new Rect();
2671 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002672 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002673 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2674 return;
2675 }
2676 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002677 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002678 animationDuration, false /* fromFullscreen */);
2679 }
2680 } finally {
2681 Binder.restoreCallingIdentity(ident);
2682 }
2683 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002684 /**
2685 * Moves the specified task to the primary-split-screen stack.
2686 *
2687 * @param taskId Id of task to move.
2688 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2689 * exist already. See
2690 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2691 * and
2692 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2693 * @param toTop If the task and stack should be moved to the top.
2694 * @param animate Whether we should play an animation for the moving the task.
2695 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2696 * stack. Pass {@code null} to use default bounds.
2697 * @param showRecents If the recents activity should be shown on the other side of the task
2698 * going into split-screen mode.
2699 */
2700 @Override
2701 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2702 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002703 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002704 "setTaskWindowingModeSplitScreenPrimary()");
2705 synchronized (mGlobalLock) {
2706 final long ident = Binder.clearCallingIdentity();
2707 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002708 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002709 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002710 if (task == null) {
2711 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2712 return false;
2713 }
2714 if (DEBUG_STACK) Slog.d(TAG_STACK,
2715 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2716 + " to createMode=" + createMode + " toTop=" + toTop);
2717 if (!task.isActivityTypeStandardOrUndefined()) {
2718 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2719 + " non-standard task " + taskId + " to split-screen windowing mode");
2720 }
2721
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002722 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002723 final int windowingMode = task.getWindowingMode();
2724 final ActivityStack stack = task.getStack();
2725 if (toTop) {
2726 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2727 }
2728 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002729 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2730 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002731 return windowingMode != task.getWindowingMode();
2732 } finally {
2733 Binder.restoreCallingIdentity(ident);
2734 }
2735 }
2736 }
2737
2738 /**
2739 * Removes stacks in the input windowing modes from the system if they are of activity type
2740 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2741 */
2742 @Override
2743 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002744 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002745 "removeStacksInWindowingModes()");
2746
2747 synchronized (mGlobalLock) {
2748 final long ident = Binder.clearCallingIdentity();
2749 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002750 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002751 } finally {
2752 Binder.restoreCallingIdentity(ident);
2753 }
2754 }
2755 }
2756
2757 @Override
2758 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002759 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002760 "removeStacksWithActivityTypes()");
2761
2762 synchronized (mGlobalLock) {
2763 final long ident = Binder.clearCallingIdentity();
2764 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002765 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002766 } finally {
2767 Binder.restoreCallingIdentity(ident);
2768 }
2769 }
2770 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002771
2772 @Override
2773 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2774 int userId) {
2775 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002776 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2777 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002778 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002779 final boolean detailed = checkGetTasksPermission(
2780 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2781 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002782 == PackageManager.PERMISSION_GRANTED;
2783
2784 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002785 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002786 callingUid);
2787 }
2788 }
2789
2790 @Override
2791 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002792 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002793 long ident = Binder.clearCallingIdentity();
2794 try {
2795 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002796 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002797 }
2798 } finally {
2799 Binder.restoreCallingIdentity(ident);
2800 }
2801 }
2802
2803 @Override
2804 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002805 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002806 long ident = Binder.clearCallingIdentity();
2807 try {
2808 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002809 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002810 }
2811 } finally {
2812 Binder.restoreCallingIdentity(ident);
2813 }
2814 }
2815
2816 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002817 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2818 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2819 long ident = Binder.clearCallingIdentity();
2820 try {
2821 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002822 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002823 }
2824 } finally {
2825 Binder.restoreCallingIdentity(ident);
2826 }
2827 }
2828
2829 @Override
2830 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2831 int displayId) {
2832 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2833 long ident = Binder.clearCallingIdentity();
2834 try {
2835 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002836 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002837 }
2838 } finally {
2839 Binder.restoreCallingIdentity(ident);
2840 }
2841 }
2842
2843 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002844 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002845 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002846 final long callingUid = Binder.getCallingUid();
2847 final long origId = Binder.clearCallingIdentity();
2848 try {
2849 synchronized (mGlobalLock) {
2850 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002851 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002852 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2853 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2854 }
2855 } finally {
2856 Binder.restoreCallingIdentity(origId);
2857 }
2858 }
2859
2860 @Override
2861 public void startLockTaskModeByToken(IBinder token) {
2862 synchronized (mGlobalLock) {
2863 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2864 if (r == null) {
2865 return;
2866 }
Louis Changcdec0802019-11-11 11:45:07 +08002867 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002868 }
2869 }
2870
2871 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002872 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002873 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002874 // This makes inner call to look as if it was initiated by system.
2875 long ident = Binder.clearCallingIdentity();
2876 try {
2877 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002878 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002879 MATCH_TASK_IN_STACKS_ONLY);
2880 if (task == null) {
2881 return;
2882 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883
2884 // When starting lock task mode the stack must be in front and focused
2885 task.getStack().moveToFront("startSystemLockTaskMode");
2886 startLockTaskModeLocked(task, true /* isSystemCaller */);
2887 }
2888 } finally {
2889 Binder.restoreCallingIdentity(ident);
2890 }
2891 }
2892
2893 @Override
2894 public void stopLockTaskModeByToken(IBinder token) {
2895 synchronized (mGlobalLock) {
2896 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2897 if (r == null) {
2898 return;
2899 }
Louis Changcdec0802019-11-11 11:45:07 +08002900 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002901 }
2902 }
2903
2904 /**
2905 * This API should be called by SystemUI only when user perform certain action to dismiss
2906 * lock task mode. We should only dismiss pinned lock task mode in this case.
2907 */
2908 @Override
2909 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002910 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002911 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2912 }
2913
Louis Changcdec0802019-11-11 11:45:07 +08002914 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002915 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2916 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2917 return;
2918 }
2919
Louis Chang149d5c82019-12-30 09:47:39 +08002920 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002921 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002922 throw new IllegalArgumentException("Invalid task, not in foreground");
2923 }
2924
2925 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2926 // system or a specific app.
2927 // * System-initiated requests will only start the pinned mode (screen pinning)
2928 // * App-initiated requests
2929 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2930 // - will start the pinned mode, otherwise
2931 final int callingUid = Binder.getCallingUid();
2932 long ident = Binder.clearCallingIdentity();
2933 try {
2934 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002935 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002936
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002937 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002938 } finally {
2939 Binder.restoreCallingIdentity(ident);
2940 }
2941 }
2942
Louis Changcdec0802019-11-11 11:45:07 +08002943 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002944 final int callingUid = Binder.getCallingUid();
2945 long ident = Binder.clearCallingIdentity();
2946 try {
2947 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002948 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002949 }
2950 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2951 // task and jumping straight into a call in the case of emergency call back.
2952 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2953 if (tm != null) {
2954 tm.showInCallScreen(false);
2955 }
2956 } finally {
2957 Binder.restoreCallingIdentity(ident);
2958 }
2959 }
2960
2961 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002962 public void updateLockTaskPackages(int userId, String[] packages) {
2963 final int callingUid = Binder.getCallingUid();
2964 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2965 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2966 "updateLockTaskPackages()");
2967 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002968 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002969 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2970 + Arrays.toString(packages));
2971 getLockTaskController().updateLockTaskPackages(userId, packages);
2972 }
2973 }
2974
2975 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002976 public boolean isInLockTaskMode() {
2977 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2978 }
2979
2980 @Override
2981 public int getLockTaskModeState() {
2982 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002983 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002984 }
2985 }
2986
2987 @Override
2988 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2989 synchronized (mGlobalLock) {
2990 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2991 if (r != null) {
2992 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08002993 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002994 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002995 }
2996 }
2997 }
2998
2999 @Override
3000 public Bundle getActivityOptions(IBinder token) {
3001 final long origId = Binder.clearCallingIdentity();
3002 try {
3003 synchronized (mGlobalLock) {
3004 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3005 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003006 final ActivityOptions activityOptions = r.takeOptionsLocked(
3007 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003008 return activityOptions == null ? null : activityOptions.toBundle();
3009 }
3010 return null;
3011 }
3012 } finally {
3013 Binder.restoreCallingIdentity(origId);
3014 }
3015 }
3016
3017 @Override
3018 public List<IBinder> getAppTasks(String callingPackage) {
3019 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003020 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003021 long ident = Binder.clearCallingIdentity();
3022 try {
3023 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003024 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003025 }
3026 } finally {
3027 Binder.restoreCallingIdentity(ident);
3028 }
3029 }
3030
3031 @Override
3032 public void finishVoiceTask(IVoiceInteractionSession session) {
3033 synchronized (mGlobalLock) {
3034 final long origId = Binder.clearCallingIdentity();
3035 try {
3036 // TODO: VI Consider treating local voice interactions and voice tasks
3037 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003038 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003039 } finally {
3040 Binder.restoreCallingIdentity(origId);
3041 }
3042 }
3043
3044 }
3045
3046 @Override
3047 public boolean isTopOfTask(IBinder token) {
3048 synchronized (mGlobalLock) {
3049 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003050 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003051 }
3052 }
3053
3054 @Override
3055 public void notifyLaunchTaskBehindComplete(IBinder token) {
3056 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3057 }
3058
3059 @Override
3060 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003061 mH.post(() -> {
3062 synchronized (mGlobalLock) {
3063 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003064 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003065 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003066 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003067 } catch (RemoteException e) {
3068 }
3069 }
3070 }
3071
3072 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003073 }
3074
3075 /** Called from an app when assist data is ready. */
3076 @Override
3077 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3078 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003079 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003080 synchronized (pae) {
3081 pae.result = extras;
3082 pae.structure = structure;
3083 pae.content = content;
3084 if (referrer != null) {
3085 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3086 }
3087 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003088 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003089 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003090 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003091 structure.setHomeActivity(pae.isHome);
3092 }
3093 pae.haveResult = true;
3094 pae.notifyAll();
3095 if (pae.intent == null && pae.receiver == null) {
3096 // Caller is just waiting for the result.
3097 return;
3098 }
3099 }
3100 // We are now ready to launch the assist activity.
3101 IAssistDataReceiver sendReceiver = null;
3102 Bundle sendBundle = null;
3103 synchronized (mGlobalLock) {
3104 buildAssistBundleLocked(pae, extras);
3105 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003106 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003107 if (!exists) {
3108 // Timed out.
3109 return;
3110 }
3111
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003112 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003113 // Caller wants result sent back to them.
3114 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003115 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003116 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003117 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3118 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003119 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3120 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3121 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3122 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3123 }
3124 }
3125 if (sendReceiver != null) {
3126 try {
3127 sendReceiver.onHandleAssistData(sendBundle);
3128 } catch (RemoteException e) {
3129 }
3130 return;
3131 }
3132
3133 final long ident = Binder.clearCallingIdentity();
3134 try {
3135 if (TextUtils.equals(pae.intent.getAction(),
3136 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003137 // Start voice interaction through VoiceInteractionManagerService.
3138 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3139 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003140 } else {
3141 pae.intent.replaceExtras(pae.extras);
3142 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3143 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3144 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003145 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003146
3147 try {
3148 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3149 } catch (ActivityNotFoundException e) {
3150 Slog.w(TAG, "No activity to handle assist action.", e);
3151 }
3152 }
3153 } finally {
3154 Binder.restoreCallingIdentity(ident);
3155 }
3156 }
3157
3158 @Override
3159 public int addAppTask(IBinder activityToken, Intent intent,
3160 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3161 final int callingUid = Binder.getCallingUid();
3162 final long callingIdent = Binder.clearCallingIdentity();
3163
3164 try {
3165 synchronized (mGlobalLock) {
3166 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3167 if (r == null) {
3168 throw new IllegalArgumentException("Activity does not exist; token="
3169 + activityToken);
3170 }
3171 ComponentName comp = intent.getComponent();
3172 if (comp == null) {
3173 throw new IllegalArgumentException("Intent " + intent
3174 + " must specify explicit component");
3175 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003176 if (thumbnail.getWidth() != mThumbnailWidth
3177 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003178 throw new IllegalArgumentException("Bad thumbnail size: got "
3179 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003180 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003181 }
3182 if (intent.getSelector() != null) {
3183 intent.setSelector(null);
3184 }
3185 if (intent.getSourceBounds() != null) {
3186 intent.setSourceBounds(null);
3187 }
3188 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3189 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3190 // The caller has added this as an auto-remove task... that makes no
3191 // sense, so turn off auto-remove.
3192 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3193 }
3194 }
3195 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3196 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3197 if (ainfo.applicationInfo.uid != callingUid) {
3198 throw new SecurityException(
3199 "Can't add task for another application: target uid="
3200 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3201 }
3202
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003203 final ActivityStack stack = r.getRootTask();
Louis Changcdec0802019-11-11 11:45:07 +08003204 final Task task = stack.createTask(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08003205 mStackSupervisor.getNextTaskIdForUser(r.mUserId), ainfo, intent, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003206 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003207 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003208 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003209 return INVALID_TASK_ID;
3210 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003211 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003212
3213 // TODO: Send the thumbnail to WM to store it.
3214
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003215 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003216 }
3217 } finally {
3218 Binder.restoreCallingIdentity(callingIdent);
3219 }
3220 }
3221
3222 @Override
3223 public Point getAppTaskThumbnailSize() {
3224 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003225 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003226 }
3227 }
3228
3229 @Override
3230 public void setTaskResizeable(int taskId, int resizeableMode) {
3231 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003232 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003233 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3234 if (task == null) {
3235 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3236 return;
3237 }
3238 task.setResizeMode(resizeableMode);
3239 }
3240 }
3241
3242 @Override
3243 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003244 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003245 long ident = Binder.clearCallingIdentity();
3246 try {
3247 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003248 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003249 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003250 if (task == null) {
3251 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3252 return;
3253 }
3254 // Place the task in the right stack if it isn't there already based on
3255 // the requested bounds.
3256 // The stack transition logic is:
3257 // - a null bounds on a freeform task moves that task to fullscreen
3258 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3259 // that task to freeform
3260 // - otherwise the task is not moved
3261 ActivityStack stack = task.getStack();
3262 if (!task.getWindowConfiguration().canResizeTask()) {
3263 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3264 }
3265 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3266 stack = stack.getDisplay().getOrCreateStack(
3267 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3268 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3269 stack = stack.getDisplay().getOrCreateStack(
3270 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3271 }
3272
3273 // Reparent the task to the right stack if necessary
3274 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3275 if (stack != task.getStack()) {
3276 // Defer resume until the task is resized below
3277 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3278 DEFER_RESUME, "resizeTask");
3279 preserveWindow = false;
3280 }
3281
3282 // After reparenting (which only resizes the task to the stack bounds), resize the
3283 // task to the actual bounds provided
3284 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3285 }
3286 } finally {
3287 Binder.restoreCallingIdentity(ident);
3288 }
3289 }
3290
3291 @Override
3292 public boolean releaseActivityInstance(IBinder token) {
3293 synchronized (mGlobalLock) {
3294 final long origId = Binder.clearCallingIdentity();
3295 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003296 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3297 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003298 return false;
3299 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003300 r.destroyImmediately(true /* removeFromApp */, "app-req");
3301 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003302 } finally {
3303 Binder.restoreCallingIdentity(origId);
3304 }
3305 }
3306 }
3307
3308 @Override
3309 public void releaseSomeActivities(IApplicationThread appInt) {
3310 synchronized (mGlobalLock) {
3311 final long origId = Binder.clearCallingIdentity();
3312 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003313 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003314 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003315 } finally {
3316 Binder.restoreCallingIdentity(origId);
3317 }
3318 }
3319 }
3320
3321 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003322 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003323 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003324 != PackageManager.PERMISSION_GRANTED) {
3325 throw new SecurityException("Requires permission "
3326 + android.Manifest.permission.DEVICE_POWER);
3327 }
3328
3329 synchronized (mGlobalLock) {
3330 long ident = Binder.clearCallingIdentity();
3331 if (mKeyguardShown != keyguardShowing) {
3332 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003333 final Message msg = PooledLambda.obtainMessage(
3334 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3335 keyguardShowing);
3336 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003337 }
3338 try {
wilsonshih177261f2019-02-22 12:02:18 +08003339 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003340 } finally {
3341 Binder.restoreCallingIdentity(ident);
3342 }
3343 }
3344
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003345 mH.post(() -> {
3346 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3347 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3348 }
3349 });
3350 }
3351
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003352 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003353 mH.post(() -> {
3354 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3355 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3356 }
3357 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003358 }
3359
3360 @Override
3361 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003362 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3363 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003364
3365 final File passedIconFile = new File(filePath);
3366 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3367 passedIconFile.getName());
3368 if (!legitIconFile.getPath().equals(filePath)
3369 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3370 throw new IllegalArgumentException("Bad file path: " + filePath
3371 + " passed for userId " + userId);
3372 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003373 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003374 }
3375
3376 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003377 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003378 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003379 synchronized (mGlobalLock) {
3380 final long ident = Binder.clearCallingIdentity();
3381 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003382 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383 if (stack == null) {
3384 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3385 return;
3386 }
3387 if (!stack.isActivityTypeStandardOrUndefined()) {
3388 throw new IllegalArgumentException(
3389 "Removing non-standard stack is not allowed.");
3390 }
3391 mStackSupervisor.removeStack(stack);
3392 } finally {
3393 Binder.restoreCallingIdentity(ident);
3394 }
3395 }
3396 }
3397
3398 @Override
3399 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003400 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003401
3402 synchronized (mGlobalLock) {
3403 final long ident = Binder.clearCallingIdentity();
3404 try {
3405 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3406 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003407 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003408 } finally {
3409 Binder.restoreCallingIdentity(ident);
3410 }
3411 }
3412 }
3413
3414 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003415 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416 synchronized (mGlobalLock) {
3417 long ident = Binder.clearCallingIdentity();
3418 try {
3419 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3420 if (r == null) {
3421 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003422 "toggleFreeformWindowingMode: No activity record matching token="
3423 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 }
3425
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003426 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003427 if (stack == null) {
3428 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3429 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003430 }
3431
Yunfan Chend967af82019-01-17 18:30:18 +09003432 if (!stack.inFreeformWindowingMode()
3433 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3434 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3435 + "toggle between fullscreen and freeform.");
3436 }
3437
3438 if (stack.inFreeformWindowingMode()) {
3439 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003440 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003441 throw new IllegalStateException("Size-compat windows are currently not"
3442 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003443 } else if (stack.getParent().inFreeformWindowingMode()) {
3444 // If the window is on a freeform display, set it to undefined. It will be
3445 // resolved to freeform and it can adjust windowing mode when the display mode
3446 // changes in runtime.
3447 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003448 } else {
3449 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3450 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003451 } finally {
3452 Binder.restoreCallingIdentity(ident);
3453 }
3454 }
3455 }
3456
3457 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3458 @Override
3459 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003460 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003461 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003462 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003463 }
3464
3465 /** Unregister a task stack listener so that it stops receiving callbacks. */
3466 @Override
3467 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003468 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003469 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003470 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003471 }
3472
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003473 @Override
3474 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3475 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3476 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3477 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3478 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3479 }
3480
3481 @Override
3482 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3483 IBinder activityToken, int flags) {
3484 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3485 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3486 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3487 }
3488
3489 @Override
3490 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3491 Bundle args) {
3492 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3493 true /* focused */, true /* newSessionId */, userHandle, args,
3494 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3495 }
3496
3497 @Override
3498 public Bundle getAssistContextExtras(int requestType) {
3499 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3500 null, null, true /* focused */, true /* newSessionId */,
3501 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3502 if (pae == null) {
3503 return null;
3504 }
3505 synchronized (pae) {
3506 while (!pae.haveResult) {
3507 try {
3508 pae.wait();
3509 } catch (InterruptedException e) {
3510 }
3511 }
3512 }
3513 synchronized (mGlobalLock) {
3514 buildAssistBundleLocked(pae, pae.result);
3515 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003516 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003517 }
3518 return pae.extras;
3519 }
3520
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003521 /**
3522 * Binder IPC calls go through the public entry point.
3523 * This can be called with or without the global lock held.
3524 */
3525 private static int checkCallingPermission(String permission) {
3526 return checkPermission(
3527 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3528 }
3529
3530 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003531 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003532 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3533 mAmInternal.enforceCallingPermission(permission, func);
3534 }
3535 }
3536
3537 @VisibleForTesting
3538 int checkGetTasksPermission(String permission, int pid, int uid) {
3539 return checkPermission(permission, pid, uid);
3540 }
3541
3542 static int checkPermission(String permission, int pid, int uid) {
3543 if (permission == null) {
3544 return PackageManager.PERMISSION_DENIED;
3545 }
3546 return checkComponentPermission(permission, pid, uid, -1, true);
3547 }
3548
Wale Ogunwale214f3482018-10-04 11:00:47 -07003549 public static int checkComponentPermission(String permission, int pid, int uid,
3550 int owningUid, boolean exported) {
3551 return ActivityManagerService.checkComponentPermission(
3552 permission, pid, uid, owningUid, exported);
3553 }
3554
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003555 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3556 if (getRecentTasks().isCallerRecents(callingUid)) {
3557 // Always allow the recents component to get tasks
3558 return true;
3559 }
3560
3561 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3562 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3563 if (!allowed) {
3564 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3565 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3566 // Temporary compatibility: some existing apps on the system image may
3567 // still be requesting the old permission and not switched to the new
3568 // one; if so, we'll still allow them full access. This means we need
3569 // to see if they are holding the old permission and are a system app.
3570 try {
3571 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3572 allowed = true;
3573 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3574 + " is using old GET_TASKS but privileged; allowing");
3575 }
3576 } catch (RemoteException e) {
3577 }
3578 }
3579 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3580 + " does not hold REAL_GET_TASKS; limiting output");
3581 }
3582 return allowed;
3583 }
3584
Nicholas Sauer0259e532019-08-30 08:24:55 -07003585 boolean isCrossUserAllowed(int pid, int uid) {
3586 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3587 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3588 }
3589
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003590 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3591 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3592 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3593 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003594 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003595 "enqueueAssistContext()");
3596
3597 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003598 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003599 if (activity == null) {
3600 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3601 return null;
3602 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003603 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003604 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3605 return null;
3606 }
3607 if (focused) {
3608 if (activityToken != null) {
3609 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3610 if (activity != caller) {
3611 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3612 + " is not current top " + activity);
3613 return null;
3614 }
3615 }
3616 } else {
3617 activity = ActivityRecord.forTokenLocked(activityToken);
3618 if (activity == null) {
3619 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3620 + " couldn't be found");
3621 return null;
3622 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003623 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003624 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3625 return null;
3626 }
3627 }
3628
3629 PendingAssistExtras pae;
3630 Bundle extras = new Bundle();
3631 if (args != null) {
3632 extras.putAll(args);
3633 }
3634 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003635 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003636
3637 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3638 userHandle);
3639 pae.isHome = activity.isActivityTypeHome();
3640
3641 // Increment the sessionId if necessary
3642 if (newSessionId) {
3643 mViSessionId++;
3644 }
3645 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003646 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3647 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003648 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003649 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003650 } catch (RemoteException e) {
3651 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3652 return null;
3653 }
3654 return pae;
3655 }
3656 }
3657
3658 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3659 if (result != null) {
3660 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3661 }
3662 if (pae.hint != null) {
3663 pae.extras.putBoolean(pae.hint, true);
3664 }
3665 }
3666
3667 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3668 IAssistDataReceiver receiver;
3669 synchronized (mGlobalLock) {
3670 mPendingAssistExtras.remove(pae);
3671 receiver = pae.receiver;
3672 }
3673 if (receiver != null) {
3674 // Caller wants result sent back to them.
3675 Bundle sendBundle = new Bundle();
3676 // At least return the receiver extras
3677 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3678 try {
3679 pae.receiver.onHandleAssistData(sendBundle);
3680 } catch (RemoteException e) {
3681 }
3682 }
3683 }
3684
3685 public class PendingAssistExtras extends Binder implements Runnable {
3686 public final ActivityRecord activity;
3687 public boolean isHome;
3688 public final Bundle extras;
3689 public final Intent intent;
3690 public final String hint;
3691 public final IAssistDataReceiver receiver;
3692 public final int userHandle;
3693 public boolean haveResult = false;
3694 public Bundle result = null;
3695 public AssistStructure structure = null;
3696 public AssistContent content = null;
3697 public Bundle receiverExtras;
3698
3699 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3700 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3701 int _userHandle) {
3702 activity = _activity;
3703 extras = _extras;
3704 intent = _intent;
3705 hint = _hint;
3706 receiver = _receiver;
3707 receiverExtras = _receiverExtras;
3708 userHandle = _userHandle;
3709 }
3710
3711 @Override
3712 public void run() {
3713 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3714 synchronized (this) {
3715 haveResult = true;
3716 notifyAll();
3717 }
3718 pendingAssistExtrasTimedOut(this);
3719 }
3720 }
3721
3722 @Override
3723 public boolean isAssistDataAllowedOnCurrentActivity() {
3724 int userId;
3725 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003726 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003727 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3728 return false;
3729 }
3730
Wale Ogunwale21e06482019-11-18 05:14:15 -08003731 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003732 if (activity == null) {
3733 return false;
3734 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003735 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003736 }
3737 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3738 }
3739
3740 @Override
3741 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3742 long ident = Binder.clearCallingIdentity();
3743 try {
3744 synchronized (mGlobalLock) {
3745 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003746 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003747 if (top != caller) {
3748 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3749 + " is not current top " + top);
3750 return false;
3751 }
3752 if (!top.nowVisible) {
3753 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3754 + " is not visible");
3755 return false;
3756 }
3757 }
3758 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3759 token);
3760 } finally {
3761 Binder.restoreCallingIdentity(ident);
3762 }
3763 }
3764
3765 @Override
3766 public boolean isRootVoiceInteraction(IBinder token) {
3767 synchronized (mGlobalLock) {
3768 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3769 if (r == null) {
3770 return false;
3771 }
3772 return r.rootVoiceInteraction;
3773 }
3774 }
3775
Wale Ogunwalef6733932018-06-27 05:14:34 -07003776 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3777 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3778 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3779 if (activityToCallback == null) return;
3780 activityToCallback.setVoiceSessionLocked(voiceSession);
3781
3782 // Inform the activity
3783 try {
3784 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3785 voiceInteractor);
3786 long token = Binder.clearCallingIdentity();
3787 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003788 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003789 } finally {
3790 Binder.restoreCallingIdentity(token);
3791 }
3792 // TODO: VI Should we cache the activity so that it's easier to find later
3793 // rather than scan through all the stacks and activities?
3794 } catch (RemoteException re) {
3795 activityToCallback.clearVoiceSessionLocked();
3796 // TODO: VI Should this terminate the voice session?
3797 }
3798 }
3799
3800 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3801 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3802 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3803 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3804 boolean wasRunningVoice = mRunningVoice != null;
3805 mRunningVoice = session;
3806 if (!wasRunningVoice) {
3807 mVoiceWakeLock.acquire();
3808 updateSleepIfNeededLocked();
3809 }
3810 }
3811 }
3812
3813 void finishRunningVoiceLocked() {
3814 if (mRunningVoice != null) {
3815 mRunningVoice = null;
3816 mVoiceWakeLock.release();
3817 updateSleepIfNeededLocked();
3818 }
3819 }
3820
3821 @Override
3822 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3823 synchronized (mGlobalLock) {
3824 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3825 if (keepAwake) {
3826 mVoiceWakeLock.acquire();
3827 } else {
3828 mVoiceWakeLock.release();
3829 }
3830 }
3831 }
3832 }
3833
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003834 @Override
3835 public ComponentName getActivityClassForToken(IBinder token) {
3836 synchronized (mGlobalLock) {
3837 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3838 if (r == null) {
3839 return null;
3840 }
3841 return r.intent.getComponent();
3842 }
3843 }
3844
3845 @Override
3846 public String getPackageForToken(IBinder token) {
3847 synchronized (mGlobalLock) {
3848 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3849 if (r == null) {
3850 return null;
3851 }
3852 return r.packageName;
3853 }
3854 }
3855
3856 @Override
3857 public void showLockTaskEscapeMessage(IBinder token) {
3858 synchronized (mGlobalLock) {
3859 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3860 if (r == null) {
3861 return;
3862 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003863 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003864 }
3865 }
3866
3867 @Override
3868 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003869 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003870 final long token = Binder.clearCallingIdentity();
3871 try {
3872 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003873 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003874 }
3875 } finally {
3876 Binder.restoreCallingIdentity(token);
3877 }
3878 }
3879
3880 /**
3881 * Try to place task to provided position. The final position might be different depending on
3882 * current user and stacks state. The task will be moved to target stack if it's currently in
3883 * different stack.
3884 */
3885 @Override
3886 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003887 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003888 synchronized (mGlobalLock) {
3889 long ident = Binder.clearCallingIdentity();
3890 try {
3891 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3892 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003893 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003894 if (task == null) {
3895 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3896 + taskId);
3897 }
3898
Louis Chang149d5c82019-12-30 09:47:39 +08003899 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003900
3901 if (stack == null) {
3902 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3903 + stackId);
3904 }
3905 if (!stack.isActivityTypeStandardOrUndefined()) {
3906 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3907 + " the position of task " + taskId + " in/to non-standard stack");
3908 }
3909
3910 // TODO: Have the callers of this API call a separate reparent method if that is
3911 // what they intended to do vs. having this method also do reparenting.
3912 if (task.getStack() == stack) {
3913 // Change position in current stack.
3914 stack.positionChildAt(task, position);
3915 } else {
3916 // Reparent to new stack.
3917 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3918 !DEFER_RESUME, "positionTaskInStack");
3919 }
3920 } finally {
3921 Binder.restoreCallingIdentity(ident);
3922 }
3923 }
3924 }
3925
3926 @Override
3927 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3928 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3929 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003930 + Arrays.toString(horizontalSizeConfiguration) + " "
3931 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003932 synchronized (mGlobalLock) {
3933 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3934 if (record == null) {
3935 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3936 + "found for: " + token);
3937 }
3938 record.setSizeConfigurations(horizontalSizeConfiguration,
3939 verticalSizeConfigurations, smallestSizeConfigurations);
3940 }
3941 }
3942
3943 /**
3944 * Dismisses split-screen multi-window mode.
3945 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3946 */
3947 @Override
3948 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003949 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003950 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3951 final long ident = Binder.clearCallingIdentity();
3952 try {
3953 synchronized (mGlobalLock) {
3954 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08003955 mRootWindowContainer.getDefaultDisplay().getRootSplitScreenPrimaryTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003956 if (stack == null) {
3957 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3958 return;
3959 }
3960
3961 if (toTop) {
3962 // Caller wants the current split-screen primary stack to be the top stack after
3963 // it goes fullscreen, so move it to the front.
3964 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003965 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003966 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003967 // stack after it goes fullscreen, so we move the focus to the top-most
3968 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003969 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3970 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3971 if (otherStack != null) {
3972 otherStack.moveToFront("dismissSplitScreenMode_other");
3973 }
3974 }
3975
Evan Rosky10475742018-09-05 19:02:48 -07003976 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003977 }
3978 } finally {
3979 Binder.restoreCallingIdentity(ident);
3980 }
3981 }
3982
3983 /**
3984 * Dismisses Pip
3985 * @param animate True if the dismissal should be animated.
3986 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3987 * default animation duration should be used.
3988 */
3989 @Override
3990 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003991 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003992 final long ident = Binder.clearCallingIdentity();
3993 try {
3994 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003995 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08003996 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003997 if (stack == null) {
3998 Slog.w(TAG, "dismissPip: pinned stack not found.");
3999 return;
4000 }
4001 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4002 throw new IllegalArgumentException("Stack: " + stack
4003 + " doesn't support animated resize.");
4004 }
Robert Carr8a2f9132019-11-11 15:03:15 -08004005 /**
4006 * TODO(b/146594635): Remove all PIP animation code from WM
4007 * once SysUI handles animation. Don't even try to animate TaskOrganized tasks.
4008 */
4009 if (animate && !stack.isControlledByTaskOrganizer()) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004010 stack.animateResizePinnedStack(null /* destBounds */,
4011 null /* sourceHintBounds */, animationDuration,
4012 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004013 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004014 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004015 }
4016 }
4017 } finally {
4018 Binder.restoreCallingIdentity(ident);
4019 }
4020 }
4021
4022 @Override
4023 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004024 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004025 synchronized (mGlobalLock) {
4026 mSuppressResizeConfigChanges = suppress;
4027 }
4028 }
4029
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004030 @Override
4031 // TODO: API should just be about changing windowing modes...
4032 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004033 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004034 "moveTasksToFullscreenStack()");
4035 synchronized (mGlobalLock) {
4036 final long origId = Binder.clearCallingIdentity();
4037 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004038 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004039 if (stack != null){
4040 if (!stack.isActivityTypeStandardOrUndefined()) {
4041 throw new IllegalArgumentException(
4042 "You can't move tasks from non-standard stacks.");
4043 }
4044 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4045 }
4046 } finally {
4047 Binder.restoreCallingIdentity(origId);
4048 }
4049 }
4050 }
4051
4052 /**
4053 * Moves the top activity in the input stackId to the pinned stack.
4054 *
4055 * @param stackId Id of stack to move the top activity to pinned stack.
4056 * @param bounds Bounds to use for pinned stack.
4057 *
4058 * @return True if the top activity of the input stack was successfully moved to the pinned
4059 * stack.
4060 */
4061 @Override
4062 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004063 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004064 "moveTopActivityToPinnedStack()");
4065 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004066 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004067 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4068 + "Device doesn't support picture-in-picture mode");
4069 }
4070
4071 long ident = Binder.clearCallingIdentity();
4072 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004073 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004074 } finally {
4075 Binder.restoreCallingIdentity(ident);
4076 }
4077 }
4078 }
4079
4080 @Override
4081 public boolean isInMultiWindowMode(IBinder token) {
4082 final long origId = Binder.clearCallingIdentity();
4083 try {
4084 synchronized (mGlobalLock) {
4085 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4086 if (r == null) {
4087 return false;
4088 }
4089 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4090 return r.inMultiWindowMode();
4091 }
4092 } finally {
4093 Binder.restoreCallingIdentity(origId);
4094 }
4095 }
4096
4097 @Override
4098 public boolean isInPictureInPictureMode(IBinder token) {
4099 final long origId = Binder.clearCallingIdentity();
4100 try {
4101 synchronized (mGlobalLock) {
4102 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4103 }
4104 } finally {
4105 Binder.restoreCallingIdentity(origId);
4106 }
4107 }
4108
4109 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004110 if (r == null || r.getRootTask() == null || !r.inPinnedWindowingMode()
4111 || r.getRootTask().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004112 return false;
4113 }
4114
4115 // If we are animating to fullscreen then we have already dispatched the PIP mode
4116 // changed, so we should reflect that check here as well.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004117 final ActivityStack taskStack = r.getRootTask();
Yunfan Chen279f5582018-12-12 15:24:50 -08004118 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004119 }
4120
4121 @Override
4122 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4123 final long origId = Binder.clearCallingIdentity();
4124 try {
4125 synchronized (mGlobalLock) {
4126 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4127 "enterPictureInPictureMode", token, params);
4128
4129 // If the activity is already in picture in picture mode, then just return early
4130 if (isInPictureInPictureMode(r)) {
4131 return true;
4132 }
4133
4134 // Activity supports picture-in-picture, now check that we can enter PiP at this
4135 // point, if it is
4136 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4137 false /* beforeStopping */)) {
4138 return false;
4139 }
4140
4141 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004142 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004143 if (r.getParent() == null) {
4144 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4145 return;
4146 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004147 // Only update the saved args from the args that are set
4148 r.pictureInPictureArgs.copyOnlySet(params);
4149 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4150 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4151 // Adjust the source bounds by the insets for the transition down
4152 final Rect sourceBounds = new Rect(
4153 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004154 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004155 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004156 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004157 stack.setPictureInPictureAspectRatio(aspectRatio);
4158 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004159 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4160 r.info.applicationInfo.uid, r.shortComponentName,
4161 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004162 logPictureInPictureArgs(params);
4163 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004164 };
4165
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004166 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004167 // If the keyguard is showing or occluded, then try and dismiss it before
4168 // entering picture-in-picture (this will prompt the user to authenticate if the
4169 // device is currently locked).
4170 dismissKeyguard(token, new KeyguardDismissCallback() {
4171 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004172 public void onDismissSucceeded() {
4173 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004174 }
4175 }, null /* message */);
4176 } else {
4177 // Enter picture in picture immediately otherwise
4178 enterPipRunnable.run();
4179 }
4180 return true;
4181 }
4182 } finally {
4183 Binder.restoreCallingIdentity(origId);
4184 }
4185 }
4186
4187 @Override
4188 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4189 final long origId = Binder.clearCallingIdentity();
4190 try {
4191 synchronized (mGlobalLock) {
4192 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4193 "setPictureInPictureParams", token, params);
4194
4195 // Only update the saved args from the args that are set
4196 r.pictureInPictureArgs.copyOnlySet(params);
4197 if (r.inPinnedWindowingMode()) {
4198 // If the activity is already in picture-in-picture, update the pinned stack now
4199 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4200 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004201 final ActivityStack stack = r.getRootTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004202 if (!stack.isAnimatingBoundsToFullscreen()) {
4203 stack.setPictureInPictureAspectRatio(
4204 r.pictureInPictureArgs.getAspectRatio());
4205 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4206 }
4207 }
4208 logPictureInPictureArgs(params);
4209 }
4210 } finally {
4211 Binder.restoreCallingIdentity(origId);
4212 }
4213 }
4214
4215 @Override
4216 public int getMaxNumPictureInPictureActions(IBinder token) {
4217 // Currently, this is a static constant, but later, we may change this to be dependent on
4218 // the context of the activity
4219 return 3;
4220 }
4221
4222 private void logPictureInPictureArgs(PictureInPictureParams params) {
4223 if (params.hasSetActions()) {
4224 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4225 params.getActions().size());
4226 }
4227 if (params.hasSetAspectRatio()) {
4228 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4229 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4230 MetricsLogger.action(lm);
4231 }
4232 }
4233
4234 /**
4235 * Checks the state of the system and the activity associated with the given {@param token} to
4236 * verify that picture-in-picture is supported for that activity.
4237 *
4238 * @return the activity record for the given {@param token} if all the checks pass.
4239 */
4240 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4241 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004242 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004243 throw new IllegalStateException(caller
4244 + ": Device doesn't support picture-in-picture mode.");
4245 }
4246
4247 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4248 if (r == null) {
4249 throw new IllegalStateException(caller
4250 + ": Can't find activity for token=" + token);
4251 }
4252
4253 if (!r.supportsPictureInPicture()) {
4254 throw new IllegalStateException(caller
4255 + ": Current activity does not support picture-in-picture.");
4256 }
4257
4258 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004259 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004260 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004261 final float minAspectRatio = mContext.getResources().getFloat(
4262 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4263 final float maxAspectRatio = mContext.getResources().getFloat(
4264 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4265 throw new IllegalArgumentException(String.format(caller
4266 + ": Aspect ratio is too extreme (must be between %f and %f).",
4267 minAspectRatio, maxAspectRatio));
4268 }
4269
4270 // Truncate the number of actions if necessary
4271 params.truncateActions(getMaxNumPictureInPictureActions(token));
4272
4273 return r;
4274 }
4275
4276 @Override
4277 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004278 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004279 synchronized (mGlobalLock) {
4280 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4281 if (r == null) {
4282 throw new IllegalArgumentException("Activity does not exist; token="
4283 + activityToken);
4284 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004285 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004286 }
4287 }
4288
4289 @Override
4290 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4291 Rect tempDockedTaskInsetBounds,
4292 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004293 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004294 long ident = Binder.clearCallingIdentity();
4295 try {
4296 synchronized (mGlobalLock) {
4297 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4298 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4299 PRESERVE_WINDOWS);
4300 }
4301 } finally {
4302 Binder.restoreCallingIdentity(ident);
4303 }
4304 }
4305
4306 @Override
4307 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004308 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004309 final long ident = Binder.clearCallingIdentity();
4310 try {
4311 synchronized (mGlobalLock) {
4312 mStackSupervisor.setSplitScreenResizing(resizing);
4313 }
4314 } finally {
4315 Binder.restoreCallingIdentity(ident);
4316 }
4317 }
4318
Evan Rosky0037e5f2019-11-05 10:26:24 -08004319 @Override
4320 public ITaskOrganizerController getTaskOrganizerController() {
4321 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
4322 "getTaskOrganizerController()");
4323 return mTaskOrganizerController;
4324 }
4325
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004326 /**
4327 * Check that we have the features required for VR-related API calls, and throw an exception if
4328 * not.
4329 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004330 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004331 if (!mContext.getPackageManager().hasSystemFeature(
4332 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4333 throw new UnsupportedOperationException("VR mode not supported on this device!");
4334 }
4335 }
4336
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004337 @Override
4338 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004339 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004340
4341 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4342
4343 ActivityRecord r;
4344 synchronized (mGlobalLock) {
4345 r = ActivityRecord.isInStackLocked(token);
4346 }
4347
4348 if (r == null) {
4349 throw new IllegalArgumentException();
4350 }
4351
4352 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004353 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004354 VrManagerInternal.NO_ERROR) {
4355 return err;
4356 }
4357
4358 // Clear the binder calling uid since this path may call moveToTask().
4359 final long callingId = Binder.clearCallingIdentity();
4360 try {
4361 synchronized (mGlobalLock) {
4362 r.requestedVrComponent = (enabled) ? packageName : null;
4363
4364 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004365 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004366 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367 }
4368 return 0;
4369 }
4370 } finally {
4371 Binder.restoreCallingIdentity(callingId);
4372 }
4373 }
4374
4375 @Override
4376 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4377 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4378 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004379 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004380 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4381 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4382 }
Louis Changcdec0802019-11-11 11:45:07 +08004383 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004384 || activity.voiceSession != null) {
4385 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4386 return;
4387 }
4388 if (activity.pendingVoiceInteractionStart) {
4389 Slog.w(TAG, "Pending start of voice interaction already.");
4390 return;
4391 }
4392 activity.pendingVoiceInteractionStart = true;
4393 }
4394 LocalServices.getService(VoiceInteractionManagerInternal.class)
4395 .startLocalVoiceInteraction(callingActivity, options);
4396 }
4397
4398 @Override
4399 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4400 LocalServices.getService(VoiceInteractionManagerInternal.class)
4401 .stopLocalVoiceInteraction(callingActivity);
4402 }
4403
4404 @Override
4405 public boolean supportsLocalVoiceInteraction() {
4406 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4407 .supportsLocalVoiceInteraction();
4408 }
4409
4410 /** Notifies all listeners when the pinned stack animation starts. */
4411 @Override
4412 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004413 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004414 }
4415
4416 /** Notifies all listeners when the pinned stack animation ends. */
4417 @Override
4418 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004419 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004420 }
4421
4422 @Override
4423 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004424 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004425 final long ident = Binder.clearCallingIdentity();
4426 try {
4427 synchronized (mGlobalLock) {
4428 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4429 }
4430 } finally {
4431 Binder.restoreCallingIdentity(ident);
4432 }
4433 }
4434
4435 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004436 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004437 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004438
4439 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004440 if (mWindowManager == null) {
4441 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4442 return false;
4443 }
4444
4445 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004446 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004447 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004448 }
4449
Riddle Hsua0022cd2019-09-09 21:12:41 +08004450 mH.sendMessage(PooledLambda.obtainMessage(
4451 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4452 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004453
4454 final long origId = Binder.clearCallingIdentity();
4455 try {
4456 if (values != null) {
4457 Settings.System.clearConfiguration(values);
4458 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004459 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004460 UserHandle.USER_NULL, false /* deferResume */,
4461 mTmpUpdateConfigurationResult);
4462 return mTmpUpdateConfigurationResult.changes != 0;
4463 } finally {
4464 Binder.restoreCallingIdentity(origId);
4465 }
4466 }
4467 }
4468
4469 @Override
4470 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4471 CharSequence message) {
4472 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004473 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004474 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4475 }
4476 final long callingId = Binder.clearCallingIdentity();
4477 try {
4478 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004479 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004480 }
4481 } finally {
4482 Binder.restoreCallingIdentity(callingId);
4483 }
4484 }
4485
4486 @Override
4487 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004488 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004489 "cancelTaskWindowTransition()");
4490 final long ident = Binder.clearCallingIdentity();
4491 try {
4492 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004493 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004494 MATCH_TASK_IN_STACKS_ONLY);
4495 if (task == null) {
4496 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4497 return;
4498 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004499 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004500 }
4501 } finally {
4502 Binder.restoreCallingIdentity(ident);
4503 }
4504 }
4505
4506 @Override
4507 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004508 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004509 final long ident = Binder.clearCallingIdentity();
4510 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004511 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004512 } finally {
4513 Binder.restoreCallingIdentity(ident);
4514 }
4515 }
4516
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004517 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4518 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004519 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004520 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004521 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004522 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4523 if (task == null) {
4524 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4525 return null;
4526 }
4527 }
4528 // Don't call this while holding the lock as this operation might hit the disk.
4529 return task.getSnapshot(reducedResolution, restoreFromDisk);
4530 }
4531
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004532 @Override
4533 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4534 synchronized (mGlobalLock) {
4535 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4536 if (r == null) {
4537 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4538 + token);
4539 return;
4540 }
4541 final long origId = Binder.clearCallingIdentity();
4542 try {
4543 r.setDisablePreviewScreenshots(disable);
4544 } finally {
4545 Binder.restoreCallingIdentity(origId);
4546 }
4547 }
4548 }
4549
Riddle Hsu440f88b2019-11-06 22:17:35 +08004550 @Override
4551 public void invalidateHomeTaskSnapshot(IBinder token) {
4552 synchronized (mGlobalLock) {
4553 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4554 if (r == null || !r.isActivityTypeHome()) {
4555 return;
4556 }
4557 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4558 }
4559 }
4560
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004561 /** Return the user id of the last resumed activity. */
4562 @Override
4563 public @UserIdInt
4564 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004565 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004566 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4567 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004568 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004569 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004570 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004571 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004572 }
4573 }
4574
4575 @Override
4576 public void updateLockTaskFeatures(int userId, int flags) {
4577 final int callingUid = Binder.getCallingUid();
4578 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004579 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004580 "updateLockTaskFeatures()");
4581 }
4582 synchronized (mGlobalLock) {
4583 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4584 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004585 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004586 }
4587 }
4588
4589 @Override
4590 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4591 synchronized (mGlobalLock) {
4592 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4593 if (r == null) {
4594 return;
4595 }
4596 final long origId = Binder.clearCallingIdentity();
4597 try {
4598 r.setShowWhenLocked(showWhenLocked);
4599 } finally {
4600 Binder.restoreCallingIdentity(origId);
4601 }
4602 }
4603 }
4604
4605 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004606 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4607 synchronized (mGlobalLock) {
4608 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4609 if (r == null) {
4610 return;
4611 }
4612 final long origId = Binder.clearCallingIdentity();
4613 try {
4614 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4615 } finally {
4616 Binder.restoreCallingIdentity(origId);
4617 }
4618 }
4619 }
4620
4621 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004622 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4623 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.setTurnScreenOn(turnScreenOn);
4631 } finally {
4632 Binder.restoreCallingIdentity(origId);
4633 }
4634 }
4635 }
4636
4637 @Override
4638 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004639 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004640 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004641 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004642 synchronized (mGlobalLock) {
4643 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4644 if (r == null) {
4645 return;
4646 }
4647 final long origId = Binder.clearCallingIdentity();
4648 try {
4649 r.registerRemoteAnimations(definition);
4650 } finally {
4651 Binder.restoreCallingIdentity(origId);
4652 }
4653 }
4654 }
4655
4656 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004657 public void unregisterRemoteAnimations(IBinder token) {
4658 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4659 "unregisterRemoteAnimations");
4660 synchronized (mGlobalLock) {
4661 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4662 if (r == null) {
4663 return;
4664 }
4665 final long origId = Binder.clearCallingIdentity();
4666 try {
4667 r.unregisterRemoteAnimations();
4668 } finally {
4669 Binder.restoreCallingIdentity(origId);
4670 }
4671 }
4672 }
4673
4674 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004675 public void registerRemoteAnimationForNextActivityStart(String packageName,
4676 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004677 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004678 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004679 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004680 synchronized (mGlobalLock) {
4681 final long origId = Binder.clearCallingIdentity();
4682 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004683 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004684 packageName, adapter);
4685 } finally {
4686 Binder.restoreCallingIdentity(origId);
4687 }
4688 }
4689 }
4690
Evan Rosky966759f2019-01-15 10:33:58 -08004691 @Override
4692 public void registerRemoteAnimationsForDisplay(int displayId,
4693 RemoteAnimationDefinition definition) {
4694 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4695 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004696 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004697 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004698 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004699 if (display == null) {
4700 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4701 return;
4702 }
4703 final long origId = Binder.clearCallingIdentity();
4704 try {
4705 display.mDisplayContent.registerRemoteAnimations(definition);
4706 } finally {
4707 Binder.restoreCallingIdentity(origId);
4708 }
4709 }
4710 }
4711
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004712 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4713 @Override
4714 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4715 synchronized (mGlobalLock) {
4716 final long origId = Binder.clearCallingIdentity();
4717 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004718 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004719 } finally {
4720 Binder.restoreCallingIdentity(origId);
4721 }
4722 }
4723 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004724
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004725 @Override
4726 public void setVrThread(int tid) {
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 wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004731 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004732 }
4733 }
4734
4735 @Override
4736 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004737 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004738 != PERMISSION_GRANTED) {
4739 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4740 + Binder.getCallingPid()
4741 + ", uid=" + Binder.getCallingUid()
4742 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4743 Slog.w(TAG, msg);
4744 throw new SecurityException(msg);
4745 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004746 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004747 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004748 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004749 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004750 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004751 }
4752 }
4753
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004754 @Override
4755 public void stopAppSwitches() {
4756 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4757 synchronized (mGlobalLock) {
4758 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004759 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004760 mDidAppSwitch = false;
4761 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4762 }
4763 }
4764
4765 @Override
4766 public void resumeAppSwitches() {
4767 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4768 synchronized (mGlobalLock) {
4769 // Note that we don't execute any pending app switches... we will
4770 // let those wait until either the timeout, or the next start
4771 // activity request.
4772 mAppSwitchesAllowedTime = 0;
4773 }
4774 }
4775
Ricky Wai906af482019-06-03 17:25:28 +01004776 long getLastStopAppSwitchesTime() {
4777 return mLastStopAppSwitchesTime;
4778 }
4779
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004780 void onStartActivitySetDidAppSwitch() {
4781 if (mDidAppSwitch) {
4782 // This is the second allowed switch since we stopped switches, so now just generally
4783 // allow switches. Use case:
4784 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4785 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4786 // anyone to switch again).
4787 mAppSwitchesAllowedTime = 0;
4788 } else {
4789 mDidAppSwitch = true;
4790 }
4791 }
4792
4793 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004794 boolean shouldDisableNonVrUiLocked() {
4795 return mVrController.shouldDisableNonVrUiLocked();
4796 }
4797
Wale Ogunwale53783742018-09-16 10:21:51 -07004798 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004799 // 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 +00004800 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004801 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004802 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4803 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004804 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004805 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004806 }
4807 mH.post(() -> {
4808 if (!mVrController.onVrModeChanged(r)) {
4809 return;
4810 }
4811 synchronized (mGlobalLock) {
4812 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4813 mWindowManager.disableNonVrUi(disableNonVrUi);
4814 if (disableNonVrUi) {
4815 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4816 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004817 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004818 }
4819 }
4820 });
4821 }
4822
Wale Ogunwale53783742018-09-16 10:21:51 -07004823 @Override
4824 public int getPackageScreenCompatMode(String packageName) {
4825 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4826 synchronized (mGlobalLock) {
4827 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4828 }
4829 }
4830
4831 @Override
4832 public void setPackageScreenCompatMode(String packageName, int mode) {
4833 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4834 "setPackageScreenCompatMode");
4835 synchronized (mGlobalLock) {
4836 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4837 }
4838 }
4839
4840 @Override
4841 public boolean getPackageAskScreenCompat(String packageName) {
4842 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4843 synchronized (mGlobalLock) {
4844 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4845 }
4846 }
4847
4848 @Override
4849 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4850 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4851 "setPackageAskScreenCompat");
4852 synchronized (mGlobalLock) {
4853 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4854 }
4855 }
4856
Wale Ogunwale64258362018-10-16 15:13:37 -07004857 public static String relaunchReasonToString(int relaunchReason) {
4858 switch (relaunchReason) {
4859 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4860 return "window_resize";
4861 case RELAUNCH_REASON_FREE_RESIZE:
4862 return "free_resize";
4863 default:
4864 return null;
4865 }
4866 }
4867
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004868 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004869 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004870 }
4871
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004872 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004873 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004874 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4875 }
4876
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004877 boolean isKeyguardLocked() {
4878 return mKeyguardController.isKeyguardLocked();
4879 }
4880
Garfield Tan01548632018-11-27 10:15:48 -08004881 /**
4882 * Clears launch params for the given package.
4883 * @param packageNames the names of the packages of which the launch params are to be cleared
4884 */
4885 @Override
4886 public void clearLaunchParamsForPackages(List<String> packageNames) {
4887 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4888 "clearLaunchParamsForPackages");
4889 synchronized (mGlobalLock) {
4890 for (int i = 0; i < packageNames.size(); ++i) {
4891 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4892 }
4893 }
4894 }
4895
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004896 /**
4897 * Makes the display with the given id a single task instance display. I.e the display can only
4898 * contain one task.
4899 */
4900 @Override
4901 public void setDisplayToSingleTaskInstance(int displayId) {
4902 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4903 "setDisplayToSingleTaskInstance");
4904 final long origId = Binder.clearCallingIdentity();
4905 try {
Louis Chang677921f2019-12-06 16:44:24 +08004906 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004907 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004908 if (display != null) {
4909 display.setDisplayToSingleTaskInstance();
4910 }
4911 } finally {
4912 Binder.restoreCallingIdentity(origId);
4913 }
4914 }
4915
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004916 /**
4917 * Requests that an activity should enter picture-in-picture mode if possible.
4918 */
4919 @Override
4920 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4921 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4922 "requestPictureInPictureMode");
4923 final long origId = Binder.clearCallingIdentity();
4924 try {
4925 synchronized (mGlobalLock) {
4926 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4927 if (activity == null) {
4928 return;
4929 }
4930
4931 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4932 "requestPictureInPictureMode", /* beforeStopping */ false);
4933 if (!canEnterPictureInPicture) {
4934 throw new IllegalStateException(
4935 "Requested PIP on an activity that doesn't support it");
4936 }
4937
4938 try {
4939 final ClientTransaction transaction = ClientTransaction.obtain(
4940 activity.app.getThread(),
4941 activity.token);
4942 transaction.addCallback(EnterPipRequestedItem.obtain());
4943 getLifecycleManager().scheduleTransaction(transaction);
4944 } catch (Exception e) {
4945 Slog.w(TAG, "Failed to send enter pip requested item: "
4946 + activity.intent.getComponent(), e);
4947 }
4948 }
4949 } finally {
4950 Binder.restoreCallingIdentity(origId);
4951 }
4952 }
4953
Wale Ogunwale31913b52018-10-13 08:29:31 -07004954 void dumpLastANRLocked(PrintWriter pw) {
4955 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4956 if (mLastANRState == null) {
4957 pw.println(" <no ANR has occurred since boot>");
4958 } else {
4959 pw.println(mLastANRState);
4960 }
4961 }
4962
4963 void dumpLastANRTracesLocked(PrintWriter pw) {
4964 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4965
4966 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4967 if (ArrayUtils.isEmpty(files)) {
4968 pw.println(" <no ANR has occurred since boot>");
4969 return;
4970 }
4971 // Find the latest file.
4972 File latest = null;
4973 for (File f : files) {
4974 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4975 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004976 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004977 }
4978 pw.print("File: ");
4979 pw.print(latest.getName());
4980 pw.println();
4981 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4982 String line;
4983 while ((line = in.readLine()) != null) {
4984 pw.println(line);
4985 }
4986 } catch (IOException e) {
4987 pw.print("Unable to read: ");
4988 pw.print(e);
4989 pw.println();
4990 }
4991 }
4992
4993 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4994 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4995 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4996 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4997 }
4998
4999 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5000 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5001 pw.println(header);
5002
Louis Chang149d5c82019-12-30 09:47:39 +08005003 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005004 dumpPackage);
5005 boolean needSep = printedAnything;
5006
5007 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08005008 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005009 " ResumedActivity: ");
5010 if (printed) {
5011 printedAnything = true;
5012 needSep = false;
5013 }
5014
5015 if (dumpPackage == null) {
5016 if (needSep) {
5017 pw.println();
5018 }
5019 printedAnything = true;
5020 mStackSupervisor.dump(pw, " ");
5021 }
5022
5023 if (!printedAnything) {
5024 pw.println(" (nothing)");
5025 }
5026 }
5027
5028 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005029 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005030 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005031 pw.println(" ");
5032 }
5033
5034 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5035 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5036 getActivityStartController().dump(pw, "", dumpPackage);
5037 }
5038
5039 /**
5040 * There are three things that cmd can be:
5041 * - a flattened component name that matches an existing activity
5042 * - the cmd arg isn't the flattened component name of an existing activity:
5043 * dump all activity whose component contains the cmd as a substring
5044 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005045 * <p>
5046 * The caller should not hold lock when calling this method because it will wait for the
5047 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005048 *
5049 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5050 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5051 */
5052 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5053 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5054 ArrayList<ActivityRecord> activities;
5055
5056 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005057 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005058 dumpFocusedStackOnly);
5059 }
5060
5061 if (activities.size() <= 0) {
5062 return false;
5063 }
5064
5065 String[] newArgs = new String[args.length - opti];
5066 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5067
Louis Changcdec0802019-11-11 11:45:07 +08005068 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005069 boolean needSep = false;
5070 for (int i = activities.size() - 1; i >= 0; i--) {
5071 ActivityRecord r = activities.get(i);
5072 if (needSep) {
5073 pw.println();
5074 }
5075 needSep = true;
5076 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005077 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005078 if (lastTask != task) {
5079 lastTask = task;
5080 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005081 pw.print(" id="); pw.print(lastTask.mTaskId);
5082 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005083 if (dumpAll) {
5084 lastTask.dump(pw, " ");
5085 }
5086 }
5087 }
5088 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5089 }
5090 return true;
5091 }
5092
5093 /**
5094 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5095 * there is a thread associated with the activity.
5096 */
5097 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5098 final ActivityRecord r, String[] args, boolean dumpAll) {
5099 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005100 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005101 synchronized (mGlobalLock) {
5102 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5103 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5104 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005105 if (r.hasProcess()) {
5106 pw.println(r.app.getPid());
5107 appThread = r.app.getThread();
5108 } else {
5109 pw.println("(not running)");
5110 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005111 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005112 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005113 }
5114 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005115 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005116 // flush anything that is already in the PrintWriter since the thread is going
5117 // to write to the file descriptor directly
5118 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005119 try (TransferPipe tp = new TransferPipe()) {
5120 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5121 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005122 } catch (IOException e) {
5123 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5124 } catch (RemoteException e) {
5125 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5126 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005127 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005128 }
5129
sanryhuang498e77e2018-12-06 14:57:01 +08005130 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5131 boolean testPssMode) {
5132 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5133 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5134 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005135 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005136 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5137 st.toString());
5138 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005139 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5140 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5141 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005142 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5143 testPssMode);
5144 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005145 }
5146
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005147 int getCurrentUserId() {
5148 return mAmInternal.getCurrentUserId();
5149 }
5150
5151 private void enforceNotIsolatedCaller(String caller) {
5152 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5153 throw new SecurityException("Isolated process not allowed to call " + caller);
5154 }
5155 }
5156
Wale Ogunwalef6733932018-06-27 05:14:34 -07005157 public Configuration getConfiguration() {
5158 Configuration ci;
5159 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005160 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005161 ci.userSetLocale = false;
5162 }
5163 return ci;
5164 }
5165
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005166 /**
5167 * Current global configuration information. Contains general settings for the entire system,
5168 * also corresponds to the merged configuration of the default display.
5169 */
5170 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005171 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005172 // while initializing process record for system, see {@link
5173 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005174 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005175 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005176 }
5177
5178 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5179 boolean initLocale) {
5180 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5181 }
5182
5183 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5184 boolean initLocale, boolean deferResume) {
5185 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5186 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5187 UserHandle.USER_NULL, deferResume);
5188 }
5189
Wale Ogunwale59507092018-10-29 09:00:30 -07005190 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005191 final long origId = Binder.clearCallingIdentity();
5192 try {
5193 synchronized (mGlobalLock) {
5194 updateConfigurationLocked(values, null, false, true, userId,
5195 false /* deferResume */);
5196 }
5197 } finally {
5198 Binder.restoreCallingIdentity(origId);
5199 }
5200 }
5201
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005202 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5203 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5204 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5205 deferResume, null /* result */);
5206 }
5207
5208 /**
5209 * Do either or both things: (1) change the current configuration, and (2)
5210 * make sure the given activity is running with the (now) current
5211 * configuration. Returns true if the activity has been left running, or
5212 * false if <var>starting</var> is being destroyed to match the new
5213 * configuration.
5214 *
5215 * @param userId is only used when persistent parameter is set to true to persist configuration
5216 * for that particular user
5217 */
5218 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5219 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5220 ActivityTaskManagerService.UpdateConfigurationResult result) {
5221 int changes = 0;
5222 boolean kept = true;
5223
Riddle Hsua0022cd2019-09-09 21:12:41 +08005224 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005225 try {
5226 if (values != null) {
5227 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5228 deferResume);
5229 }
5230
5231 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5232 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005233 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005234 }
5235
5236 if (result != null) {
5237 result.changes = changes;
5238 result.activityRelaunched = !kept;
5239 }
5240 return kept;
5241 }
5242
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005243 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005244 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005245 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005246
Louis Chang677921f2019-12-06 16:44:24 +08005247 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005248 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005249
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005250 mTempConfig.setTo(getGlobalConfiguration());
5251 final int changes = mTempConfig.updateFrom(values);
5252 if (changes == 0) {
5253 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5254 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5255 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5256 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005257 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005258 return 0;
5259 }
5260
5261 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5262 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005263 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005264 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005265 values.colorMode,
5266 values.densityDpi,
5267 values.fontScale,
5268 values.hardKeyboardHidden,
5269 values.keyboard,
5270 values.keyboardHidden,
5271 values.mcc,
5272 values.mnc,
5273 values.navigation,
5274 values.navigationHidden,
5275 values.orientation,
5276 values.screenHeightDp,
5277 values.screenLayout,
5278 values.screenWidthDp,
5279 values.smallestScreenWidthDp,
5280 values.touchscreen,
5281 values.uiMode);
5282
5283
5284 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5285 final LocaleList locales = values.getLocales();
5286 int bestLocaleIndex = 0;
5287 if (locales.size() > 1) {
5288 if (mSupportedSystemLocales == null) {
5289 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5290 }
5291 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5292 }
5293 SystemProperties.set("persist.sys.locale",
5294 locales.get(bestLocaleIndex).toLanguageTag());
5295 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005296
5297 final Message m = PooledLambda.obtainMessage(
5298 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5299 locales.get(bestLocaleIndex));
5300 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005301 }
5302
Yunfan Chen75157d72018-07-27 14:47:21 +09005303 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005304
5305 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005306 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005307
5308 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5309 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005310 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005311
5312 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005313 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005314
5315 AttributeCache ac = AttributeCache.instance();
5316 if (ac != null) {
5317 ac.updateConfiguration(mTempConfig);
5318 }
5319
5320 // Make sure all resources in our process are updated right now, so that anyone who is going
5321 // to retrieve resource values after we return will be sure to get the new ones. This is
5322 // especially important during boot, where the first config change needs to guarantee all
5323 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005324 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005325
5326 // We need another copy of global config because we're scheduling some calls instead of
5327 // running them in place. We need to be sure that object we send will be handled unchanged.
5328 final Configuration configCopy = new Configuration(mTempConfig);
5329 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005330 final Message msg = PooledLambda.obtainMessage(
5331 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5332 this, userId, configCopy);
5333 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005334 }
5335
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005336 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5337 for (int i = pidMap.size() - 1; i >= 0; i--) {
5338 final int pid = pidMap.keyAt(i);
5339 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005340 if (DEBUG_CONFIGURATION) {
5341 Slog.v(TAG_CONFIGURATION, "Update process config of "
5342 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005343 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005344 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005345 }
5346
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005347 final Message msg = PooledLambda.obtainMessage(
5348 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5349 mAmInternal, changes, initLocale);
5350 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005351
5352 // Override configuration of the default display duplicates global config, so we need to
5353 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005354 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005355 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005356
5357 return changes;
5358 }
5359
Riddle Hsua0022cd2019-09-09 21:12:41 +08005360 /** @see WindowSurfacePlacer#deferLayout */
5361 void deferWindowLayout() {
5362 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5363 // Reset the reasons at the first entrance because we only care about the changes in the
5364 // deferred scope.
5365 mLayoutReasons = 0;
5366 }
5367
5368 mWindowManager.mWindowPlacerLocked.deferLayout();
5369 }
5370
5371 /** @see WindowSurfacePlacer#continueLayout */
5372 void continueWindowLayout() {
5373 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5374 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5375 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5376 }
5377 }
5378
5379 /**
5380 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5381 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5382 * defer count is gone.
5383 */
5384 void addWindowLayoutReasons(@LayoutReason int reasons) {
5385 mLayoutReasons |= reasons;
5386 }
5387
Wale Ogunwalef6733932018-06-27 05:14:34 -07005388 private void updateEventDispatchingLocked(boolean booted) {
5389 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5390 }
5391
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005392 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5393 final ContentResolver resolver = mContext.getContentResolver();
5394 Settings.System.putConfigurationForUser(resolver, config, userId);
5395 }
5396
5397 private void sendLocaleToMountDaemonMsg(Locale l) {
5398 try {
5399 IBinder service = ServiceManager.getService("mount");
5400 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5401 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5402 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5403 } catch (RemoteException e) {
5404 Log.e(TAG, "Error storing locale for decryption UI", e);
5405 }
5406 }
5407
Alison Cichowlas3e340502018-08-07 17:15:01 -04005408 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5409 mStartActivitySources.remove(permissionToken);
5410 mExpiredStartAsCallerTokens.add(permissionToken);
5411 }
5412
5413 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5414 mExpiredStartAsCallerTokens.remove(permissionToken);
5415 }
5416
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005417 boolean isActivityStartsLoggingEnabled() {
5418 return mAmInternal.isActivityStartsLoggingEnabled();
5419 }
5420
Michal Karpinski8596ded2018-11-14 14:43:48 +00005421 boolean isBackgroundActivityStartsEnabled() {
5422 return mAmInternal.isBackgroundActivityStartsEnabled();
5423 }
5424
Wale Ogunwalef6733932018-06-27 05:14:34 -07005425 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005426 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005427 mWindowManager.enableScreenAfterBoot();
5428
5429 synchronized (mGlobalLock) {
5430 updateEventDispatchingLocked(booted);
5431 }
5432 }
5433
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005434 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5435 if (r == null || !r.hasProcess()) {
5436 return KEY_DISPATCHING_TIMEOUT_MS;
5437 }
5438 return getInputDispatchingTimeoutLocked(r.app);
5439 }
5440
5441 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005442 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005443 }
5444
Wale Ogunwalef6733932018-06-27 05:14:34 -07005445 /**
5446 * Decide based on the configuration whether we should show the ANR,
5447 * crash, etc dialogs. The idea is that if there is no affordance to
5448 * press the on-screen buttons, or the user experience would be more
5449 * greatly impacted than the crash itself, we shouldn't show the dialog.
5450 *
5451 * A thought: SystemUI might also want to get told about this, the Power
5452 * dialog / global actions also might want different behaviors.
5453 */
5454 private void updateShouldShowDialogsLocked(Configuration config) {
5455 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5456 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5457 && config.navigation == Configuration.NAVIGATION_NONAV);
5458 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5459 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5460 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5461 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5462 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5463 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5464 HIDE_ERROR_DIALOGS, 0) != 0;
5465 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5466 }
5467
5468 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5469 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5470 FONT_SCALE, 1.0f, userId);
5471
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005472 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005473 if (getGlobalConfiguration().fontScale == scaleFactor) {
5474 return;
5475 }
5476
5477 final Configuration configuration
5478 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5479 configuration.fontScale = scaleFactor;
5480 updatePersistentConfiguration(configuration, userId);
5481 }
5482 }
5483
5484 // Actually is sleeping or shutting down or whatever else in the future
5485 // is an inactive state.
5486 boolean isSleepingOrShuttingDownLocked() {
5487 return isSleepingLocked() || mShuttingDown;
5488 }
5489
5490 boolean isSleepingLocked() {
5491 return mSleeping;
5492 }
5493
Riddle Hsu16567132018-08-16 21:37:47 +08005494 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005495 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005496 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005497 if (task.isActivityTypeStandard()) {
5498 if (mCurAppTimeTracker != r.appTimeTracker) {
5499 // We are switching app tracking. Complete the current one.
5500 if (mCurAppTimeTracker != null) {
5501 mCurAppTimeTracker.stop();
5502 mH.obtainMessage(
5503 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005504 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005505 mCurAppTimeTracker = null;
5506 }
5507 if (r.appTimeTracker != null) {
5508 mCurAppTimeTracker = r.appTimeTracker;
5509 startTimeTrackingFocusedActivityLocked();
5510 }
5511 } else {
5512 startTimeTrackingFocusedActivityLocked();
5513 }
5514 } else {
5515 r.appTimeTracker = null;
5516 }
5517 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5518 // TODO: Probably not, because we don't want to resume voice on switching
5519 // back to this activity
5520 if (task.voiceInteractor != null) {
5521 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5522 } else {
5523 finishRunningVoiceLocked();
5524
5525 if (mLastResumedActivity != null) {
5526 final IVoiceInteractionSession session;
5527
Louis Changcdec0802019-11-11 11:45:07 +08005528 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005529 if (lastResumedActivityTask != null
5530 && lastResumedActivityTask.voiceSession != null) {
5531 session = lastResumedActivityTask.voiceSession;
5532 } else {
5533 session = mLastResumedActivity.voiceSession;
5534 }
5535
5536 if (session != null) {
5537 // We had been in a voice interaction session, but now focused has
5538 // move to something different. Just finish the session, we can't
5539 // return to it and retain the proper state and synchronization with
5540 // the voice interaction service.
5541 finishVoiceTask(session);
5542 }
5543 }
5544 }
5545
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005546 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5547 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005548 }
5549 updateResumedAppTrace(r);
5550 mLastResumedActivity = r;
5551
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005552 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005553
5554 applyUpdateLockStateLocked(r);
5555 applyUpdateVrModeLocked(r);
5556
Jeff Changd136e772019-11-05 20:33:52 +08005557 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005558 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005559 r == null ? "NULL" : r.shortComponentName,
5560 reason);
5561 }
5562
5563 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5564 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005565 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005566 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005567 updateSleepIfNeededLocked();
5568 return token;
5569 }
5570 }
5571
5572 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005573 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005574 final boolean wasSleeping = mSleeping;
5575 boolean updateOomAdj = false;
5576
5577 if (!shouldSleep) {
5578 // If wasSleeping is true, we need to wake up activity manager state from when
5579 // we started sleeping. In either case, we need to apply the sleep tokens, which
5580 // will wake up stacks or put them to sleep as appropriate.
5581 if (wasSleeping) {
5582 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005583 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5584 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005585 startTimeTrackingFocusedActivityLocked();
5586 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005587 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005588 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5589 }
Louis Chang149d5c82019-12-30 09:47:39 +08005590 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005591 if (wasSleeping) {
5592 updateOomAdj = true;
5593 }
5594 } else if (!mSleeping && shouldSleep) {
5595 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005596 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5597 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005598 if (mCurAppTimeTracker != null) {
5599 mCurAppTimeTracker.stop();
5600 }
5601 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005602 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005603 mStackSupervisor.goingToSleepLocked();
5604 updateResumedAppTrace(null /* resumed */);
5605 updateOomAdj = true;
5606 }
5607 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005608 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005609 }
5610 }
5611
5612 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005613 mH.removeCallbacks(mUpdateOomAdjRunnable);
5614 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005615 }
5616
Wale Ogunwale53783742018-09-16 10:21:51 -07005617 void updateCpuStats() {
5618 mH.post(mAmInternal::updateCpuStats);
5619 }
5620
Hui Yu03d12402018-12-06 18:00:37 -08005621 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5622 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005623 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5624 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005625 mH.sendMessage(m);
5626 }
5627
Hui Yu03d12402018-12-06 18:00:37 -08005628 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005629 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005630 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005631 if (task != null) {
5632 final ActivityRecord rootActivity = task.getRootActivity();
5633 if (rootActivity != null) {
5634 taskRoot = rootActivity.mActivityComponent;
5635 }
5636 }
5637
Hui Yu03d12402018-12-06 18:00:37 -08005638 final Message m = PooledLambda.obtainMessage(
5639 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005640 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005641 mH.sendMessage(m);
5642 }
5643
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005644 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5645 String hostingType) {
5646 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005647 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5648 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005649 + activity.processName);
5650 }
5651 // Post message to start process to avoid possible deadlock of calling into AMS with the
5652 // ATMS lock held.
5653 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5654 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5655 isTop, hostingType, activity.intent.getComponent());
5656 mH.sendMessage(m);
5657 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005658 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005659 }
5660 }
5661
Wale Ogunwale53783742018-09-16 10:21:51 -07005662 void setBooting(boolean booting) {
5663 mAmInternal.setBooting(booting);
5664 }
5665
5666 boolean isBooting() {
5667 return mAmInternal.isBooting();
5668 }
5669
5670 void setBooted(boolean booted) {
5671 mAmInternal.setBooted(booted);
5672 }
5673
5674 boolean isBooted() {
5675 return mAmInternal.isBooted();
5676 }
5677
5678 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5679 mH.post(() -> {
5680 if (finishBooting) {
5681 mAmInternal.finishBooting();
5682 }
5683 if (enableScreen) {
5684 mInternal.enableScreenAfterBoot(isBooted());
5685 }
5686 });
5687 }
5688
5689 void setHeavyWeightProcess(ActivityRecord root) {
5690 mHeavyWeightProcess = root.app;
5691 final Message m = PooledLambda.obtainMessage(
5692 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005693 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005694 mH.sendMessage(m);
5695 }
5696
5697 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5698 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5699 return;
5700 }
5701
5702 mHeavyWeightProcess = null;
5703 final Message m = PooledLambda.obtainMessage(
5704 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5705 proc.mUserId);
5706 mH.sendMessage(m);
5707 }
5708
5709 private void cancelHeavyWeightProcessNotification(int userId) {
5710 final INotificationManager inm = NotificationManager.getService();
5711 if (inm == null) {
5712 return;
5713 }
5714 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005715 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005716 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5717 } catch (RuntimeException e) {
5718 Slog.w(TAG, "Error canceling notification for service", e);
5719 } catch (RemoteException e) {
5720 }
5721
5722 }
5723
5724 private void postHeavyWeightProcessNotification(
5725 WindowProcessController proc, Intent intent, int userId) {
5726 if (proc == null) {
5727 return;
5728 }
5729
5730 final INotificationManager inm = NotificationManager.getService();
5731 if (inm == null) {
5732 return;
5733 }
5734
5735 try {
5736 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5737 String text = mContext.getString(R.string.heavy_weight_notification,
5738 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5739 Notification notification =
5740 new Notification.Builder(context,
5741 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5742 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5743 .setWhen(0)
5744 .setOngoing(true)
5745 .setTicker(text)
5746 .setColor(mContext.getColor(
5747 com.android.internal.R.color.system_notification_accent_color))
5748 .setContentTitle(text)
5749 .setContentText(
5750 mContext.getText(R.string.heavy_weight_notification_detail))
5751 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5752 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5753 new UserHandle(userId)))
5754 .build();
5755 try {
5756 inm.enqueueNotificationWithTag("android", "android", null,
5757 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5758 } catch (RuntimeException e) {
5759 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5760 } catch (RemoteException e) {
5761 }
5762 } catch (PackageManager.NameNotFoundException e) {
5763 Slog.w(TAG, "Unable to create context for heavy notification", e);
5764 }
5765
5766 }
5767
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005768 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5769 IBinder token, String resultWho, int requestCode, Intent[] intents,
5770 String[] resolvedTypes, int flags, Bundle bOptions) {
5771
5772 ActivityRecord activity = null;
5773 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5774 activity = ActivityRecord.isInStackLocked(token);
5775 if (activity == null) {
5776 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5777 return null;
5778 }
5779 if (activity.finishing) {
5780 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5781 return null;
5782 }
5783 }
5784
5785 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5786 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5787 bOptions);
5788 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5789 if (noCreate) {
5790 return rec;
5791 }
5792 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5793 if (activity.pendingResults == null) {
5794 activity.pendingResults = new HashSet<>();
5795 }
5796 activity.pendingResults.add(rec.ref);
5797 }
5798 return rec;
5799 }
5800
Andrii Kulian52d255c2018-07-13 11:32:19 -07005801 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005802 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005803 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005804 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5805 mCurAppTimeTracker.start(resumedActivity.packageName);
5806 }
5807 }
5808
5809 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5810 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005811 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005812 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5813 }
5814 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005815 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005816 constructResumedTraceName(resumed.packageName), 0);
5817 }
5818 mTracedResumedActivity = resumed;
5819 }
5820
5821 private String constructResumedTraceName(String packageName) {
5822 return "focused app: " + packageName;
5823 }
5824
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005825 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005826 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005827 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005828 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005829 // mainStack is null during startup.
5830 if (mainStack != null) {
5831 if (changes != 0 && starting == null) {
5832 // If the configuration changed, and the caller is not already
5833 // in the process of starting an activity, then find the top
5834 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005835 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005836 }
5837
5838 if (starting != null) {
5839 kept = starting.ensureActivityConfiguration(changes,
5840 false /* preserveWindow */);
5841 // And we need to make sure at this point that all other activities
5842 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005843 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005844 !PRESERVE_WINDOWS);
5845 }
5846 }
5847
5848 return kept;
5849 }
5850
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005851 void scheduleAppGcsLocked() {
5852 mH.post(() -> mAmInternal.scheduleAppGcs());
5853 }
5854
Wale Ogunwale53783742018-09-16 10:21:51 -07005855 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5856 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5857 }
5858
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005859 /**
5860 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5861 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5862 * on demand.
5863 */
5864 IPackageManager getPackageManager() {
5865 return AppGlobals.getPackageManager();
5866 }
5867
5868 PackageManagerInternal getPackageManagerInternalLocked() {
5869 if (mPmInternal == null) {
5870 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5871 }
5872 return mPmInternal;
5873 }
5874
Hai Zhangf4da9be2019-05-01 13:46:06 +08005875 PermissionPolicyInternal getPermissionPolicyInternal() {
5876 if (mPermissionPolicyInternal == null) {
5877 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5878 }
5879 return mPermissionPolicyInternal;
5880 }
5881
Wale Ogunwale008163e2018-07-23 23:11:08 -07005882 AppWarnings getAppWarningsLocked() {
5883 return mAppWarnings;
5884 }
5885
Wale Ogunwale214f3482018-10-04 11:00:47 -07005886 Intent getHomeIntent() {
5887 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5888 intent.setComponent(mTopComponent);
5889 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5890 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5891 intent.addCategory(Intent.CATEGORY_HOME);
5892 }
5893 return intent;
5894 }
5895
Chilun2ef71f72018-11-16 17:57:15 +08005896 /**
5897 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5898 * activities.
5899 *
5900 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5901 * component defined in config_secondaryHomeComponent.
5902 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5903 */
5904 Intent getSecondaryHomeIntent(String preferredPackage) {
5905 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005906 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5907 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5908 if (preferredPackage == null || useSystemProvidedLauncher) {
5909 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005910 final String secondaryHomeComponent = mContext.getResources().getString(
5911 com.android.internal.R.string.config_secondaryHomeComponent);
5912 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5913 } else {
5914 intent.setPackage(preferredPackage);
5915 }
5916 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5917 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5918 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5919 }
5920 return intent;
5921 }
5922
Wale Ogunwale214f3482018-10-04 11:00:47 -07005923 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5924 if (info == null) return null;
5925 ApplicationInfo newInfo = new ApplicationInfo(info);
5926 newInfo.initForUser(userId);
5927 return newInfo;
5928 }
5929
Wale Ogunwale9c103022018-10-18 07:44:54 -07005930 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005931 if (uid == SYSTEM_UID) {
5932 // The system gets to run in any process. If there are multiple processes with the same
5933 // uid, just pick the first (this should never happen).
5934 final SparseArray<WindowProcessController> procs =
5935 mProcessNames.getMap().get(processName);
5936 if (procs == null) return null;
5937 final int procCount = procs.size();
5938 for (int i = 0; i < procCount; i++) {
5939 final int procUid = procs.keyAt(i);
5940 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5941 // Don't use an app process or different user process for system component.
5942 continue;
5943 }
5944 return procs.valueAt(i);
5945 }
5946 }
5947
5948 return mProcessNames.get(processName, uid);
5949 }
5950
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005951 WindowProcessController getProcessController(IApplicationThread thread) {
5952 if (thread == null) {
5953 return null;
5954 }
5955
5956 final IBinder threadBinder = thread.asBinder();
5957 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5958 for (int i = pmap.size()-1; i >= 0; i--) {
5959 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5960 for (int j = procs.size() - 1; j >= 0; j--) {
5961 final WindowProcessController proc = procs.valueAt(j);
5962 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5963 return proc;
5964 }
5965 }
5966 }
5967
5968 return null;
5969 }
5970
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005971 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005972 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005973 if (proc == null) return null;
5974 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5975 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005976 }
5977 return null;
5978 }
5979
Riddle Hsua0536432019-02-16 00:38:59 +08005980 int getUidState(int uid) {
5981 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005982 }
5983
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005984 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005985 // A uid is considered to be foreground if it has a visible non-toast window.
5986 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005987 }
5988
Ricky Wai96f5c352019-04-10 18:40:17 +01005989 boolean isDeviceOwner(int uid) {
5990 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005991 }
5992
Ricky Wai96f5c352019-04-10 18:40:17 +01005993 void setDeviceOwnerUid(int uid) {
5994 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005995 }
5996
Wale Ogunwale9de19442018-10-18 19:05:03 -07005997 /**
5998 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5999 * the whitelist
6000 */
6001 String getPendingTempWhitelistTagForUidLocked(int uid) {
6002 return mPendingTempWhitelist.get(uid);
6003 }
6004
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006005 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6006 if (true || Build.IS_USER) {
6007 return;
6008 }
6009
6010 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6011 StrictMode.allowThreadDiskWrites();
6012 try {
6013 File tracesDir = new File("/data/anr");
6014 File tracesFile = null;
6015 try {
6016 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6017
6018 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006019 String timeString =
6020 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6021 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006022 sb.append(": ");
6023 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6024 sb.append(" since ");
6025 sb.append(msg);
6026 FileOutputStream fos = new FileOutputStream(tracesFile);
6027 fos.write(sb.toString().getBytes());
6028 if (app == null) {
6029 fos.write("\n*** No application process!".getBytes());
6030 }
6031 fos.close();
6032 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6033 } catch (IOException e) {
6034 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6035 return;
6036 }
6037
6038 if (app != null && app.getPid() > 0) {
6039 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6040 firstPids.add(app.getPid());
6041 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6042 }
6043
6044 File lastTracesFile = null;
6045 File curTracesFile = null;
6046 for (int i=9; i>=0; i--) {
6047 String name = String.format(Locale.US, "slow%02d.txt", i);
6048 curTracesFile = new File(tracesDir, name);
6049 if (curTracesFile.exists()) {
6050 if (lastTracesFile != null) {
6051 curTracesFile.renameTo(lastTracesFile);
6052 } else {
6053 curTracesFile.delete();
6054 }
6055 }
6056 lastTracesFile = curTracesFile;
6057 }
6058 tracesFile.renameTo(curTracesFile);
6059 } finally {
6060 StrictMode.setThreadPolicy(oldPolicy);
6061 }
6062 }
6063
Michal Karpinskida34cd42019-04-02 19:46:52 +01006064 boolean isAssociatedCompanionApp(int userId, int uid) {
6065 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6066 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006067 return false;
6068 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006069 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006070 }
6071
Issei Suzuki734bc942019-06-05 13:59:52 +02006072 void notifySingleTaskDisplayEmpty(int displayId) {
6073 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6074 }
6075
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006076 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006077 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006078
6079
Wale Ogunwale98875612018-10-12 07:53:02 -07006080 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6081 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006082
Riddle Hsud93a6c42018-11-29 21:50:06 +08006083 H(Looper looper) {
6084 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006085 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006086
6087 @Override
6088 public void handleMessage(Message msg) {
6089 switch (msg.what) {
6090 case REPORT_TIME_TRACKER_MSG: {
6091 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6092 tracker.deliverResult(mContext);
6093 } break;
6094 }
6095 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006096 }
6097
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006098 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006099 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006100
6101 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006102 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006103 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006104
6105 @Override
6106 public void handleMessage(Message msg) {
6107 switch (msg.what) {
6108 case DISMISS_DIALOG_UI_MSG: {
6109 final Dialog d = (Dialog) msg.obj;
6110 d.dismiss();
6111 break;
6112 }
6113 }
6114 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006115 }
6116
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006117 final class LocalService extends ActivityTaskManagerInternal {
6118 @Override
6119 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006120 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006121 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006122 }
6123
6124 @Override
6125 public ComponentName getHomeActivityForUser(int userId) {
6126 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006127 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006128 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006129 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006130 }
6131 }
6132
6133 @Override
6134 public void onLocalVoiceInteractionStarted(IBinder activity,
6135 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6136 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006137 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006138 }
6139 }
6140
6141 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006142 public void notifySingleTaskDisplayDrawn(int displayId) {
6143 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6144 }
6145
6146 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006147 public void notifyAppTransitionFinished() {
6148 synchronized (mGlobalLock) {
6149 mStackSupervisor.notifyAppTransitionDone();
6150 }
6151 }
6152
6153 @Override
6154 public void notifyAppTransitionCancelled() {
6155 synchronized (mGlobalLock) {
6156 mStackSupervisor.notifyAppTransitionDone();
6157 }
6158 }
6159
6160 @Override
6161 public List<IBinder> getTopVisibleActivities() {
6162 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006163 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006164 }
6165 }
6166
6167 @Override
6168 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6169 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006170 mRootWindowContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006171 }
6172 }
6173
6174 @Override
6175 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6176 Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006177 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006178 final String[] resolvedTypes = new String[intents.length];
6179
6180 // UID of the package on user userId.
6181 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6182 // packageUid may not be initialized.
6183 int packageUid = 0;
6184 final long ident = Binder.clearCallingIdentity();
6185
6186 try {
6187 for (int i = 0; i < intents.length; i++) {
6188 resolvedTypes[i] =
6189 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6190 }
6191
6192 packageUid = AppGlobals.getPackageManager().getPackageUid(
6193 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6194 } catch (RemoteException e) {
6195 // Shouldn't happen.
6196 } finally {
6197 Binder.restoreCallingIdentity(ident);
6198 }
6199
Riddle Hsu591bf612019-02-14 17:55:31 +08006200 return getActivityStartController().startActivitiesInPackage(
6201 packageUid, packageName,
6202 intents, resolvedTypes, null /* resultTo */,
6203 SafeActivityOptions.fromBundle(bOptions), userId,
6204 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6205 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006206 }
6207
6208 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006209 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6210 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6211 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6212 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006213 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006214 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006215 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006216 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6217 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6218 userId, validateIncomingUser, originatingPendingIntent,
6219 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006220 }
6221 }
6222
6223 @Override
6224 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6225 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6226 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006227 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006228 PendingIntentRecord originatingPendingIntent,
6229 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006230 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006231 synchronized (mGlobalLock) {
6232 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6233 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6234 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006235 validateIncomingUser, originatingPendingIntent,
6236 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006237 }
6238 }
6239
6240 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006241 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6242 Intent intent, Bundle options, int userId) {
6243 return ActivityTaskManagerService.this.startActivityAsUser(
6244 caller, callerPacakge, intent,
6245 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6246 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6247 false /*validateIncomingUser*/);
6248 }
6249
6250 @Override
lumark588a3e82018-07-20 18:53:54 +08006251 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006252 synchronized (mGlobalLock) {
6253
6254 // We might change the visibilities here, so prepare an empty app transition which
6255 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006256 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006257 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006258 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006259 return;
6260 }
Louis Chang677921f2019-12-06 16:44:24 +08006261 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006262 final boolean wasTransitionSet =
6263 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006264 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006265 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006266 }
Louis Chang149d5c82019-12-30 09:47:39 +08006267 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006268
6269 // If there was a transition set already we don't want to interfere with it as we
6270 // might be starting it too early.
6271 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006272 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006273 }
6274 }
6275 if (callback != null) {
6276 callback.run();
6277 }
6278 }
6279
6280 @Override
6281 public void notifyKeyguardTrustedChanged() {
6282 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006283 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006284 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006285 }
6286 }
6287 }
6288
6289 /**
6290 * Called after virtual display Id is updated by
6291 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6292 * {@param vrVr2dDisplayId}.
6293 */
6294 @Override
6295 public void setVr2dDisplayId(int vr2dDisplayId) {
6296 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6297 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006298 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006299 }
6300 }
6301
6302 @Override
6303 public void setFocusedActivity(IBinder token) {
6304 synchronized (mGlobalLock) {
6305 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6306 if (r == null) {
6307 throw new IllegalArgumentException(
6308 "setFocusedActivity: No activity record matching token=" + token);
6309 }
Louis Chang19443452018-10-09 12:10:21 +08006310 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006311 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006312 }
6313 }
6314 }
6315
6316 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006317 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006318 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006319 }
6320
6321 @Override
6322 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006323 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006324 }
6325
6326 @Override
6327 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006328 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006329 }
6330
6331 @Override
6332 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6333 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6334 }
6335
6336 @Override
6337 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006338 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006339 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006340
6341 @Override
6342 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6343 synchronized (mGlobalLock) {
6344 mActiveVoiceInteractionServiceComponent = component;
6345 }
6346 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006347
6348 @Override
6349 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6350 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6351 return;
6352 }
6353 synchronized (mGlobalLock) {
6354 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6355 if (types == null) {
6356 if (uid < 0) {
6357 return;
6358 }
6359 types = new ArrayMap<>();
6360 mAllowAppSwitchUids.put(userId, types);
6361 }
6362 if (uid < 0) {
6363 types.remove(type);
6364 } else {
6365 types.put(type, uid);
6366 }
6367 }
6368 }
6369
6370 @Override
6371 public void onUserStopped(int userId) {
6372 synchronized (mGlobalLock) {
6373 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6374 mAllowAppSwitchUids.remove(userId);
6375 }
6376 }
6377
6378 @Override
6379 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6380 synchronized (mGlobalLock) {
6381 return ActivityTaskManagerService.this.isGetTasksAllowed(
6382 caller, callingPid, callingUid);
6383 }
6384 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006385
Riddle Hsua0536432019-02-16 00:38:59 +08006386 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006387 @Override
6388 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006389 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006390 mProcessNames.put(proc.mName, proc.mUid, proc);
6391 }
6392 }
6393
Riddle Hsua0536432019-02-16 00:38:59 +08006394 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006395 @Override
6396 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006397 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006398 mProcessNames.remove(name, uid);
6399 }
6400 }
6401
Riddle Hsua0536432019-02-16 00:38:59 +08006402 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006403 @Override
6404 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006405 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006406 if (proc == mHomeProcess) {
6407 mHomeProcess = null;
6408 }
6409 if (proc == mPreviousProcess) {
6410 mPreviousProcess = null;
6411 }
6412 }
6413 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006414
Riddle Hsua0536432019-02-16 00:38:59 +08006415 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006416 @Override
6417 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006418 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006419 return mTopProcessState;
6420 }
6421 }
6422
Riddle Hsua0536432019-02-16 00:38:59 +08006423 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006424 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006425 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006426 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006427 return proc == mHeavyWeightProcess;
6428 }
6429 }
6430
Riddle Hsua0536432019-02-16 00:38:59 +08006431 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006432 @Override
6433 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006434 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006435 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6436 }
6437 }
6438
6439 @Override
6440 public void finishHeavyWeightApp() {
6441 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006442 if (mHeavyWeightProcess != null) {
6443 mHeavyWeightProcess.finishActivities();
6444 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006445 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6446 mHeavyWeightProcess);
6447 }
6448 }
6449
Riddle Hsua0536432019-02-16 00:38:59 +08006450 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006451 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006452 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006453 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006454 return isSleepingLocked();
6455 }
6456 }
6457
6458 @Override
6459 public boolean isShuttingDown() {
6460 synchronized (mGlobalLock) {
6461 return mShuttingDown;
6462 }
6463 }
6464
6465 @Override
6466 public boolean shuttingDown(boolean booted, int timeout) {
6467 synchronized (mGlobalLock) {
6468 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006469 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006470 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006471 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006472 return mStackSupervisor.shutdownLocked(timeout);
6473 }
6474 }
6475
6476 @Override
6477 public void enableScreenAfterBoot(boolean booted) {
6478 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006479 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006480 mWindowManager.enableScreenAfterBoot();
6481 updateEventDispatchingLocked(booted);
6482 }
6483 }
6484
6485 @Override
6486 public boolean showStrictModeViolationDialog() {
6487 synchronized (mGlobalLock) {
6488 return mShowDialogs && !mSleeping && !mShuttingDown;
6489 }
6490 }
6491
6492 @Override
6493 public void showSystemReadyErrorDialogsIfNeeded() {
6494 synchronized (mGlobalLock) {
6495 try {
6496 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6497 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6498 + " data partition or your device will be unstable.");
6499 mUiHandler.post(() -> {
6500 if (mShowDialogs) {
6501 AlertDialog d = new BaseErrorDialog(mUiContext);
6502 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6503 d.setCancelable(false);
6504 d.setTitle(mUiContext.getText(R.string.android_system_label));
6505 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6506 d.setButton(DialogInterface.BUTTON_POSITIVE,
6507 mUiContext.getText(R.string.ok),
6508 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6509 d.show();
6510 }
6511 });
6512 }
6513 } catch (RemoteException e) {
6514 }
6515
6516 if (!Build.isBuildConsistent()) {
6517 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6518 mUiHandler.post(() -> {
6519 if (mShowDialogs) {
6520 AlertDialog d = new BaseErrorDialog(mUiContext);
6521 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6522 d.setCancelable(false);
6523 d.setTitle(mUiContext.getText(R.string.android_system_label));
6524 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6525 d.setButton(DialogInterface.BUTTON_POSITIVE,
6526 mUiContext.getText(R.string.ok),
6527 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6528 d.show();
6529 }
6530 });
6531 }
6532 }
6533 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006534
6535 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006536 public void onProcessMapped(int pid, WindowProcessController proc) {
6537 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006538 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006539 }
6540 }
6541
6542 @Override
6543 public void onProcessUnMapped(int pid) {
6544 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006545 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006546 }
6547 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006548
6549 @Override
6550 public void onPackageDataCleared(String name) {
6551 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006552 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006553 mAppWarnings.onPackageDataCleared(name);
6554 }
6555 }
6556
6557 @Override
6558 public void onPackageUninstalled(String name) {
6559 synchronized (mGlobalLock) {
6560 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006561 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006562 }
6563 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006564
6565 @Override
6566 public void onPackageAdded(String name, boolean replacing) {
6567 synchronized (mGlobalLock) {
6568 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6569 }
6570 }
6571
6572 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006573 public void onPackageReplaced(ApplicationInfo aInfo) {
6574 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006575 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006576 }
6577 }
6578
6579 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006580 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6581 synchronized (mGlobalLock) {
6582 return compatibilityInfoForPackageLocked(ai);
6583 }
6584 }
6585
Yunfan Chen75157d72018-07-27 14:47:21 +09006586 /**
6587 * Set the corresponding display information for the process global configuration. To be
6588 * called when we need to show IME on a different display.
6589 *
6590 * @param pid The process id associated with the IME window.
6591 * @param displayId The ID of the display showing the IME.
6592 */
6593 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006594 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006595 // Don't update process-level configuration for Multi-Client IME process since other
6596 // IMEs on other displays will also receive this configuration change due to IME
6597 // services use the same application config/context.
6598 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006599
Yunfan Chen75157d72018-07-27 14:47:21 +09006600 if (pid == MY_PID || pid < 0) {
6601 if (DEBUG_CONFIGURATION) {
6602 Slog.w(TAG,
6603 "Trying to update display configuration for system/invalid process.");
6604 }
6605 return;
6606 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006607 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006608 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006609 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006610 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006611 // Call might come when display is not yet added or has been removed.
6612 if (DEBUG_CONFIGURATION) {
6613 Slog.w(TAG, "Trying to update display configuration for non-existing "
6614 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006615 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006616 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006617 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006618 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006619 if (process == null) {
6620 if (DEBUG_CONFIGURATION) {
6621 Slog.w(TAG, "Trying to update display configuration for invalid "
6622 + "process, pid=" + pid);
6623 }
6624 return;
6625 }
lumarkddc77fb2019-06-27 22:22:23 +08006626 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006627 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006628 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006629 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006630
6631 @Override
6632 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006633 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006634 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006635 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006636 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006637 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006638 }
6639 }
6640 }
6641
6642 @Override
6643 public void clearPendingResultForActivity(IBinder activityToken,
6644 WeakReference<PendingIntentRecord> pir) {
6645 synchronized (mGlobalLock) {
6646 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6647 if (r != null && r.pendingResults != null) {
6648 r.pendingResults.remove(pir);
6649 }
6650 }
6651 }
6652
6653 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006654 public ActivityTokens getTopActivityForTask(int taskId) {
6655 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006656 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006657 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006658 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6659 + " Requested task not found");
6660 return null;
6661 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006662 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006663 if (activity == null) {
6664 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6665 + " Requested activity not found");
6666 return null;
6667 }
6668 if (!activity.attachedToProcess()) {
6669 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6670 + activity);
6671 return null;
6672 }
6673 return new ActivityTokens(activity.appToken, activity.assistToken,
6674 activity.app.getThread());
6675 }
6676 }
6677
6678 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006679 public IIntentSender getIntentSender(int type, String packageName,
6680 int callingUid, int userId, IBinder token, String resultWho,
6681 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6682 Bundle bOptions) {
6683 synchronized (mGlobalLock) {
6684 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6685 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6686 }
6687 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006688
6689 @Override
6690 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6691 synchronized (mGlobalLock) {
6692 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6693 if (r == null) {
6694 return null;
6695 }
6696 if (r.mServiceConnectionsHolder == null) {
6697 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6698 ActivityTaskManagerService.this, r);
6699 }
6700
6701 return r.mServiceConnectionsHolder;
6702 }
6703 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006704
6705 @Override
6706 public Intent getHomeIntent() {
6707 synchronized (mGlobalLock) {
6708 return ActivityTaskManagerService.this.getHomeIntent();
6709 }
6710 }
6711
6712 @Override
6713 public boolean startHomeActivity(int userId, String reason) {
6714 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006715 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006716 }
6717 }
6718
6719 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006720 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006721 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006722 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006723 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006724 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006725 }
Chilun8b1f1be2019-03-13 17:14:36 +08006726 }
6727
6728 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006729 public boolean startHomeOnAllDisplays(int userId, String reason) {
6730 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006731 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006732 }
6733 }
6734
Riddle Hsua0536432019-02-16 00:38:59 +08006735 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006736 @Override
6737 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006738 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006739 if (mFactoryTest == FACTORY_TEST_OFF) {
6740 return false;
6741 }
6742 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6743 && wpc.mName.equals(mTopComponent.getPackageName())) {
6744 return true;
6745 }
6746 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6747 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6748 }
6749 }
6750
6751 @Override
6752 public void updateTopComponentForFactoryTest() {
6753 synchronized (mGlobalLock) {
6754 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6755 return;
6756 }
6757 final ResolveInfo ri = mContext.getPackageManager()
6758 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6759 final CharSequence errorMsg;
6760 if (ri != null) {
6761 final ActivityInfo ai = ri.activityInfo;
6762 final ApplicationInfo app = ai.applicationInfo;
6763 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6764 mTopAction = Intent.ACTION_FACTORY_TEST;
6765 mTopData = null;
6766 mTopComponent = new ComponentName(app.packageName, ai.name);
6767 errorMsg = null;
6768 } else {
6769 errorMsg = mContext.getResources().getText(
6770 com.android.internal.R.string.factorytest_not_system);
6771 }
6772 } else {
6773 errorMsg = mContext.getResources().getText(
6774 com.android.internal.R.string.factorytest_no_action);
6775 }
6776 if (errorMsg == null) {
6777 return;
6778 }
6779
6780 mTopAction = null;
6781 mTopData = null;
6782 mTopComponent = null;
6783 mUiHandler.post(() -> {
6784 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6785 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006786 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006787 });
6788 }
6789 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006790
Riddle Hsua0536432019-02-16 00:38:59 +08006791 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006792 @Override
6793 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6794 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006795 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006796 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006797 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006798
6799 wpc.clearRecentTasks();
6800 wpc.clearActivities();
6801
6802 if (wpc.isInstrumenting()) {
6803 finishInstrumentationCallback.run();
6804 }
6805
Jorim Jaggid0752812018-10-16 16:07:20 +02006806 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006807 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006808 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006809 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006810 // If there was nothing to resume, and we are not already restarting
6811 // this process, but there is a visible activity that is hosted by the
6812 // process...then make sure all visible activities are running, taking
6813 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006814 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006815 !PRESERVE_WINDOWS);
6816 }
6817 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006818 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006819 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006820 }
6821 }
6822 }
6823
6824 @Override
6825 public void closeSystemDialogs(String reason) {
6826 enforceNotIsolatedCaller("closeSystemDialogs");
6827
6828 final int pid = Binder.getCallingPid();
6829 final int uid = Binder.getCallingUid();
6830 final long origId = Binder.clearCallingIdentity();
6831 try {
6832 synchronized (mGlobalLock) {
6833 // Only allow this from foreground processes, so that background
6834 // applications can't abuse it to prevent system UI from being shown.
6835 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006836 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006837 if (!proc.isPerceptible()) {
6838 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6839 + " from background process " + proc);
6840 return;
6841 }
6842 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006843 mWindowManager.closeSystemDialogs(reason);
6844
Louis Chang149d5c82019-12-30 09:47:39 +08006845 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006846 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006847 // Call into AM outside the synchronized block.
6848 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006849 } finally {
6850 Binder.restoreCallingIdentity(origId);
6851 }
6852 }
6853
6854 @Override
6855 public void cleanupDisabledPackageComponents(
6856 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6857 synchronized (mGlobalLock) {
6858 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006859 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006860 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006861 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006862 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006863 }
6864
6865 // Clean-up disabled tasks
6866 getRecentTasks().cleanupDisabledPackageTasksLocked(
6867 packageName, disabledClasses, userId);
6868 }
6869 }
6870
6871 @Override
6872 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6873 int userId) {
6874 synchronized (mGlobalLock) {
6875
6876 boolean didSomething =
6877 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006878 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 null, doit, evenPersistent, userId);
6880 return didSomething;
6881 }
6882 }
6883
6884 @Override
6885 public void resumeTopActivities(boolean scheduleIdle) {
6886 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006887 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006888 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006889 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006890 }
6891 }
6892 }
6893
Riddle Hsua0536432019-02-16 00:38:59 +08006894 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006895 @Override
6896 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006897 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006898 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6899 }
6900 }
6901
Riddle Hsua0536432019-02-16 00:38:59 +08006902 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006903 @Override
6904 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006905 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006906 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6907 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6908 }
6909 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006910 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006911 } finally {
6912 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6913 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006914 }
6915 }
6916
6917 @Override
6918 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6919 try {
6920 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6921 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6922 }
6923 } catch (RemoteException ex) {
6924 throw new SecurityException("Fail to check is caller a privileged app", ex);
6925 }
6926
6927 synchronized (mGlobalLock) {
6928 final long ident = Binder.clearCallingIdentity();
6929 try {
6930 if (mAmInternal.shouldConfirmCredentials(userId)) {
6931 if (mKeyguardController.isKeyguardLocked()) {
6932 // Showing launcher to avoid user entering credential twice.
6933 startHomeActivity(currentUserId, "notifyLockedProfile");
6934 }
Louis Chang149d5c82019-12-30 09:47:39 +08006935 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006936 }
6937 } finally {
6938 Binder.restoreCallingIdentity(ident);
6939 }
6940 }
6941 }
6942
6943 @Override
6944 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6945 mAmInternal.enforceCallingPermission(
6946 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6947
6948 synchronized (mGlobalLock) {
6949 final long ident = Binder.clearCallingIdentity();
6950 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006951 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6952 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006953 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006954 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6955 UserHandle.CURRENT);
6956 } finally {
6957 Binder.restoreCallingIdentity(ident);
6958 }
6959 }
6960 }
6961
6962 @Override
6963 public void writeActivitiesToProto(ProtoOutputStream proto) {
6964 synchronized (mGlobalLock) {
6965 // The output proto of "activity --proto activities"
6966 // is ActivityManagerServiceDumpActivitiesProto
Louis Chang149d5c82019-12-30 09:47:39 +08006967 mRootWindowContainer.dumpDebug(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006968 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6969 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006970 }
6971 }
6972
6973 @Override
6974 public void saveANRState(String reason) {
6975 synchronized (mGlobalLock) {
6976 final StringWriter sw = new StringWriter();
6977 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6978 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6979 if (reason != null) {
6980 pw.println(" Reason: " + reason);
6981 }
6982 pw.println();
6983 getActivityStartController().dump(pw, " ", null);
6984 pw.println();
6985 pw.println("-------------------------------------------------------------------------------");
6986 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6987 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6988 "" /* header */);
6989 pw.println();
6990 pw.close();
6991
6992 mLastANRState = sw.toString();
6993 }
6994 }
6995
6996 @Override
6997 public void clearSavedANRState() {
6998 synchronized (mGlobalLock) {
6999 mLastANRState = null;
7000 }
7001 }
7002
7003 @Override
7004 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7005 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7006 synchronized (mGlobalLock) {
7007 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7008 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7009 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7010 dumpLastANRLocked(pw);
7011 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7012 dumpLastANRTracesLocked(pw);
7013 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7014 dumpActivityStarterLocked(pw, dumpPackage);
7015 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7016 dumpActivityContainersLocked(pw);
7017 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7018 if (getRecentTasks() != null) {
7019 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7020 }
7021 }
7022 }
7023 }
7024
7025 @Override
7026 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7027 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7028 int wakefulness) {
7029 synchronized (mGlobalLock) {
7030 if (mHomeProcess != null && (dumpPackage == null
7031 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7032 if (needSep) {
7033 pw.println();
7034 needSep = false;
7035 }
7036 pw.println(" mHomeProcess: " + mHomeProcess);
7037 }
7038 if (mPreviousProcess != null && (dumpPackage == null
7039 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7040 if (needSep) {
7041 pw.println();
7042 needSep = false;
7043 }
7044 pw.println(" mPreviousProcess: " + mPreviousProcess);
7045 }
7046 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7047 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7048 StringBuilder sb = new StringBuilder(128);
7049 sb.append(" mPreviousProcessVisibleTime: ");
7050 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7051 pw.println(sb);
7052 }
7053 if (mHeavyWeightProcess != null && (dumpPackage == null
7054 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7055 if (needSep) {
7056 pw.println();
7057 needSep = false;
7058 }
7059 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7060 }
7061 if (dumpPackage == null) {
7062 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007063 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007064 }
7065 if (dumpAll) {
7066 if (dumpPackage == null) {
7067 pw.println(" mConfigWillChange: "
7068 + getTopDisplayFocusedStack().mConfigWillChange);
7069 }
7070 if (mCompatModePackages.getPackages().size() > 0) {
7071 boolean printed = false;
7072 for (Map.Entry<String, Integer> entry
7073 : mCompatModePackages.getPackages().entrySet()) {
7074 String pkg = entry.getKey();
7075 int mode = entry.getValue();
7076 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7077 continue;
7078 }
7079 if (!printed) {
7080 pw.println(" mScreenCompatPackages:");
7081 printed = true;
7082 }
7083 pw.println(" " + pkg + ": " + mode);
7084 }
7085 }
7086 }
7087
7088 if (dumpPackage == null) {
7089 pw.println(" mWakefulness="
7090 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007091 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007092 if (mRunningVoice != null) {
7093 pw.println(" mRunningVoice=" + mRunningVoice);
7094 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7095 }
7096 pw.println(" mSleeping=" + mSleeping);
7097 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7098 pw.println(" mVrController=" + mVrController);
7099 }
7100 if (mCurAppTimeTracker != null) {
7101 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7102 }
7103 if (mAllowAppSwitchUids.size() > 0) {
7104 boolean printed = false;
7105 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7106 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7107 for (int j = 0; j < types.size(); j++) {
7108 if (dumpPackage == null ||
7109 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7110 if (needSep) {
7111 pw.println();
7112 needSep = false;
7113 }
7114 if (!printed) {
7115 pw.println(" mAllowAppSwitchUids:");
7116 printed = true;
7117 }
7118 pw.print(" User ");
7119 pw.print(mAllowAppSwitchUids.keyAt(i));
7120 pw.print(": Type ");
7121 pw.print(types.keyAt(j));
7122 pw.print(" = ");
7123 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7124 pw.println();
7125 }
7126 }
7127 }
7128 }
7129 if (dumpPackage == null) {
7130 if (mController != null) {
7131 pw.println(" mController=" + mController
7132 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7133 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007134 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7135 pw.println(" mLaunchingActivityWakeLock="
7136 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007137 }
7138
7139 return needSep;
7140 }
7141 }
7142
7143 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007144 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7145 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007146 synchronized (mGlobalLock) {
7147 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007148 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007149 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007150 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7151 if (mRunningVoice != null) {
7152 final long vrToken = proto.start(
7153 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7154 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7155 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007156 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007157 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7158 proto.end(vrToken);
7159 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007160 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007161 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007162 if (mController != null) {
7163 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007164 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7165 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007166 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7167 proto.end(token);
7168 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007169 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7170 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007171 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007172 }
7173
7174 if (mHomeProcess != null && (dumpPackage == null
7175 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007176 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007177 }
7178
7179 if (mPreviousProcess != null && (dumpPackage == null
7180 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007181 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007182 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7183 }
7184
7185 if (mHeavyWeightProcess != null && (dumpPackage == null
7186 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007187 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007188 }
7189
7190 for (Map.Entry<String, Integer> entry
7191 : mCompatModePackages.getPackages().entrySet()) {
7192 String pkg = entry.getKey();
7193 int mode = entry.getValue();
7194 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7195 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7196 proto.write(PACKAGE, pkg);
7197 proto.write(MODE, mode);
7198 proto.end(compatToken);
7199 }
7200 }
7201
7202 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007203 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007204 }
7205
7206 }
7207 }
7208
7209 @Override
7210 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7211 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7212 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007213 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7214 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007215 }
7216
7217 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007218 public void dumpForOom(PrintWriter pw) {
7219 synchronized (mGlobalLock) {
7220 pw.println(" mHomeProcess: " + mHomeProcess);
7221 pw.println(" mPreviousProcess: " + mPreviousProcess);
7222 if (mHeavyWeightProcess != null) {
7223 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7224 }
7225 }
7226 }
7227
7228 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007229 public boolean canGcNow() {
7230 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007231 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007232 }
7233 }
7234
Riddle Hsua0536432019-02-16 00:38:59 +08007235 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007236 @Override
7237 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007238 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007239 if (mRootWindowContainer == null) {
7240 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007241 // oomadj after AMS created.
7242 return null;
7243 }
Louis Chang149d5c82019-12-30 09:47:39 +08007244 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007245 return top != null ? top.app : null;
7246 }
7247 }
7248
Riddle Hsua0536432019-02-16 00:38:59 +08007249 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007250 @Override
7251 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007252 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007253 if (mRootWindowContainer != null) {
7254 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007255 }
7256 }
7257 }
7258
7259 @Override
7260 public void scheduleDestroyAllActivities(String reason) {
7261 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007262 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007263 }
7264 }
7265
7266 @Override
7267 public void removeUser(int userId) {
7268 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007269 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007270 }
7271 }
7272
7273 @Override
7274 public boolean switchUser(int userId, UserState userState) {
7275 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007276 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007277 }
7278 }
7279
7280 @Override
7281 public void onHandleAppCrash(WindowProcessController wpc) {
7282 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007283 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007284 }
7285 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007286
7287 @Override
7288 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7289 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007290 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007291 }
7292 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007293
Riddle Hsua0536432019-02-16 00:38:59 +08007294 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007295 @Override
7296 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007297 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007298 }
7299
Riddle Hsua0536432019-02-16 00:38:59 +08007300 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007301 @Override
7302 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007303 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007304 }
7305
Riddle Hsua0536432019-02-16 00:38:59 +08007306 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007307 @Override
7308 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007309 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007310 }
7311
Riddle Hsua0536432019-02-16 00:38:59 +08007312 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007313 @Override
7314 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007315 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007316 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007317
7318 @Override
7319 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007320 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007321 mPendingTempWhitelist.put(uid, tag);
7322 }
7323 }
7324
7325 @Override
7326 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007327 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007328 mPendingTempWhitelist.remove(uid);
7329 }
7330 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007331
7332 @Override
7333 public boolean handleAppCrashInActivityController(String processName, int pid,
7334 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7335 Runnable killCrashingAppCallback) {
7336 synchronized (mGlobalLock) {
7337 if (mController == null) {
7338 return false;
7339 }
7340
7341 try {
7342 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7343 stackTrace)) {
7344 killCrashingAppCallback.run();
7345 return true;
7346 }
7347 } catch (RemoteException e) {
7348 mController = null;
7349 Watchdog.getInstance().setActivityController(null);
7350 }
7351 return false;
7352 }
7353 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007354
7355 @Override
7356 public void removeRecentTasksByPackageName(String packageName, int userId) {
7357 synchronized (mGlobalLock) {
7358 mRecentTasks.removeTasksByPackageName(packageName, userId);
7359 }
7360 }
7361
7362 @Override
7363 public void cleanupRecentTasksForUser(int userId) {
7364 synchronized (mGlobalLock) {
7365 mRecentTasks.cleanupLocked(userId);
7366 }
7367 }
7368
7369 @Override
7370 public void loadRecentTasksForUser(int userId) {
7371 synchronized (mGlobalLock) {
7372 mRecentTasks.loadUserRecentsLocked(userId);
7373 }
7374 }
7375
7376 @Override
7377 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7378 synchronized (mGlobalLock) {
7379 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7380 }
7381 }
7382
7383 @Override
7384 public void flushRecentTasks() {
7385 mRecentTasks.flush();
7386 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007387
7388 @Override
7389 public WindowProcessController getHomeProcess() {
7390 synchronized (mGlobalLock) {
7391 return mHomeProcess;
7392 }
7393 }
7394
7395 @Override
7396 public WindowProcessController getPreviousProcess() {
7397 synchronized (mGlobalLock) {
7398 return mPreviousProcess;
7399 }
7400 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007401
7402 @Override
7403 public void clearLockedTasks(String reason) {
7404 synchronized (mGlobalLock) {
7405 getLockTaskController().clearLockedTasks(reason);
7406 }
7407 }
7408
7409 @Override
7410 public void updateUserConfiguration() {
7411 synchronized (mGlobalLock) {
7412 final Configuration configuration = new Configuration(getGlobalConfiguration());
7413 final int currentUserId = mAmInternal.getCurrentUserId();
7414 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7415 configuration, currentUserId, Settings.System.canWrite(mContext));
7416 updateConfigurationLocked(configuration, null /* starting */,
7417 false /* initLocale */, false /* persistent */, currentUserId,
7418 false /* deferResume */);
7419 }
7420 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007421
7422 @Override
7423 public boolean canShowErrorDialogs() {
7424 synchronized (mGlobalLock) {
7425 return mShowDialogs && !mSleeping && !mShuttingDown
7426 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7427 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7428 mAmInternal.getCurrentUserId())
7429 && !(UserManager.isDeviceInDemoMode(mContext)
7430 && mAmInternal.getCurrentUser().isDemo());
7431 }
7432 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007433
7434 @Override
7435 public void setProfileApp(String profileApp) {
7436 synchronized (mGlobalLock) {
7437 mProfileApp = profileApp;
7438 }
7439 }
7440
7441 @Override
7442 public void setProfileProc(WindowProcessController wpc) {
7443 synchronized (mGlobalLock) {
7444 mProfileProc = wpc;
7445 }
7446 }
7447
7448 @Override
7449 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7450 synchronized (mGlobalLock) {
7451 mProfilerInfo = profilerInfo;
7452 }
7453 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007454
7455 @Override
7456 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7457 synchronized (mGlobalLock) {
7458 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7459 }
7460 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007461
7462 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007463 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7464 boolean reducedResolution) {
7465 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7466 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007467 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007468
7469 @Override
7470 public boolean isUidForeground(int uid) {
7471 synchronized (mGlobalLock) {
7472 return ActivityTaskManagerService.this.isUidForeground(uid);
7473 }
7474 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007475
7476 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007477 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007478 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007479 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007480 }
7481 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007482
7483 @Override
7484 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007485 // Translate package names into UIDs
7486 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007487 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007488 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7489 if (uid >= 0) {
7490 result.add(uid);
7491 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007492 }
7493 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007494 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007495 }
7496 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007497 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007498}