blob: 945893986ae3b25f2c60c1abbb0e31f6f6c84a46 [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;
40import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070041import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070042import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070043import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070044import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070045import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
46import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070047import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070048import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070049import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
50import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070052import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070053import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080054import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070055import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070059import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
60import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070061import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040062import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.view.Display.DEFAULT_DISPLAY;
64import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070065import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070066
Yunfan Chen79b96062018-10-17 12:45:23 -070067import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
68import static com.android.server.am.ActivityManagerService.MY_PID;
69import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
70import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwalef342f062020-01-27 07:34:13 -080071import static com.android.server.am.ActivityManagerServiceDumpActivitiesProto.ROOT_WINDOW_CONTAINER;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Jeff Changd136e772019-11-05 20:33:52 +080086import static com.android.server.am.EventLogTags.writeBootProgressEnableScreen;
87import static com.android.server.am.EventLogTags.writeConfigurationChanged;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070088import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
89import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Louis Chang149d5c82019-12-30 09:47:39 +0800120import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
Louis Changcdec0802019-11-11 11:45:07 +0800122import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800127import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700128import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.annotation.Nullable;
130import android.annotation.UserIdInt;
131import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700132import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700133import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.ActivityOptions;
135import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700136import android.app.ActivityThread;
137import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700138import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100139import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700140import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700141import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700142import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.IApplicationThread;
144import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400146import android.app.IRequestFinishCallback;
Evan Rosky0037e5f2019-11-05 10:26:24 -0800147import android.app.ITaskOrganizerController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700149import android.app.Notification;
150import android.app.NotificationManager;
151import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700152import android.app.PictureInPictureParams;
153import android.app.ProfilerInfo;
154import android.app.RemoteAction;
155import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700156import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.app.admin.DevicePolicyCache;
158import android.app.assist.AssistContent;
159import android.app.assist.AssistStructure;
jorgegil@google.com06bc3232019-10-31 14:51:22 -0700160import android.app.servertransaction.ClientTransaction;
161import android.app.servertransaction.EnterPipRequestedItem;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700162import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700163import android.content.ActivityNotFoundException;
164import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700166import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.IIntentSender;
169import android.content.Intent;
170import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700171import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900172import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700173import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700174import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.content.pm.ParceledListSlice;
177import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700178import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700180import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700181import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.graphics.Bitmap;
183import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700184import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700185import android.metrics.LogMaker;
186import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700187import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700189import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700190import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700191import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700192import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700193import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700194import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700195import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800196import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700197import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700200import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100201import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700204import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700205import android.os.SystemClock;
206import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700207import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700208import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700210import android.os.UserManager;
211import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700212import android.os.storage.IStorageManager;
213import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700214import android.provider.Settings;
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 Roskyaf9f27c2020-02-18 18:58:35 +0000231import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700233
Evan Rosky4505b352018-09-06 11:20:40 -0700234import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700235import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.app.AssistUtils;
237import 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;
Wale Ogunwale59507092018-10-29 09:00:30 -0700260import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
261import com.android.server.am.AppTimeTracker;
262import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700263import com.android.server.am.PendingIntentController;
264import com.android.server.am.PendingIntentRecord;
265import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700266import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700267import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700268import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800269import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700270import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700278import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700279import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700280import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800281import java.lang.annotation.ElementType;
282import java.lang.annotation.Retention;
283import java.lang.annotation.RetentionPolicy;
284import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700285import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700287import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700288import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400290import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700291import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700292import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700293import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700294import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000295import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700296import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700297
298/**
299 * System service for managing activities and their containers (task, stacks, displays,... ).
300 *
301 * {@hide}
302 */
303public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700304 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800305 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000306 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700307 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
308 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
309 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
310 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700311 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700312
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700313 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700314 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700316 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100317 // How long we permit background activity starts after an activity in the process
318 // started or finished.
319 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700320
Wale Ogunwale98875612018-10-12 07:53:02 -0700321 /** Used to indicate that an app transition should be animated. */
322 static final boolean ANIMATE = true;
323
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700324 /** Hardware-reported OpenGLES version. */
325 final int GL_ES_VERSION;
326
Wale Ogunwale31913b52018-10-13 08:29:31 -0700327 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
328 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
329 public static final String DUMP_LASTANR_CMD = "lastanr" ;
330 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
331 public static final String DUMP_STARTER_CMD = "starter" ;
332 public static final String DUMP_CONTAINERS_CMD = "containers" ;
333 public static final String DUMP_RECENTS_CMD = "recents" ;
334 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
335
Wale Ogunwale64258362018-10-16 15:13:37 -0700336 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
337 public static final int RELAUNCH_REASON_NONE = 0;
338 /** This activity is being relaunched due to windowing mode change. */
339 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
340 /** This activity is being relaunched due to a free-resize operation. */
341 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
342
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700343 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700344
Wale Ogunwalef6733932018-06-27 05:14:34 -0700345 /**
346 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
347 * change at runtime. Use mContext for non-UI purposes.
348 */
349 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700350 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700351 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700352 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700353 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700354 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700355 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800356 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800357 @VisibleForTesting
358 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700359 PowerManagerInternal mPowerManagerInternal;
360 private UsageStatsManagerInternal mUsageStatsInternal;
361
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700362 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700363 IntentFirewall mIntentFirewall;
364
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700365 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800366 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800367 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700368 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800369 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
370 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
371 *
372 * @see WindowManagerThreadPriorityBooster
373 */
374 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700375 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800376 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700377 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700378 private UserManagerService mUserManager;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800379 private AppOpsManager mAppOpsManager;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700380 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800381 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700382 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700383 /** All processes currently running that might have a window organized by name. */
384 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100385 /** All processes we currently have running mapped by pid and uid */
386 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700387 /** This is the process holding what we currently consider to be the "home" activity. */
388 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700389 /** The currently running heavy-weight process, if any. */
390 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700391 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700392 /**
393 * This is the process holding the activity the user last visited that is in a different process
394 * from the one they are currently in.
395 */
396 WindowProcessController mPreviousProcess;
397 /** The time at which the previous process was last visible. */
398 long mPreviousProcessVisibleTime;
399
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700400 /** List of intents that were used to start the most recent tasks. */
401 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700402 /** State of external calls telling us if the device is awake or asleep. */
403 private boolean mKeyguardShown = false;
404
405 // Wrapper around VoiceInteractionServiceManager
406 private AssistUtils mAssistUtils;
407
408 // VoiceInteraction session ID that changes for each new request except when
409 // being called for multi-window assist in a single session.
410 private int mViSessionId = 1000;
411
412 // How long to wait in getAssistContextExtras for the activity and foreground services
413 // to respond with the result.
414 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
415
416 // How long top wait when going through the modern assist (which doesn't need to block
417 // on getting this result before starting to launch its UI).
418 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
419
420 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
421 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
422
Alison Cichowlas3e340502018-08-07 17:15:01 -0400423 // Permission tokens are used to temporarily granted a trusted app the ability to call
424 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
425 // showing any appropriate error messages to the user.
426 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
427 10 * MINUTE_IN_MILLIS;
428
429 // How long before the service actually expires a token. This is slightly longer than
430 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
431 // expiration exception.
432 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
433 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
434
435 // How long the service will remember expired tokens, for the purpose of providing error
436 // messaging when a client uses an expired token.
437 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
438 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
439
440 // Activity tokens of system activities that are delegating their call to
441 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
442 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
443
444 // Permission tokens that have expired, but we remember for error reporting.
445 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
446
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700447 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
448
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700449 // Keeps track of the active voice interaction service component, notified from
450 // VoiceInteractionManagerService
451 ComponentName mActiveVoiceInteractionServiceComponent;
452
Michal Karpinskida34cd42019-04-02 19:46:52 +0100453 // A map userId and all its companion app uids
454 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000455
Wale Ogunwalee2172292018-10-25 10:11:10 -0700456 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700457 KeyguardController mKeyguardController;
458 private final ClientLifecycleManager mLifecycleManager;
459 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700460 /** The controller for all operations related to locktask. */
461 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700462 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700463
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700464 boolean mSuppressResizeConfigChanges;
465
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700466 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700467 new UpdateConfigurationResult();
468
469 static final class UpdateConfigurationResult {
470 // Configuration changes that were updated.
471 int changes;
472 // If the activity was relaunched to match the new configuration.
473 boolean activityRelaunched;
474
475 void reset() {
476 changes = 0;
477 activityRelaunched = false;
478 }
479 }
480
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700482 private int mConfigurationSeq;
483 // To cache the list of supported system locales
484 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700485
486 /**
487 * Temp object used when global and/or display override configuration is updated. It is also
488 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
489 * anyone...
490 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700491 private Configuration mTempConfig = new Configuration();
492
Wale Ogunwalef6733932018-06-27 05:14:34 -0700493 /** Temporary to avoid allocations. */
494 final StringBuilder mStringBuilder = new StringBuilder(256);
495
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700496 // Amount of time after a call to stopAppSwitches() during which we will
497 // prevent further untrusted switches from happening.
498 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
499
500 /**
501 * The time at which we will allow normal application switches again,
502 * after a call to {@link #stopAppSwitches()}.
503 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700504 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700505 /**
506 * This is set to true after the first switch after mAppSwitchesAllowedTime
507 * is set; any switches after that will clear the time.
508 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700509 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700510
Ricky Wai906af482019-06-03 17:25:28 +0100511 /**
512 * Last stop app switches time, apps finished before this time cannot start background activity
513 * even if they are in grace period.
514 */
515 private long mLastStopAppSwitchesTime;
516
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700517 IActivityController mController = null;
518 boolean mControllerIsAMonkey = false;
519
Wale Ogunwale214f3482018-10-04 11:00:47 -0700520 final int mFactoryTest;
521
522 /** Used to control how we initialize the service. */
523 ComponentName mTopComponent;
524 String mTopAction = Intent.ACTION_MAIN;
525 String mTopData;
526
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800527 /** Profiling app information. */
528 String mProfileApp = null;
529 WindowProcessController mProfileProc = null;
530 ProfilerInfo mProfilerInfo = null;
531
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700532 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700533 * Dump of the activity state at the time of the last ANR. Cleared after
534 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
535 */
536 String mLastANRState;
537
538 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700539 * Used to retain an update lock when the foreground activity is in
540 * immersive mode.
541 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700542 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700543
544 /**
545 * Packages that are being allowed to perform unrestricted app switches. Mapping is
546 * User -> Type -> uid.
547 */
548 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
549
550 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700551 private int mThumbnailWidth;
552 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700553
554 /**
555 * Flag that indicates if multi-window is enabled.
556 *
557 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
558 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
559 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
560 * At least one of the forms of multi-window must be enabled in order for this flag to be
561 * initialized to 'true'.
562 *
563 * @see #mSupportsSplitScreenMultiWindow
564 * @see #mSupportsFreeformWindowManagement
565 * @see #mSupportsPictureInPicture
566 * @see #mSupportsMultiDisplay
567 */
568 boolean mSupportsMultiWindow;
569 boolean mSupportsSplitScreenMultiWindow;
570 boolean mSupportsFreeformWindowManagement;
571 boolean mSupportsPictureInPicture;
572 boolean mSupportsMultiDisplay;
573 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700574 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700575
576 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
577
578 // VR Vr2d Display Id.
579 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700580
Wale Ogunwalef6733932018-06-27 05:14:34 -0700581 /**
582 * Set while we are wanting to sleep, to prevent any
583 * activities from being started/resumed.
584 *
585 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
586 *
587 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
588 * while in the sleep state until there is a pending transition out of sleep, in which case
589 * mSleeping is set to false, and remains false while awake.
590 *
591 * Whether mSleeping can quickly toggled between true/false without the device actually
592 * display changing states is undefined.
593 */
594 private boolean mSleeping = false;
595
596 /**
597 * The process state used for processes that are running the top activities.
598 * This changes between TOP and TOP_SLEEPING to following mSleeping.
599 */
600 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
601
Riddle Hsua0022cd2019-09-09 21:12:41 +0800602 @Retention(RetentionPolicy.SOURCE)
603 @IntDef({
604 LAYOUT_REASON_CONFIG_CHANGED,
605 LAYOUT_REASON_VISIBILITY_CHANGED,
606 })
607 @interface LayoutReason {}
608 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
609 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
610
611 /** The reasons to perform surface placement. */
612 @LayoutReason
613 private int mLayoutReasons;
614
Wale Ogunwalef6733932018-06-27 05:14:34 -0700615 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
616 // automatically. Important for devices without direct input devices.
617 private boolean mShowDialogs = true;
618
619 /** Set if we are shutting down the system, similar to sleeping. */
620 boolean mShuttingDown = false;
621
622 /**
623 * We want to hold a wake lock while running a voice interaction session, since
624 * this may happen with the screen off and we need to keep the CPU running to
625 * be able to continue to interact with the user.
626 */
627 PowerManager.WakeLock mVoiceWakeLock;
628
629 /**
630 * Set while we are running a voice interaction. This overrides sleeping while it is active.
631 */
632 IVoiceInteractionSession mRunningVoice;
633
634 /**
635 * The last resumed activity. This is identical to the current resumed activity most
636 * of the time but could be different when we're pausing one activity before we resume
637 * another activity.
638 */
639 ActivityRecord mLastResumedActivity;
640
641 /**
642 * The activity that is currently being traced as the active resumed activity.
643 *
644 * @see #updateResumedAppTrace
645 */
646 private @Nullable ActivityRecord mTracedResumedActivity;
647
648 /** If non-null, we are tracking the time the user spends in the currently focused app. */
649 AppTimeTracker mCurAppTimeTracker;
650
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700651 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700652
Wale Ogunwale53783742018-09-16 10:21:51 -0700653 /**
654 * Packages that the user has asked to have run in screen size
655 * compatibility mode instead of filling the screen.
656 */
657 CompatModePackages mCompatModePackages;
658
Wale Ogunwalef6733932018-06-27 05:14:34 -0700659 private FontScaleSettingObserver mFontScaleSettingObserver;
660
Robert Carr8a2f9132019-11-11 15:03:15 -0800661 /**
662 * Stores the registration and state of TaskOrganizers in use.
663 */
Evan Rosky0037e5f2019-11-05 10:26:24 -0800664 TaskOrganizerController mTaskOrganizerController = new TaskOrganizerController(this);
Robert Carr8a2f9132019-11-11 15:03:15 -0800665
Ricky Wai96f5c352019-04-10 18:40:17 +0100666 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000667
Wale Ogunwalef6733932018-06-27 05:14:34 -0700668 private final class FontScaleSettingObserver extends ContentObserver {
669 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
670 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
671
672 public FontScaleSettingObserver() {
673 super(mH);
674 final ContentResolver resolver = mContext.getContentResolver();
675 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
676 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
677 UserHandle.USER_ALL);
678 }
679
680 @Override
681 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
682 if (mFontScaleUri.equals(uri)) {
683 updateFontScaleIfNeeded(userId);
684 } else if (mHideErrorDialogsUri.equals(uri)) {
685 synchronized (mGlobalLock) {
686 updateShouldShowDialogsLocked(getGlobalConfiguration());
687 }
688 }
689 }
690 }
691
Riddle Hsua0536432019-02-16 00:38:59 +0800692 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
693 @Target(ElementType.METHOD)
694 @Retention(RetentionPolicy.SOURCE)
695 @interface HotPath {
696 int NONE = 0;
697 int OOM_ADJUSTMENT = 1;
698 int LRU_UPDATE = 2;
699 int PROCESS_CHANGE = 3;
700 int caller() default NONE;
701 }
702
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800703 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
704 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900705 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800706 mAmInternal.updateOomAdj();
707 }
708 };
709
Charles Chen8d98dd22018-12-26 17:36:54 +0800710 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
711 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700712 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700713 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700714 mSystemThread = ActivityThread.currentActivityThread();
715 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700716 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800717 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700718 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700719 }
720
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700721 public void onSystemReady() {
722 synchronized (mGlobalLock) {
723 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
724 PackageManager.FEATURE_CANT_SAVE_STATE);
725 mAssistUtils = new AssistUtils(mContext);
726 mVrController.onSystemReady();
727 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700728 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700729 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700730 }
731
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700732 public void onInitPowerManagement() {
733 synchronized (mGlobalLock) {
734 mStackSupervisor.initPowerManagement();
735 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
736 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
737 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
738 mVoiceWakeLock.setReferenceCounted(false);
739 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700740 }
741
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700742 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700743 mFontScaleSettingObserver = new FontScaleSettingObserver();
744 }
745
Wale Ogunwale59507092018-10-29 09:00:30 -0700746 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700747 final boolean freeformWindowManagement =
748 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
749 || Settings.Global.getInt(
750 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
751
752 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
753 final boolean supportsPictureInPicture = supportsMultiWindow &&
754 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
755 final boolean supportsSplitScreenMultiWindow =
756 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
757 final boolean supportsMultiDisplay = mContext.getPackageManager()
758 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700759 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
760 final boolean forceResizable = Settings.Global.getInt(
761 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700762 final boolean sizeCompatFreeform = Settings.Global.getInt(
763 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700764
765 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900766 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700767
768 final Configuration configuration = new Configuration();
769 Settings.System.getConfiguration(resolver, configuration);
770 if (forceRtl) {
771 // This will take care of setting the correct layout direction flags
772 configuration.setLayoutDirection(configuration.locale);
773 }
774
775 synchronized (mGlobalLock) {
776 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700777 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700778 final boolean multiWindowFormEnabled = freeformWindowManagement
779 || supportsSplitScreenMultiWindow
780 || supportsPictureInPicture
781 || supportsMultiDisplay;
782 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
783 mSupportsMultiWindow = true;
784 mSupportsFreeformWindowManagement = freeformWindowManagement;
785 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
786 mSupportsPictureInPicture = supportsPictureInPicture;
787 mSupportsMultiDisplay = supportsMultiDisplay;
788 } else {
789 mSupportsMultiWindow = false;
790 mSupportsFreeformWindowManagement = false;
791 mSupportsSplitScreenMultiWindow = false;
792 mSupportsPictureInPicture = false;
793 mSupportsMultiDisplay = false;
794 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700795 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700796 // This happens before any activities are started, so we can change global configuration
797 // in-place.
798 updateConfigurationLocked(configuration, null, true);
799 final Configuration globalConfig = getGlobalConfiguration();
800 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
801
802 // Load resources only after the current configuration has been set.
803 final Resources res = mContext.getResources();
804 mThumbnailWidth = res.getDimensionPixelSize(
805 com.android.internal.R.dimen.thumbnail_width);
806 mThumbnailHeight = res.getDimensionPixelSize(
807 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700808 }
809 }
810
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800811 public WindowManagerGlobalLock getGlobalLock() {
812 return mGlobalLock;
813 }
814
Yunfan Chen585f2932019-01-29 16:04:45 +0900815 /** For test purpose only. */
816 @VisibleForTesting
817 public ActivityTaskManagerInternal getAtmInternal() {
818 return mInternal;
819 }
820
Riddle Hsud93a6c42018-11-29 21:50:06 +0800821 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
822 Looper looper) {
823 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700824 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700825 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700826 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800827 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700828 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700829 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700830 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700831
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700832 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700833 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700834 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700835 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700836 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700837 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700838 mKeyguardController = mStackSupervisor.getKeyguardController();
839 }
840
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700841 public void onActivityManagerInternalAdded() {
842 synchronized (mGlobalLock) {
843 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
844 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
845 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700846 }
847
Yunfan Chen75157d72018-07-27 14:47:21 +0900848 int increaseConfigurationSeqLocked() {
849 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
850 return mConfigurationSeq;
851 }
852
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700853 protected ActivityStackSupervisor createStackSupervisor() {
854 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
855 supervisor.initialize();
856 return supervisor;
857 }
858
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800859 protected AppWarnings createAppWarnings(
860 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
861 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
862 }
863
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700864 public void setWindowManager(WindowManagerService wm) {
865 synchronized (mGlobalLock) {
866 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800867 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800868 mTempConfig.setToDefaults();
869 mTempConfig.setLocales(LocaleList.getDefault());
870 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800871 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700872 mLockTaskController.setWindowManager(wm);
873 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800874 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700875 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700876 }
877
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700878 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
879 synchronized (mGlobalLock) {
880 mUsageStatsInternal = usageStatsManager;
881 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700882 }
883
Wale Ogunwalef6733932018-06-27 05:14:34 -0700884 UserManagerService getUserManager() {
885 if (mUserManager == null) {
886 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
887 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
888 }
889 return mUserManager;
890 }
891
Philip P. Moltmannee295092020-02-10 08:46:26 -0800892 AppOpsManager getAppOpsManager() {
893 if (mAppOpsManager == null) {
894 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Wale Ogunwalef6733932018-06-27 05:14:34 -0700895 }
Philip P. Moltmannee295092020-02-10 08:46:26 -0800896 return mAppOpsManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700897 }
898
899 boolean hasUserRestriction(String restriction, int userId) {
900 return getUserManager().hasUserRestriction(restriction, userId);
901 }
902
Michal Karpinski15486842019-04-25 17:33:42 +0100903 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
Philip P. Moltmannee295092020-02-10 08:46:26 -0800904 final int mode = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
905 callingUid, callingPackage, /* featureId */ null, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100906 if (mode == AppOpsManager.MODE_DEFAULT) {
907 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
908 == PERMISSION_GRANTED;
909 }
910 return mode == AppOpsManager.MODE_ALLOWED;
911 }
912
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700913 @VisibleForTesting
914 protected void setRecentTasks(RecentTasks recentTasks) {
915 mRecentTasks = recentTasks;
916 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700917 }
918
919 RecentTasks getRecentTasks() {
920 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700921 }
922
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700923 ClientLifecycleManager getLifecycleManager() {
924 return mLifecycleManager;
925 }
926
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700927 ActivityStartController getActivityStartController() {
928 return mActivityStartController;
929 }
930
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700931 TaskChangeNotificationController getTaskChangeNotificationController() {
932 return mTaskChangeNotificationController;
933 }
934
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700935 LockTaskController getLockTaskController() {
936 return mLockTaskController;
937 }
938
Yunfan Chen75157d72018-07-27 14:47:21 +0900939 /**
940 * Return the global configuration used by the process corresponding to the input pid. This is
941 * usually the global configuration with some overrides specific to that process.
942 */
943 Configuration getGlobalConfigurationForCallingPid() {
944 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800945 return getGlobalConfigurationForPid(pid);
946 }
947
948 /**
949 * Return the global configuration used by the process corresponding to the given pid.
950 */
951 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900952 if (pid == MY_PID || pid < 0) {
953 return getGlobalConfiguration();
954 }
955 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100956 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900957 return app != null ? app.getConfiguration() : getGlobalConfiguration();
958 }
959 }
960
961 /**
962 * Return the device configuration info used by the process corresponding to the input pid.
963 * The value is consistent with the global configuration for the process.
964 */
965 @Override
966 public ConfigurationInfo getDeviceConfigurationInfo() {
967 ConfigurationInfo config = new ConfigurationInfo();
968 synchronized (mGlobalLock) {
969 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
970 config.reqTouchScreen = globalConfig.touchscreen;
971 config.reqKeyboardType = globalConfig.keyboard;
972 config.reqNavigation = globalConfig.navigation;
973 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
974 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
975 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
976 }
977 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
978 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
979 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
980 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700981 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900982 }
983 return config;
984 }
985
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700986 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700987 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700988 }
989
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700990 public static final class Lifecycle extends SystemService {
991 private final ActivityTaskManagerService mService;
992
993 public Lifecycle(Context context) {
994 super(context);
995 mService = new ActivityTaskManagerService(context);
996 }
997
998 @Override
999 public void onStart() {
1000 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001001 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001002 }
1003
Garfield Tan891146c2018-10-09 12:14:00 -07001004 @Override
1005 public void onUnlockUser(int userId) {
1006 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001007 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001008 }
1009 }
1010
1011 @Override
1012 public void onCleanupUser(int userId) {
1013 synchronized (mService.getGlobalLock()) {
1014 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1015 }
1016 }
1017
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001018 public ActivityTaskManagerService getService() {
1019 return mService;
1020 }
1021 }
1022
1023 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001024 public final int startActivity(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001025 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1026 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1027 Bundle bOptions) {
1028 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1029 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001030 UserHandle.getCallingUserId());
1031 }
1032
1033 @Override
1034 public final int startActivities(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001035 String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
1036 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001037 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001039 enforceNotIsolatedCaller(reason);
1040 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001041 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001042 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001043 callingFeatureId, intents, resolvedTypes, resultTo,
1044 SafeActivityOptions.fromBundle(bOptions), userId, reason,
1045 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001046 }
1047
1048 @Override
1049 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001050 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1051 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1052 Bundle bOptions, int userId) {
1053 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1054 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001055 true /*validateIncomingUser*/);
1056 }
1057
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001058 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001059 @Nullable String callingFeatureId, Intent intent, String resolvedType,
1060 IBinder resultTo, String resultWho, int requestCode, int startFlags,
1061 ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001062 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001063 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001064
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001065 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1067
1068 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001069 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001070 .setCaller(caller)
1071 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001072 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001073 .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)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001218 .setCallingFeatureId(r.launchedFromFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001219 .setRealCallingPid(-1)
1220 .setRealCallingUid(r.launchedFromUid)
1221 .setActivityOptions(options)
1222 .execute();
1223 Binder.restoreCallingIdentity(origId);
1224
1225 r.finishing = wasFinishing;
1226 if (res != ActivityManager.START_SUCCESS) {
1227 return false;
1228 }
1229 return true;
1230 }
1231 }
1232
1233 @Override
1234 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001235 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1236 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1237 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001238 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001239 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001240 enforceNotIsolatedCaller("startActivityAndWait");
1241 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1242 userId, "startActivityAndWait");
1243 // TODO: Switch to user app stacks here.
1244 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1245 .setCaller(caller)
1246 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001247 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001248 .setResolvedType(resolvedType)
1249 .setResultTo(resultTo)
1250 .setResultWho(resultWho)
1251 .setRequestCode(requestCode)
1252 .setStartFlags(startFlags)
1253 .setActivityOptions(bOptions)
1254 .setUserId(userId)
1255 .setProfilerInfo(profilerInfo)
1256 .setWaitResult(res)
1257 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001258 return res;
1259 }
1260
1261 @Override
1262 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001263 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1264 String resultWho, int requestCode, int startFlags, Configuration config,
1265 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001266 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001267 enforceNotIsolatedCaller("startActivityWithConfig");
1268 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1269 "startActivityWithConfig");
1270 // TODO: Switch to user app stacks here.
1271 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1272 .setCaller(caller)
1273 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001274 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001275 .setResolvedType(resolvedType)
1276 .setResultTo(resultTo)
1277 .setResultWho(resultWho)
1278 .setRequestCode(requestCode)
1279 .setStartFlags(startFlags)
1280 .setGlobalConfiguration(config)
1281 .setActivityOptions(bOptions)
1282 .setUserId(userId)
1283 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001284 }
1285
Robert Carr8a2f9132019-11-11 15:03:15 -08001286 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001287 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1288 int callingUid = Binder.getCallingUid();
1289 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1290 throw new SecurityException("Only the system process can request a permission token, "
1291 + "received request from uid: " + callingUid);
1292 }
1293 IBinder permissionToken = new Binder();
1294 synchronized (mGlobalLock) {
1295 mStartActivitySources.put(permissionToken, delegatorToken);
1296 }
1297
1298 Message expireMsg = PooledLambda.obtainMessage(
1299 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1300 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1301
1302 Message forgetMsg = PooledLambda.obtainMessage(
1303 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1304 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1305
1306 return permissionToken;
1307 }
1308
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001309 @Override
1310 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1311 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001312 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1313 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001314 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001315 // permission grants) as any app that may launch one of your own activities. So we only
1316 // allow this in two cases:
1317 // 1) The caller is an activity that is part of the core framework, and then only when it
1318 // is running as the system.
1319 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1320 // can only be requested by a system activity, which may then delegate this call to
1321 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001322 final ActivityRecord sourceRecord;
1323 final int targetUid;
1324 final String targetPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001325 final String targetFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001326 final boolean isResolver;
1327 synchronized (mGlobalLock) {
1328 if (resultTo == null) {
1329 throw new SecurityException("Must be called from an activity");
1330 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001331 final IBinder sourceToken;
1332 if (permissionToken != null) {
1333 // To even attempt to use a permissionToken, an app must also have this signature
1334 // permission.
1335 mAmInternal.enforceCallingPermission(
1336 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1337 "startActivityAsCaller");
1338 // If called with a permissionToken, we want the sourceRecord from the delegator
1339 // activity that requested this token.
1340 sourceToken = mStartActivitySources.remove(permissionToken);
1341 if (sourceToken == null) {
1342 // Invalid permissionToken, check if it recently expired.
1343 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1344 throw new SecurityException("Called with expired permission token: "
1345 + permissionToken);
1346 } else {
1347 throw new SecurityException("Called with invalid permission token: "
1348 + permissionToken);
1349 }
1350 }
1351 } else {
1352 // This method was called directly by the source.
1353 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001354 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001355
Louis Chang149d5c82019-12-30 09:47:39 +08001356 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001357 if (sourceRecord == null) {
1358 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001359 }
1360 if (sourceRecord.app == null) {
1361 throw new SecurityException("Called without a process attached to activity");
1362 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001363
1364 // Whether called directly or from a delegate, the source activity must be from the
1365 // android package.
1366 if (!sourceRecord.info.packageName.equals("android")) {
1367 throw new SecurityException("Must be called from an activity that is "
1368 + "declared in the android package");
1369 }
1370
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001371 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001372 // This is still okay, as long as this activity is running under the
1373 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001374 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001375 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001376 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377 + " must be system uid or original calling uid "
1378 + sourceRecord.launchedFromUid);
1379 }
1380 }
1381 if (ignoreTargetSecurity) {
1382 if (intent.getComponent() == null) {
1383 throw new SecurityException(
1384 "Component must be specified with ignoreTargetSecurity");
1385 }
1386 if (intent.getSelector() != null) {
1387 throw new SecurityException(
1388 "Selector not allowed with ignoreTargetSecurity");
1389 }
1390 }
1391 targetUid = sourceRecord.launchedFromUid;
1392 targetPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001393 targetFeatureId = sourceRecord.launchedFromFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394 isResolver = sourceRecord.isResolverOrChildActivity();
1395 }
1396
1397 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001398 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001399 }
1400
1401 // TODO: Switch to user app stacks here.
1402 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001403 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001404 .setCallingUid(targetUid)
1405 .setCallingPackage(targetPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001406 .setCallingFeatureId(targetFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001407 .setResolvedType(resolvedType)
1408 .setResultTo(resultTo)
1409 .setResultWho(resultWho)
1410 .setRequestCode(requestCode)
1411 .setStartFlags(startFlags)
1412 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001413 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001414 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1415 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001416 // The target may well be in the background, which would normally prevent it
1417 // from starting an activity. Here we definitely want the start to succeed.
1418 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001419 .execute();
1420 } catch (SecurityException e) {
1421 // XXX need to figure out how to propagate to original app.
1422 // A SecurityException here is generally actually a fault of the original
1423 // calling activity (such as a fairly granting permissions), so propagate it
1424 // back to them.
1425 /*
1426 StringBuilder msg = new StringBuilder();
1427 msg.append("While launching");
1428 msg.append(intent.toString());
1429 msg.append(": ");
1430 msg.append(e.getMessage());
1431 */
1432 throw e;
1433 }
1434 }
1435
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001436 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1437 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001438 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001439 }
1440
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001441 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001442 public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1443 int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001444 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1445 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001446 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001447 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001448 if (session == null || interactor == null) {
1449 throw new NullPointerException("null session or interactor");
1450 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001451 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001453 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001454 .setCallingUid(callingUid)
1455 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001456 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001457 .setResolvedType(resolvedType)
1458 .setVoiceSession(session)
1459 .setVoiceInteractor(interactor)
1460 .setStartFlags(startFlags)
1461 .setProfilerInfo(profilerInfo)
1462 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001463 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001464 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465 .execute();
1466 }
1467
1468 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001469 public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1470 int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1471 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001472 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001473 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1474 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001475
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001476 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001477 .setCallingUid(callingUid)
1478 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001479 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001480 .setResolvedType(resolvedType)
1481 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001482 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001483 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001484 .execute();
1485 }
1486
Riddle Hsu609a8e22019-06-27 16:46:29 -06001487 /**
1488 * Start the recents activity to perform the recents animation.
1489 *
1490 * @param intent The intent to start the recents activity.
1491 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1492 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001493 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001494 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1495 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001496 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001497 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001498 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001499 final long origId = Binder.clearCallingIdentity();
1500 try {
1501 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001502 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
Philip P. Moltmannee295092020-02-10 08:46:26 -08001503 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001504 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001505 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001506
1507 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001508 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001509 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001510 recentsFeatureId, recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001511 if (recentsAnimationRunner == null) {
1512 anim.preloadRecentsActivity();
1513 } else {
1514 anim.startRecentsActivity(recentsAnimationRunner);
1515 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001516 }
1517 } finally {
1518 Binder.restoreCallingIdentity(origId);
1519 }
1520 }
1521
1522 @Override
1523 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001524 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001525 "startActivityFromRecents()");
1526
1527 final int callingPid = Binder.getCallingPid();
1528 final int callingUid = Binder.getCallingUid();
1529 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1530 final long origId = Binder.clearCallingIdentity();
1531 try {
1532 synchronized (mGlobalLock) {
1533 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1534 safeOptions);
1535 }
1536 } finally {
1537 Binder.restoreCallingIdentity(origId);
1538 }
1539 }
1540
1541 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001542 * Public API to check if the client is allowed to start an activity on specified display.
1543 *
1544 * If the target display is private or virtual, some restrictions will apply.
1545 *
1546 * @param displayId Target display id.
1547 * @param intent Intent used to launch the activity.
1548 * @param resolvedType The MIME type of the intent.
1549 * @param userId The id of the user for whom the call is made.
1550 * @return {@code true} if a call to start an activity on the target display should succeed and
1551 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1552 */
1553 @Override
1554 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1555 String resolvedType, int userId) {
1556 final int callingUid = Binder.getCallingUid();
1557 final int callingPid = Binder.getCallingPid();
1558 final long origId = Binder.clearCallingIdentity();
1559
1560 try {
1561 // Collect information about the target of the Intent.
1562 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1563 0 /* startFlags */, null /* profilerInfo */, userId,
1564 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1565 UserHandle.USER_NULL));
1566 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1567
1568 synchronized (mGlobalLock) {
1569 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1570 aInfo);
1571 }
1572 } finally {
1573 Binder.restoreCallingIdentity(origId);
1574 }
1575 }
1576
1577 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001578 * This is the internal entry point for handling Activity.finish().
1579 *
1580 * @param token The Binder token referencing the Activity we want to finish.
1581 * @param resultCode Result code, if any, from this Activity.
1582 * @param resultData Result data (Intent), if any, from this Activity.
1583 * @param finishTask Whether to finish the task associated with this Activity.
1584 *
1585 * @return Returns true if the activity successfully finished, or false if it is still running.
1586 */
1587 @Override
1588 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1589 int finishTask) {
1590 // Refuse possible leaked file descriptors
1591 if (resultData != null && resultData.hasFileDescriptors()) {
1592 throw new IllegalArgumentException("File descriptors passed in Intent");
1593 }
1594
1595 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001596 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 if (r == null) {
1598 return true;
1599 }
1600 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001601 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001602 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001603 if (rootR == null) {
1604 Slog.w(TAG, "Finishing task with all activities already finished");
1605 }
1606 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1607 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001608 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001609 return false;
1610 }
1611
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001612 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1613 // We should consolidate.
1614 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001615 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001616 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001617 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001618 if (next != null) {
1619 // ask watcher if this is allowed
1620 boolean resumeOK = true;
1621 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001622 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001623 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001624 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001625 Watchdog.getInstance().setActivityController(null);
1626 }
1627
1628 if (!resumeOK) {
1629 Slog.i(TAG, "Not finishing activity because controller resumed");
1630 return false;
1631 }
1632 }
1633 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001634
1635 // note down that the process has finished an activity and is in background activity
1636 // starts grace period
1637 if (r.app != null) {
1638 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1639 }
1640
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001641 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001642 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001643 try {
1644 boolean res;
1645 final boolean finishWithRootActivity =
1646 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1647 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1648 || (finishWithRootActivity && r == rootR)) {
1649 // If requested, remove the task that is associated to this activity only if it
1650 // was the root activity in the task. The result code and data is ignored
1651 // because we don't support returning them across task boundaries. Also, to
1652 // keep backwards compatibility we remove the task from recents when finishing
1653 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001654 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001655 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001656 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001657 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001658 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001659 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001660 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001661 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001662 if (!res) {
1663 Slog.i(TAG, "Failed to finish by app-request");
1664 }
1665 }
1666 return res;
1667 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001668 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001669 Binder.restoreCallingIdentity(origId);
1670 }
1671 }
1672 }
1673
1674 @Override
1675 public boolean finishActivityAffinity(IBinder token) {
1676 synchronized (mGlobalLock) {
1677 final long origId = Binder.clearCallingIdentity();
1678 try {
1679 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1680 if (r == null) {
1681 return false;
1682 }
1683
1684 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1685 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001686 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001687 return false;
1688 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001689
1690 final PooledFunction p = PooledLambda.obtainFunction(
1691 ActivityRecord::finishIfSameAffinity, r,
1692 PooledLambda.__(ActivityRecord.class));
1693 r.getTask().forAllActivities(
1694 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1695 p.recycle();
1696
Andrii Kuliande93eff2019-07-12 12:21:27 -07001697 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001698 } finally {
1699 Binder.restoreCallingIdentity(origId);
1700 }
1701 }
1702 }
1703
1704 @Override
1705 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1706 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001707 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001708 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001709 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001710 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1711 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001712 return;
1713 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001714 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1715 false /* processPausingActivities */, config);
1716 if (stopProfiling && r.hasProcess()) {
1717 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001718 }
1719 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001720 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001721 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001722 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001723 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001724 }
1725
1726 @Override
1727 public final void activityResumed(IBinder token) {
1728 final long origId = Binder.clearCallingIdentity();
1729 synchronized (mGlobalLock) {
1730 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001731 }
1732 Binder.restoreCallingIdentity(origId);
1733 }
1734
1735 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001736 public final void activityTopResumedStateLost() {
1737 final long origId = Binder.clearCallingIdentity();
1738 synchronized (mGlobalLock) {
1739 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1740 }
1741 Binder.restoreCallingIdentity(origId);
1742 }
1743
1744 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001745 public final void activityPaused(IBinder token) {
1746 final long origId = Binder.clearCallingIdentity();
1747 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001748 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001749 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1750 if (r != null) {
1751 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001752 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001753 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001754 }
1755 Binder.restoreCallingIdentity(origId);
1756 }
1757
1758 @Override
1759 public final void activityStopped(IBinder token, Bundle icicle,
1760 PersistableBundle persistentState, CharSequence description) {
1761 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1762
1763 // Refuse possible leaked file descriptors
1764 if (icicle != null && icicle.hasFileDescriptors()) {
1765 throw new IllegalArgumentException("File descriptors passed in Bundle");
1766 }
1767
1768 final long origId = Binder.clearCallingIdentity();
1769
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001770 String restartingName = null;
1771 int restartingUid = 0;
1772 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001773 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001774 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001775 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001776 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001777 if (r.attachedToProcess()
1778 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1779 // The activity was requested to restart from
1780 // {@link #restartActivityProcessIfVisible}.
1781 restartingName = r.app.mName;
1782 restartingUid = r.app.mUid;
1783 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001784 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001785 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001786 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001787 }
1788
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001789 if (restartingName != null) {
1790 // In order to let the foreground activity can be restarted with its saved state from
1791 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1792 // until the activity reports stopped with the state. And the activity record will be
1793 // kept because the record state is restarting, then the activity will be restarted
1794 // immediately if it is still the top one.
1795 mStackSupervisor.removeRestartTimeouts(r);
1796 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1797 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001798 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001799
1800 Binder.restoreCallingIdentity(origId);
1801 }
1802
1803 @Override
1804 public final void activityDestroyed(IBinder token) {
1805 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1806 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001807 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001808 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001809 try {
1810 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1811 if (activity != null) {
1812 activity.destroyed("activityDestroyed");
1813 }
1814 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001815 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001816 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001817 }
1818 }
1819 }
1820
1821 @Override
1822 public final void activityRelaunched(IBinder token) {
1823 final long origId = Binder.clearCallingIdentity();
1824 synchronized (mGlobalLock) {
1825 mStackSupervisor.activityRelaunchedLocked(token);
1826 }
1827 Binder.restoreCallingIdentity(origId);
1828 }
1829
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001830 @Override
1831 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1832 synchronized (mGlobalLock) {
1833 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1834 if (r == null) {
1835 return;
1836 }
1837 final long origId = Binder.clearCallingIdentity();
1838 try {
1839 r.setRequestedOrientation(requestedOrientation);
1840 } finally {
1841 Binder.restoreCallingIdentity(origId);
1842 }
1843 }
1844 }
1845
1846 @Override
1847 public int getRequestedOrientation(IBinder token) {
1848 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001849 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1850 return (r != null)
1851 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001852 }
1853 }
1854
1855 @Override
1856 public void setImmersive(IBinder token, boolean immersive) {
1857 synchronized (mGlobalLock) {
1858 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1859 if (r == null) {
1860 throw new IllegalArgumentException();
1861 }
1862 r.immersive = immersive;
1863
1864 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001865 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001866 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001867 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001868 }
1869 }
1870 }
1871
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001872 void applyUpdateLockStateLocked(ActivityRecord r) {
1873 // Modifications to the UpdateLock state are done on our handler, outside
1874 // the activity manager's locks. The new state is determined based on the
1875 // state *now* of the relevant activity record. The object is passed to
1876 // the handler solely for logging detail, not to be consulted/modified.
1877 final boolean nextState = r != null && r.immersive;
1878 mH.post(() -> {
1879 if (mUpdateLock.isHeld() != nextState) {
1880 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1881 "Applying new update lock state '" + nextState + "' for " + r);
1882 if (nextState) {
1883 mUpdateLock.acquire();
1884 } else {
1885 mUpdateLock.release();
1886 }
1887 }
1888 });
1889 }
1890
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001891 @Override
1892 public boolean isImmersive(IBinder token) {
1893 synchronized (mGlobalLock) {
1894 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1895 if (r == null) {
1896 throw new IllegalArgumentException();
1897 }
1898 return r.immersive;
1899 }
1900 }
1901
1902 @Override
1903 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001904 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001905 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001906 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001907 return (r != null) ? r.immersive : false;
1908 }
1909 }
1910
1911 @Override
1912 public void overridePendingTransition(IBinder token, String packageName,
1913 int enterAnim, int exitAnim) {
1914 synchronized (mGlobalLock) {
1915 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1916 if (self == null) {
1917 return;
1918 }
1919
1920 final long origId = Binder.clearCallingIdentity();
1921
1922 if (self.isState(
1923 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001924 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001925 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001926 }
1927
1928 Binder.restoreCallingIdentity(origId);
1929 }
1930 }
1931
1932 @Override
1933 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001934 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001936 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001937 if (r == null) {
1938 return ActivityManager.COMPAT_MODE_UNKNOWN;
1939 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001940 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001941 }
1942 }
1943
1944 @Override
1945 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001946 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001947 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001948 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001949 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001950 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001951 if (r == null) {
1952 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1953 return;
1954 }
1955 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001956 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001957 }
1958 }
1959
1960 @Override
1961 public int getLaunchedFromUid(IBinder activityToken) {
1962 ActivityRecord srec;
1963 synchronized (mGlobalLock) {
1964 srec = ActivityRecord.forTokenLocked(activityToken);
1965 }
1966 if (srec == null) {
1967 return -1;
1968 }
1969 return srec.launchedFromUid;
1970 }
1971
1972 @Override
1973 public String getLaunchedFromPackage(IBinder activityToken) {
1974 ActivityRecord srec;
1975 synchronized (mGlobalLock) {
1976 srec = ActivityRecord.forTokenLocked(activityToken);
1977 }
1978 if (srec == null) {
1979 return null;
1980 }
1981 return srec.launchedFromPackage;
1982 }
1983
1984 @Override
1985 public boolean convertFromTranslucent(IBinder token) {
1986 final long origId = Binder.clearCallingIdentity();
1987 try {
1988 synchronized (mGlobalLock) {
1989 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1990 if (r == null) {
1991 return false;
1992 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001993 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001994 }
1995 } finally {
1996 Binder.restoreCallingIdentity(origId);
1997 }
1998 }
1999
2000 @Override
2001 public boolean convertToTranslucent(IBinder token, Bundle options) {
2002 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2003 final long origId = Binder.clearCallingIdentity();
2004 try {
2005 synchronized (mGlobalLock) {
2006 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2007 if (r == null) {
2008 return false;
2009 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002010 final ActivityRecord under = r.getTask().getActivityBelow(r);
2011 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002012 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2013 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002014 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002015 }
2016 } finally {
2017 Binder.restoreCallingIdentity(origId);
2018 }
2019 }
2020
2021 @Override
2022 public void notifyActivityDrawn(IBinder token) {
2023 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2024 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002025 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002026 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002027 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002028 }
2029 }
2030 }
2031
2032 @Override
2033 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2034 synchronized (mGlobalLock) {
2035 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2036 if (r == null) {
2037 return;
2038 }
2039 r.reportFullyDrawnLocked(restoredFromBundle);
2040 }
2041 }
2042
2043 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002044 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002045 synchronized (mGlobalLock) {
2046 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002047 if (stack != null) {
2048 final int displayId = stack.getDisplayId();
2049 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002050 }
2051 return DEFAULT_DISPLAY;
2052 }
2053 }
2054
2055 @Override
2056 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002057 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002058 long ident = Binder.clearCallingIdentity();
2059 try {
2060 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002061 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002062 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002063 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002064 }
2065 return null;
2066 }
2067 } finally {
2068 Binder.restoreCallingIdentity(ident);
2069 }
2070 }
2071
2072 @Override
2073 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002074 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002075 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2076 final long callingId = Binder.clearCallingIdentity();
2077 try {
2078 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002079 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002080 if (stack == null) {
2081 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2082 return;
2083 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002084 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002085 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002086 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002087 }
2088 }
2089 } finally {
2090 Binder.restoreCallingIdentity(callingId);
2091 }
2092 }
2093
2094 @Override
2095 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002096 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002097 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2098 final long callingId = Binder.clearCallingIdentity();
2099 try {
2100 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002101 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002102 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002103 if (task == null) {
2104 return;
2105 }
2106 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002107 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002108 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002109 }
2110 }
2111 } finally {
2112 Binder.restoreCallingIdentity(callingId);
2113 }
2114 }
2115
2116 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002117 public void restartActivityProcessIfVisible(IBinder activityToken) {
2118 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2119 final long callingId = Binder.clearCallingIdentity();
2120 try {
2121 synchronized (mGlobalLock) {
2122 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2123 if (r == null) {
2124 return;
2125 }
2126 r.restartProcessIfVisible();
2127 }
2128 } finally {
2129 Binder.restoreCallingIdentity(callingId);
2130 }
2131 }
2132
2133 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002134 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002135 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002136 synchronized (mGlobalLock) {
2137 final long ident = Binder.clearCallingIdentity();
2138 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002139 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002140 "remove-task");
2141 } finally {
2142 Binder.restoreCallingIdentity(ident);
2143 }
2144 }
2145 }
2146
2147 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002148 public void removeAllVisibleRecentTasks() {
2149 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2150 synchronized (mGlobalLock) {
2151 final long ident = Binder.clearCallingIdentity();
2152 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002153 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002154 } finally {
2155 Binder.restoreCallingIdentity(ident);
2156 }
2157 }
2158 }
2159
2160 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002161 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2162 synchronized (mGlobalLock) {
2163 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2164 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002165 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002166 }
2167 }
2168 return false;
2169 }
2170
2171 @Override
2172 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2173 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002174
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002175 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002176 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2177 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002178 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002179 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002180 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002181 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002182 }
2183 }
2184
2185 /**
2186 * Attempts to move a task backwards in z-order (the order of activities within the task is
2187 * unchanged).
2188 *
2189 * There are several possible results of this call:
2190 * - if the task is locked, then we will show the lock toast
2191 * - if there is a task behind the provided task, then that task is made visible and resumed as
2192 * this task is moved to the back
2193 * - otherwise, if there are no other tasks in the stack:
2194 * - if this task is in the pinned stack, then we remove the stack completely, which will
2195 * have the effect of moving the task to the top or bottom of the fullscreen stack
2196 * (depending on whether it is visible)
2197 * - otherwise, we simply return home and hide this task
2198 *
2199 * @param token A reference to the activity we wish to move
2200 * @param nonRoot If false then this only works if the activity is the root
2201 * of a task; if true it will work for any activity in a task.
2202 * @return Returns true if the move completed, false if not.
2203 */
2204 @Override
2205 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002206 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002207 synchronized (mGlobalLock) {
2208 final long origId = Binder.clearCallingIdentity();
2209 try {
2210 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002211 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002212 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002213 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002214 }
2215 } finally {
2216 Binder.restoreCallingIdentity(origId);
2217 }
2218 }
2219 return false;
2220 }
2221
2222 @Override
2223 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002224 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002225 long ident = Binder.clearCallingIdentity();
2226 Rect rect = new Rect();
2227 try {
2228 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002229 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002230 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2231 if (task == null) {
2232 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2233 return rect;
2234 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002235 if (task.getParent() != null) {
2236 rect.set(task.getBounds());
2237 } else if (task.mLastNonFullscreenBounds != null) {
2238 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002239 }
2240 }
2241 } finally {
2242 Binder.restoreCallingIdentity(ident);
2243 }
2244 return rect;
2245 }
2246
2247 @Override
2248 public ActivityManager.TaskDescription getTaskDescription(int id) {
2249 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002250 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002251 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002252 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002253 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2254 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002255 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002256 }
2257 }
2258 return null;
2259 }
2260
2261 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002262 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002263 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Winson Chung7ccc6812020-01-23 16:15:10 -08002264 return setTaskWindowingModeSplitScreenPrimary(taskId,
2265 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002266 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002267 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002268 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002269 synchronized (mGlobalLock) {
2270 final long ident = Binder.clearCallingIdentity();
2271 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002272 if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2273 return setTaskWindowingModeSplitScreen(taskId, windowingMode, toTop);
2274 }
Louis Chang149d5c82019-12-30 09:47:39 +08002275 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002276 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002277 if (task == null) {
2278 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002279 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002280 }
2281
2282 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2283 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2284
2285 if (!task.isActivityTypeStandardOrUndefined()) {
2286 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2287 + " non-standard task " + taskId + " to windowing mode="
2288 + windowingMode);
2289 }
2290
2291 final ActivityStack stack = task.getStack();
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002292 // Convert some windowing-mode changes into root-task reparents for split-screen.
2293 if (stack.getTile() != null) {
2294 stack.getDisplay().onSplitScreenModeDismissed();
2295 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002296 if (toTop) {
2297 stack.moveToFront("setTaskWindowingMode", task);
2298 }
2299 stack.setWindowingMode(windowingMode);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002300 stack.getDisplay().ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2301 true /* notifyClients */);
Winson Chung7ccc6812020-01-23 16:15:10 -08002302 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002303 } finally {
2304 Binder.restoreCallingIdentity(ident);
2305 }
2306 }
2307 }
2308
2309 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002310 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002311 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002312 ActivityRecord r = getCallingRecordLocked(token);
2313 return r != null ? r.info.packageName : null;
2314 }
2315 }
2316
2317 @Override
2318 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002319 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002320 ActivityRecord r = getCallingRecordLocked(token);
2321 return r != null ? r.intent.getComponent() : null;
2322 }
2323 }
2324
2325 private ActivityRecord getCallingRecordLocked(IBinder token) {
2326 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2327 if (r == null) {
2328 return null;
2329 }
2330 return r.resultTo;
2331 }
2332
2333 @Override
2334 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002335 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002336
2337 synchronized (mGlobalLock) {
2338 final long origId = Binder.clearCallingIdentity();
2339 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002340 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002341 } finally {
2342 Binder.restoreCallingIdentity(origId);
2343 }
2344 }
2345 }
2346
Mark Renouf446251d2019-04-26 10:22:41 -04002347 @Override
2348 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2349 synchronized (mGlobalLock) {
2350 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2351 if (r == null) {
2352 return;
2353 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002354 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002355 if (stack != null && stack.isSingleTaskInstance()) {
2356 // Single-task stacks are used for activities which are presented in floating
2357 // windows above full screen activities. Instead of directly finishing the
2358 // task, a task change listener is used to notify SystemUI so the action can be
2359 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002360 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002361 mTaskChangeNotificationController
2362 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2363 } else {
2364 try {
2365 callback.requestFinish();
2366 } catch (RemoteException e) {
2367 Slog.e(TAG, "Failed to invoke request finish callback", e);
2368 }
2369 }
2370 }
2371 }
2372
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002373 /**
2374 * TODO: Add mController hook
2375 */
2376 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002377 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2378 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002379 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002380
2381 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2382 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002383 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2384 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002385 }
2386 }
2387
Ricky Waiaca8a772019-04-04 16:01:06 +01002388 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2389 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002390 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002391 final int callingPid = Binder.getCallingPid();
2392 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002393 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002394 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002395 SafeActivityOptions.abort(options);
2396 return;
2397 }
2398 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002399 WindowProcessController callerApp = null;
2400 if (appThread != null) {
2401 callerApp = getProcessController(appThread);
2402 }
2403 final ActivityStarter starter = getActivityStartController().obtainStarter(
2404 null /* intent */, "moveTaskToFront");
2405 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2406 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002407 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002408 return;
2409 }
2410 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002411 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002412 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002413 if (task == null) {
2414 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002415 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002416 return;
2417 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002418 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002419 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002420 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002421 return;
2422 }
2423 ActivityOptions realOptions = options != null
2424 ? options.getOptions(mStackSupervisor)
2425 : null;
2426 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2427 false /* forceNonResizable */);
2428
Wale Ogunwale21e06482019-11-18 05:14:15 -08002429 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002430 if (topActivity != null) {
2431
2432 // We are reshowing a task, use a starting window to hide the initial draw delay
2433 // so the transition can start earlier.
2434 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2435 true /* taskSwitch */, fromRecents);
2436 }
2437 } finally {
2438 Binder.restoreCallingIdentity(origId);
2439 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002440 }
2441
Ricky Waiaca8a772019-04-04 16:01:06 +01002442 /**
2443 * Return true if callingUid is system, or packageName belongs to that callingUid.
2444 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002445 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002446 try {
2447 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2448 if (packageName == null) {
2449 return false;
2450 }
2451 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2452 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2453 UserHandle.getUserId(callingUid));
2454 return UserHandle.isSameApp(callingUid, uid);
2455 }
2456 } catch (RemoteException e) {
2457 // Should not happen
2458 }
2459 return true;
2460 }
2461
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002462 /**
2463 * Checks that the provided package name matches the current calling UID, throws a security
2464 * exception if it doesn't.
2465 */
2466 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2467 final int callingUid = Binder.getCallingUid();
2468 if (isSameApp(callingUid, packageName)) {
2469 return;
2470 }
2471 final String msg = "Permission Denial: package=" + packageName
2472 + " does not belong to uid=" + callingUid;
2473 Slog.w(TAG, msg);
2474 throw new SecurityException(msg);
2475 }
2476
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002477 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2478 int callingPid, int callingUid, String name) {
2479 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2480 return true;
2481 }
2482
2483 if (getRecentTasks().isCallerRecents(sourceUid)) {
2484 return true;
2485 }
2486
2487 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2488 if (perm == PackageManager.PERMISSION_GRANTED) {
2489 return true;
2490 }
2491 if (checkAllowAppSwitchUid(sourceUid)) {
2492 return true;
2493 }
2494
2495 // If the actual IPC caller is different from the logical source, then
2496 // also see if they are allowed to control app switches.
2497 if (callingUid != -1 && callingUid != sourceUid) {
2498 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2499 if (perm == PackageManager.PERMISSION_GRANTED) {
2500 return true;
2501 }
2502 if (checkAllowAppSwitchUid(callingUid)) {
2503 return true;
2504 }
2505 }
2506
2507 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2508 return false;
2509 }
2510
2511 private boolean checkAllowAppSwitchUid(int uid) {
2512 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2513 if (types != null) {
2514 for (int i = types.size() - 1; i >= 0; i--) {
2515 if (types.valueAt(i).intValue() == uid) {
2516 return true;
2517 }
2518 }
2519 }
2520 return false;
2521 }
2522
2523 @Override
2524 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2525 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2526 "setActivityController()");
2527 synchronized (mGlobalLock) {
2528 mController = controller;
2529 mControllerIsAMonkey = imAMonkey;
2530 Watchdog.getInstance().setActivityController(controller);
2531 }
2532 }
2533
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002534 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002535 synchronized (mGlobalLock) {
2536 return mController != null && mControllerIsAMonkey;
2537 }
2538 }
2539
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002540 @Override
2541 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2542 synchronized (mGlobalLock) {
2543 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2544 }
2545 }
2546
2547 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002548 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2549 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2550 }
2551
2552 @Override
2553 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2554 @WindowConfiguration.ActivityType int ignoreActivityType,
2555 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2556 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002557 final int callingPid = Binder.getCallingPid();
2558 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002559 final int[] profileIds = getUserManager().getProfileIds(
2560 UserHandle.getUserId(callingUid), true);
2561 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2562 for (int i = 0; i < profileIds.length; i++) {
2563 callingProfileIds.add(profileIds[i]);
2564 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002565 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2566
2567 synchronized (mGlobalLock) {
2568 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2569
Nicholas Sauer0259e532019-08-30 08:24:55 -07002570 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002571 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002572 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002573 }
2574
2575 return list;
2576 }
2577
2578 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002579 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2580 synchronized (mGlobalLock) {
2581 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002582 try {
2583 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2584 if (r == null) return;
2585
2586 final PooledConsumer c = PooledLambda.obtainConsumer(
2587 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2588 r, resultWho, requestCode);
2589 // TODO: This should probably only loop over the task since you need to be in the
2590 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002591 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002592 c.recycle();
2593
2594 updateOomAdj();
2595 } finally {
2596 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002597 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002598 }
2599 }
2600
2601 @Override
2602 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002603 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002604 ActivityStack stack = ActivityRecord.getStackLocked(token);
2605 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002606 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002607 }
2608 return false;
2609 }
2610 }
2611
2612 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002613 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002614 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002615 synchronized (mGlobalLock) {
2616 final long ident = Binder.clearCallingIdentity();
2617 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002618 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002619 if (task == null) {
2620 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2621 return;
2622 }
2623
2624 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2625 + " to stackId=" + stackId + " toTop=" + toTop);
2626
Louis Chang149d5c82019-12-30 09:47:39 +08002627 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002628 if (stack == null) {
2629 throw new IllegalStateException(
2630 "moveTaskToStack: No stack for stackId=" + stackId);
2631 }
2632 if (!stack.isActivityTypeStandardOrUndefined()) {
2633 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2634 + taskId + " to stack " + stackId);
2635 }
2636 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002637 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002638 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2639 }
2640 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2641 "moveTaskToStack");
2642 } finally {
2643 Binder.restoreCallingIdentity(ident);
2644 }
2645 }
2646 }
2647
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002648 /**
2649 * Moves the specified task to the primary-split-screen stack.
2650 *
2651 * @param taskId Id of task to move.
2652 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2653 * exist already. See
2654 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2655 * and
2656 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2657 * @param toTop If the task and stack should be moved to the top.
2658 * @param animate Whether we should play an animation for the moving the task.
2659 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2660 * stack. Pass {@code null} to use default bounds.
2661 * @param showRecents If the recents activity should be shown on the other side of the task
2662 * going into split-screen mode.
Winson Chung7ccc6812020-01-23 16:15:10 -08002663 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002664 */
2665 @Override
2666 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2667 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002668 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002669 "setTaskWindowingModeSplitScreenPrimary()");
2670 synchronized (mGlobalLock) {
2671 final long ident = Binder.clearCallingIdentity();
2672 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002673 return setTaskWindowingModeSplitScreen(taskId, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY,
2674 toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002675 } finally {
2676 Binder.restoreCallingIdentity(ident);
2677 }
2678 }
2679 }
2680
2681 /**
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002682 * Moves the specified task into a split-screen tile.
2683 */
2684 private boolean setTaskWindowingModeSplitScreen(int taskId, int windowingMode, boolean toTop) {
2685 if (!WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2686 throw new IllegalArgumentException("Calling setTaskWindowingModeSplitScreen with non"
2687 + "split-screen mode: " + windowingMode);
2688 }
2689 if (isInLockTaskMode()) {
2690 Slog.w(TAG, "setTaskWindowingModeSplitScreen: Is in lock task mode="
2691 + getLockTaskModeState());
2692 return false;
2693 }
2694
2695 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2696 MATCH_TASK_IN_STACKS_ONLY);
2697 if (task == null) {
2698 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2699 return false;
2700 }
2701 if (!task.isActivityTypeStandardOrUndefined()) {
2702 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2703 + " non-standard task " + taskId + " to split-screen windowing mode");
2704 }
Wale Ogunwale0d465192020-01-23 19:14:44 -08002705 if (!task.supportsSplitScreenWindowingMode()) {
2706 return false;
2707 }
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002708
2709 final int prevMode = task.getWindowingMode();
Wale Ogunwale0d465192020-01-23 19:14:44 -08002710 moveTaskToSplitScreenPrimaryTile(task, toTop);
2711 return prevMode != task.getWindowingMode();
2712 }
2713
2714 void moveTaskToSplitScreenPrimaryTile(Task task, boolean toTop) {
2715 ActivityStack stack = task.getStack();
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002716 TaskTile tile = null;
2717 for (int i = stack.getDisplay().getStackCount() - 1; i >= 0; --i) {
2718 tile = stack.getDisplay().getStackAt(i).asTile();
2719 if (tile != null && tile.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2720 break;
2721 }
2722 }
2723 if (tile == null) {
2724 throw new IllegalStateException("Can't enter split without associated tile");
2725 }
2726 WindowContainerTransaction wct = new WindowContainerTransaction();
2727 wct.reparent(stack.mRemoteToken, tile.mRemoteToken, toTop);
2728 mTaskOrganizerController.applyContainerTransaction(wct, null);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002729 }
2730
2731 /**
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002732 * Removes stacks in the input windowing modes from the system if they are of activity type
2733 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2734 */
2735 @Override
2736 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002737 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002738 "removeStacksInWindowingModes()");
2739
2740 synchronized (mGlobalLock) {
2741 final long ident = Binder.clearCallingIdentity();
2742 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002743 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002744 } finally {
2745 Binder.restoreCallingIdentity(ident);
2746 }
2747 }
2748 }
2749
2750 @Override
2751 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002752 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002753 "removeStacksWithActivityTypes()");
2754
2755 synchronized (mGlobalLock) {
2756 final long ident = Binder.clearCallingIdentity();
2757 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002758 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002759 } finally {
2760 Binder.restoreCallingIdentity(ident);
2761 }
2762 }
2763 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002764
2765 @Override
2766 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2767 int userId) {
2768 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002769 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2770 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002771 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002772 final boolean detailed = checkGetTasksPermission(
2773 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2774 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002775 == PackageManager.PERMISSION_GRANTED;
2776
2777 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002778 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779 callingUid);
2780 }
2781 }
2782
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002783 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002784 @Override
2785 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002786 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002787 long ident = Binder.clearCallingIdentity();
2788 try {
2789 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002790 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002791 }
2792 } finally {
2793 Binder.restoreCallingIdentity(ident);
2794 }
2795 }
2796
2797 @Override
2798 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002799 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002800 long ident = Binder.clearCallingIdentity();
2801 try {
2802 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002803 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002804 }
2805 } finally {
2806 Binder.restoreCallingIdentity(ident);
2807 }
2808 }
2809
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002810 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002811 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002812 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2813 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2814 long ident = Binder.clearCallingIdentity();
2815 try {
2816 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002817 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002818 }
2819 } finally {
2820 Binder.restoreCallingIdentity(ident);
2821 }
2822 }
2823
2824 @Override
2825 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2826 int displayId) {
2827 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2828 long ident = Binder.clearCallingIdentity();
2829 try {
2830 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002831 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002832 }
2833 } finally {
2834 Binder.restoreCallingIdentity(ident);
2835 }
2836 }
2837
2838 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002839 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002840 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002841 final long callingUid = Binder.getCallingUid();
2842 final long origId = Binder.clearCallingIdentity();
2843 try {
2844 synchronized (mGlobalLock) {
2845 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002846 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002847 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2848 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2849 }
2850 } finally {
2851 Binder.restoreCallingIdentity(origId);
2852 }
2853 }
2854
2855 @Override
2856 public void startLockTaskModeByToken(IBinder token) {
2857 synchronized (mGlobalLock) {
2858 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2859 if (r == null) {
2860 return;
2861 }
Louis Changcdec0802019-11-11 11:45:07 +08002862 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002863 }
2864 }
2865
2866 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002867 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002868 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002869 // This makes inner call to look as if it was initiated by system.
2870 long ident = Binder.clearCallingIdentity();
2871 try {
2872 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002873 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002874 MATCH_TASK_IN_STACKS_ONLY);
2875 if (task == null) {
2876 return;
2877 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002878
2879 // When starting lock task mode the stack must be in front and focused
2880 task.getStack().moveToFront("startSystemLockTaskMode");
2881 startLockTaskModeLocked(task, true /* isSystemCaller */);
2882 }
2883 } finally {
2884 Binder.restoreCallingIdentity(ident);
2885 }
2886 }
2887
2888 @Override
2889 public void stopLockTaskModeByToken(IBinder token) {
2890 synchronized (mGlobalLock) {
2891 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2892 if (r == null) {
2893 return;
2894 }
Louis Changcdec0802019-11-11 11:45:07 +08002895 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002896 }
2897 }
2898
2899 /**
2900 * This API should be called by SystemUI only when user perform certain action to dismiss
2901 * lock task mode. We should only dismiss pinned lock task mode in this case.
2902 */
2903 @Override
2904 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002905 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002906 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2907 }
2908
Louis Changcdec0802019-11-11 11:45:07 +08002909 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002910 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2911 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2912 return;
2913 }
2914
Louis Chang149d5c82019-12-30 09:47:39 +08002915 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002916 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002917 throw new IllegalArgumentException("Invalid task, not in foreground");
2918 }
2919
2920 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2921 // system or a specific app.
2922 // * System-initiated requests will only start the pinned mode (screen pinning)
2923 // * App-initiated requests
2924 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2925 // - will start the pinned mode, otherwise
2926 final int callingUid = Binder.getCallingUid();
2927 long ident = Binder.clearCallingIdentity();
2928 try {
2929 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002930 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002931
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002932 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002933 } finally {
2934 Binder.restoreCallingIdentity(ident);
2935 }
2936 }
2937
Louis Changcdec0802019-11-11 11:45:07 +08002938 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002939 final int callingUid = Binder.getCallingUid();
2940 long ident = Binder.clearCallingIdentity();
2941 try {
2942 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002943 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002944 }
2945 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2946 // task and jumping straight into a call in the case of emergency call back.
2947 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2948 if (tm != null) {
2949 tm.showInCallScreen(false);
2950 }
2951 } finally {
2952 Binder.restoreCallingIdentity(ident);
2953 }
2954 }
2955
2956 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002957 public void updateLockTaskPackages(int userId, String[] packages) {
2958 final int callingUid = Binder.getCallingUid();
2959 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2960 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2961 "updateLockTaskPackages()");
2962 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002963 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002964 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2965 + Arrays.toString(packages));
2966 getLockTaskController().updateLockTaskPackages(userId, packages);
2967 }
2968 }
2969
2970 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002971 public boolean isInLockTaskMode() {
2972 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2973 }
2974
2975 @Override
2976 public int getLockTaskModeState() {
2977 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002978 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002979 }
2980 }
2981
2982 @Override
2983 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2984 synchronized (mGlobalLock) {
2985 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2986 if (r != null) {
2987 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08002988 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002989 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002990 }
2991 }
2992 }
2993
2994 @Override
2995 public Bundle getActivityOptions(IBinder token) {
2996 final long origId = Binder.clearCallingIdentity();
2997 try {
2998 synchronized (mGlobalLock) {
2999 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3000 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003001 final ActivityOptions activityOptions = r.takeOptionsLocked(
3002 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003003 return activityOptions == null ? null : activityOptions.toBundle();
3004 }
3005 return null;
3006 }
3007 } finally {
3008 Binder.restoreCallingIdentity(origId);
3009 }
3010 }
3011
3012 @Override
3013 public List<IBinder> getAppTasks(String callingPackage) {
3014 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003015 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003016 long ident = Binder.clearCallingIdentity();
3017 try {
3018 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003019 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003020 }
3021 } finally {
3022 Binder.restoreCallingIdentity(ident);
3023 }
3024 }
3025
3026 @Override
3027 public void finishVoiceTask(IVoiceInteractionSession session) {
3028 synchronized (mGlobalLock) {
3029 final long origId = Binder.clearCallingIdentity();
3030 try {
3031 // TODO: VI Consider treating local voice interactions and voice tasks
3032 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003033 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003034 } finally {
3035 Binder.restoreCallingIdentity(origId);
3036 }
3037 }
3038
3039 }
3040
3041 @Override
3042 public boolean isTopOfTask(IBinder token) {
3043 synchronized (mGlobalLock) {
3044 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003045 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003046 }
3047 }
3048
3049 @Override
3050 public void notifyLaunchTaskBehindComplete(IBinder token) {
3051 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3052 }
3053
3054 @Override
3055 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003056 mH.post(() -> {
3057 synchronized (mGlobalLock) {
3058 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003059 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003060 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003061 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003062 } catch (RemoteException e) {
3063 }
3064 }
3065 }
3066
3067 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003068 }
3069
3070 /** Called from an app when assist data is ready. */
3071 @Override
3072 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3073 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003074 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003075 synchronized (pae) {
3076 pae.result = extras;
3077 pae.structure = structure;
3078 pae.content = content;
3079 if (referrer != null) {
3080 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3081 }
3082 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003083 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003084 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003085 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003086 structure.setHomeActivity(pae.isHome);
3087 }
3088 pae.haveResult = true;
3089 pae.notifyAll();
3090 if (pae.intent == null && pae.receiver == null) {
3091 // Caller is just waiting for the result.
3092 return;
3093 }
3094 }
3095 // We are now ready to launch the assist activity.
3096 IAssistDataReceiver sendReceiver = null;
3097 Bundle sendBundle = null;
3098 synchronized (mGlobalLock) {
3099 buildAssistBundleLocked(pae, extras);
3100 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003101 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003102 if (!exists) {
3103 // Timed out.
3104 return;
3105 }
3106
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003107 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003108 // Caller wants result sent back to them.
3109 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003110 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003111 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003112 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3113 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003114 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3115 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3116 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3117 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3118 }
3119 }
3120 if (sendReceiver != null) {
3121 try {
3122 sendReceiver.onHandleAssistData(sendBundle);
3123 } catch (RemoteException e) {
3124 }
3125 return;
3126 }
3127
3128 final long ident = Binder.clearCallingIdentity();
3129 try {
3130 if (TextUtils.equals(pae.intent.getAction(),
3131 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003132 // Start voice interaction through VoiceInteractionManagerService.
3133 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3134 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003135 } else {
3136 pae.intent.replaceExtras(pae.extras);
3137 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3138 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3139 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003140 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003141
3142 try {
3143 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3144 } catch (ActivityNotFoundException e) {
3145 Slog.w(TAG, "No activity to handle assist action.", e);
3146 }
3147 }
3148 } finally {
3149 Binder.restoreCallingIdentity(ident);
3150 }
3151 }
3152
3153 @Override
3154 public int addAppTask(IBinder activityToken, Intent intent,
3155 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3156 final int callingUid = Binder.getCallingUid();
3157 final long callingIdent = Binder.clearCallingIdentity();
3158
3159 try {
3160 synchronized (mGlobalLock) {
3161 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3162 if (r == null) {
3163 throw new IllegalArgumentException("Activity does not exist; token="
3164 + activityToken);
3165 }
3166 ComponentName comp = intent.getComponent();
3167 if (comp == null) {
3168 throw new IllegalArgumentException("Intent " + intent
3169 + " must specify explicit component");
3170 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003171 if (thumbnail.getWidth() != mThumbnailWidth
3172 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003173 throw new IllegalArgumentException("Bad thumbnail size: got "
3174 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003175 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003176 }
3177 if (intent.getSelector() != null) {
3178 intent.setSelector(null);
3179 }
3180 if (intent.getSourceBounds() != null) {
3181 intent.setSourceBounds(null);
3182 }
3183 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3184 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3185 // The caller has added this as an auto-remove task... that makes no
3186 // sense, so turn off auto-remove.
3187 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3188 }
3189 }
3190 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3191 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3192 if (ainfo.applicationInfo.uid != callingUid) {
3193 throw new SecurityException(
3194 "Can't add task for another application: target uid="
3195 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3196 }
3197
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003198 final ActivityStack stack = r.getRootTask();
Wale Ogunwale0d465192020-01-23 19:14:44 -08003199 final Task task = stack.getDisplay().createStack(stack.getWindowingMode(),
3200 stack.getActivityType(), !ON_TOP, ainfo, intent);
3201
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003202 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003203 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003204 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003205 return INVALID_TASK_ID;
3206 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003207 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003208
3209 // TODO: Send the thumbnail to WM to store it.
3210
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003211 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003212 }
3213 } finally {
3214 Binder.restoreCallingIdentity(callingIdent);
3215 }
3216 }
3217
3218 @Override
3219 public Point getAppTaskThumbnailSize() {
3220 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003221 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003222 }
3223 }
3224
3225 @Override
3226 public void setTaskResizeable(int taskId, int resizeableMode) {
3227 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003228 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003229 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3230 if (task == null) {
3231 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3232 return;
3233 }
3234 task.setResizeMode(resizeableMode);
3235 }
3236 }
3237
3238 @Override
3239 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003240 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003241 long ident = Binder.clearCallingIdentity();
3242 try {
3243 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003244 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003245 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003246 if (task == null) {
3247 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3248 return;
3249 }
3250 // Place the task in the right stack if it isn't there already based on
3251 // the requested bounds.
3252 // The stack transition logic is:
3253 // - a null bounds on a freeform task moves that task to fullscreen
3254 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3255 // that task to freeform
3256 // - otherwise the task is not moved
3257 ActivityStack stack = task.getStack();
3258 if (!task.getWindowConfiguration().canResizeTask()) {
3259 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3260 }
3261 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3262 stack = stack.getDisplay().getOrCreateStack(
3263 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3264 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3265 stack = stack.getDisplay().getOrCreateStack(
3266 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3267 }
3268
3269 // Reparent the task to the right stack if necessary
3270 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3271 if (stack != task.getStack()) {
3272 // Defer resume until the task is resized below
3273 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3274 DEFER_RESUME, "resizeTask");
3275 preserveWindow = false;
3276 }
3277
3278 // After reparenting (which only resizes the task to the stack bounds), resize the
3279 // task to the actual bounds provided
3280 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3281 }
3282 } finally {
3283 Binder.restoreCallingIdentity(ident);
3284 }
3285 }
3286
3287 @Override
3288 public boolean releaseActivityInstance(IBinder token) {
3289 synchronized (mGlobalLock) {
3290 final long origId = Binder.clearCallingIdentity();
3291 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003292 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3293 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003294 return false;
3295 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003296 r.destroyImmediately(true /* removeFromApp */, "app-req");
3297 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003298 } finally {
3299 Binder.restoreCallingIdentity(origId);
3300 }
3301 }
3302 }
3303
3304 @Override
3305 public void releaseSomeActivities(IApplicationThread appInt) {
3306 synchronized (mGlobalLock) {
3307 final long origId = Binder.clearCallingIdentity();
3308 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003309 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003310 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003311 } finally {
3312 Binder.restoreCallingIdentity(origId);
3313 }
3314 }
3315 }
3316
3317 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003318 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003319 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003320 != PackageManager.PERMISSION_GRANTED) {
3321 throw new SecurityException("Requires permission "
3322 + android.Manifest.permission.DEVICE_POWER);
3323 }
3324
3325 synchronized (mGlobalLock) {
3326 long ident = Binder.clearCallingIdentity();
3327 if (mKeyguardShown != keyguardShowing) {
3328 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003329 final Message msg = PooledLambda.obtainMessage(
3330 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3331 keyguardShowing);
3332 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003333 }
3334 try {
wilsonshih177261f2019-02-22 12:02:18 +08003335 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003336 } finally {
3337 Binder.restoreCallingIdentity(ident);
3338 }
3339 }
3340
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003341 mH.post(() -> {
3342 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3343 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3344 }
3345 });
3346 }
3347
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003348 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003349 mH.post(() -> {
3350 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3351 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3352 }
3353 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003354 }
3355
3356 @Override
3357 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003358 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3359 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003360
3361 final File passedIconFile = new File(filePath);
3362 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3363 passedIconFile.getName());
3364 if (!legitIconFile.getPath().equals(filePath)
3365 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3366 throw new IllegalArgumentException("Bad file path: " + filePath
3367 + " passed for userId " + userId);
3368 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003369 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 }
3371
3372 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003373 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003374 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003375 synchronized (mGlobalLock) {
3376 final long ident = Binder.clearCallingIdentity();
3377 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003378 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003379 if (stack == null) {
3380 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3381 return;
3382 }
3383 if (!stack.isActivityTypeStandardOrUndefined()) {
3384 throw new IllegalArgumentException(
3385 "Removing non-standard stack is not allowed.");
3386 }
3387 mStackSupervisor.removeStack(stack);
3388 } finally {
3389 Binder.restoreCallingIdentity(ident);
3390 }
3391 }
3392 }
3393
3394 @Override
3395 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003396 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003397
3398 synchronized (mGlobalLock) {
3399 final long ident = Binder.clearCallingIdentity();
3400 try {
3401 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3402 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003403 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 } finally {
3405 Binder.restoreCallingIdentity(ident);
3406 }
3407 }
3408 }
3409
3410 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003411 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 synchronized (mGlobalLock) {
3413 long ident = Binder.clearCallingIdentity();
3414 try {
3415 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3416 if (r == null) {
3417 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003418 "toggleFreeformWindowingMode: No activity record matching token="
3419 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003420 }
3421
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003422 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003423 if (stack == null) {
3424 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3425 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003426 }
3427
Yunfan Chend967af82019-01-17 18:30:18 +09003428 if (!stack.inFreeformWindowingMode()
3429 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3430 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3431 + "toggle between fullscreen and freeform.");
3432 }
3433
3434 if (stack.inFreeformWindowingMode()) {
3435 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003436 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003437 throw new IllegalStateException("Size-compat windows are currently not"
3438 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003439 } else if (stack.getParent().inFreeformWindowingMode()) {
3440 // If the window is on a freeform display, set it to undefined. It will be
3441 // resolved to freeform and it can adjust windowing mode when the display mode
3442 // changes in runtime.
3443 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003444 } else {
3445 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3446 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003447 } finally {
3448 Binder.restoreCallingIdentity(ident);
3449 }
3450 }
3451 }
3452
3453 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3454 @Override
3455 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003456 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003457 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003458 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003459 }
3460
3461 /** Unregister a task stack listener so that it stops receiving callbacks. */
3462 @Override
3463 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003464 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003465 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003466 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003467 }
3468
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003469 @Override
3470 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3471 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3472 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3473 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3474 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3475 }
3476
3477 @Override
3478 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3479 IBinder activityToken, int flags) {
3480 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3481 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3482 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3483 }
3484
3485 @Override
3486 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3487 Bundle args) {
3488 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3489 true /* focused */, true /* newSessionId */, userHandle, args,
3490 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3491 }
3492
3493 @Override
3494 public Bundle getAssistContextExtras(int requestType) {
3495 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3496 null, null, true /* focused */, true /* newSessionId */,
3497 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3498 if (pae == null) {
3499 return null;
3500 }
3501 synchronized (pae) {
3502 while (!pae.haveResult) {
3503 try {
3504 pae.wait();
3505 } catch (InterruptedException e) {
3506 }
3507 }
3508 }
3509 synchronized (mGlobalLock) {
3510 buildAssistBundleLocked(pae, pae.result);
3511 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003512 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003513 }
3514 return pae.extras;
3515 }
3516
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003517 /**
3518 * Binder IPC calls go through the public entry point.
3519 * This can be called with or without the global lock held.
3520 */
3521 private static int checkCallingPermission(String permission) {
3522 return checkPermission(
3523 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3524 }
3525
3526 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003527 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003528 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3529 mAmInternal.enforceCallingPermission(permission, func);
3530 }
3531 }
3532
3533 @VisibleForTesting
3534 int checkGetTasksPermission(String permission, int pid, int uid) {
3535 return checkPermission(permission, pid, uid);
3536 }
3537
3538 static int checkPermission(String permission, int pid, int uid) {
3539 if (permission == null) {
3540 return PackageManager.PERMISSION_DENIED;
3541 }
3542 return checkComponentPermission(permission, pid, uid, -1, true);
3543 }
3544
Wale Ogunwale214f3482018-10-04 11:00:47 -07003545 public static int checkComponentPermission(String permission, int pid, int uid,
3546 int owningUid, boolean exported) {
3547 return ActivityManagerService.checkComponentPermission(
3548 permission, pid, uid, owningUid, exported);
3549 }
3550
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003551 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3552 if (getRecentTasks().isCallerRecents(callingUid)) {
3553 // Always allow the recents component to get tasks
3554 return true;
3555 }
3556
3557 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3558 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3559 if (!allowed) {
3560 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3561 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3562 // Temporary compatibility: some existing apps on the system image may
3563 // still be requesting the old permission and not switched to the new
3564 // one; if so, we'll still allow them full access. This means we need
3565 // to see if they are holding the old permission and are a system app.
3566 try {
3567 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3568 allowed = true;
3569 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3570 + " is using old GET_TASKS but privileged; allowing");
3571 }
3572 } catch (RemoteException e) {
3573 }
3574 }
3575 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3576 + " does not hold REAL_GET_TASKS; limiting output");
3577 }
3578 return allowed;
3579 }
3580
Nicholas Sauer0259e532019-08-30 08:24:55 -07003581 boolean isCrossUserAllowed(int pid, int uid) {
3582 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3583 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3584 }
3585
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003586 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3587 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3588 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3589 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003590 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003591 "enqueueAssistContext()");
3592
3593 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003594 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003595 if (activity == null) {
3596 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3597 return null;
3598 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003599 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003600 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3601 return null;
3602 }
3603 if (focused) {
3604 if (activityToken != null) {
3605 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3606 if (activity != caller) {
3607 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3608 + " is not current top " + activity);
3609 return null;
3610 }
3611 }
3612 } else {
3613 activity = ActivityRecord.forTokenLocked(activityToken);
3614 if (activity == null) {
3615 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3616 + " couldn't be found");
3617 return null;
3618 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003619 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003620 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3621 return null;
3622 }
3623 }
3624
3625 PendingAssistExtras pae;
3626 Bundle extras = new Bundle();
3627 if (args != null) {
3628 extras.putAll(args);
3629 }
3630 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003631 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003632
3633 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3634 userHandle);
3635 pae.isHome = activity.isActivityTypeHome();
3636
3637 // Increment the sessionId if necessary
3638 if (newSessionId) {
3639 mViSessionId++;
3640 }
3641 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003642 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3643 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003644 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003645 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003646 } catch (RemoteException e) {
3647 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3648 return null;
3649 }
3650 return pae;
3651 }
3652 }
3653
3654 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3655 if (result != null) {
3656 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3657 }
3658 if (pae.hint != null) {
3659 pae.extras.putBoolean(pae.hint, true);
3660 }
3661 }
3662
3663 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3664 IAssistDataReceiver receiver;
3665 synchronized (mGlobalLock) {
3666 mPendingAssistExtras.remove(pae);
3667 receiver = pae.receiver;
3668 }
3669 if (receiver != null) {
3670 // Caller wants result sent back to them.
3671 Bundle sendBundle = new Bundle();
3672 // At least return the receiver extras
3673 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3674 try {
3675 pae.receiver.onHandleAssistData(sendBundle);
3676 } catch (RemoteException e) {
3677 }
3678 }
3679 }
3680
3681 public class PendingAssistExtras extends Binder implements Runnable {
3682 public final ActivityRecord activity;
3683 public boolean isHome;
3684 public final Bundle extras;
3685 public final Intent intent;
3686 public final String hint;
3687 public final IAssistDataReceiver receiver;
3688 public final int userHandle;
3689 public boolean haveResult = false;
3690 public Bundle result = null;
3691 public AssistStructure structure = null;
3692 public AssistContent content = null;
3693 public Bundle receiverExtras;
3694
3695 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3696 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3697 int _userHandle) {
3698 activity = _activity;
3699 extras = _extras;
3700 intent = _intent;
3701 hint = _hint;
3702 receiver = _receiver;
3703 receiverExtras = _receiverExtras;
3704 userHandle = _userHandle;
3705 }
3706
3707 @Override
3708 public void run() {
3709 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3710 synchronized (this) {
3711 haveResult = true;
3712 notifyAll();
3713 }
3714 pendingAssistExtrasTimedOut(this);
3715 }
3716 }
3717
3718 @Override
3719 public boolean isAssistDataAllowedOnCurrentActivity() {
3720 int userId;
3721 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003722 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003723 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3724 return false;
3725 }
3726
Wale Ogunwale21e06482019-11-18 05:14:15 -08003727 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003728 if (activity == null) {
3729 return false;
3730 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003731 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003732 }
3733 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3734 }
3735
3736 @Override
3737 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3738 long ident = Binder.clearCallingIdentity();
3739 try {
3740 synchronized (mGlobalLock) {
3741 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003742 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003743 if (top != caller) {
3744 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3745 + " is not current top " + top);
3746 return false;
3747 }
3748 if (!top.nowVisible) {
3749 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3750 + " is not visible");
3751 return false;
3752 }
3753 }
3754 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3755 token);
3756 } finally {
3757 Binder.restoreCallingIdentity(ident);
3758 }
3759 }
3760
3761 @Override
3762 public boolean isRootVoiceInteraction(IBinder token) {
3763 synchronized (mGlobalLock) {
3764 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3765 if (r == null) {
3766 return false;
3767 }
3768 return r.rootVoiceInteraction;
3769 }
3770 }
3771
Wale Ogunwalef6733932018-06-27 05:14:34 -07003772 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3773 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3774 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3775 if (activityToCallback == null) return;
3776 activityToCallback.setVoiceSessionLocked(voiceSession);
3777
3778 // Inform the activity
3779 try {
3780 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3781 voiceInteractor);
3782 long token = Binder.clearCallingIdentity();
3783 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003784 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003785 } finally {
3786 Binder.restoreCallingIdentity(token);
3787 }
3788 // TODO: VI Should we cache the activity so that it's easier to find later
3789 // rather than scan through all the stacks and activities?
3790 } catch (RemoteException re) {
3791 activityToCallback.clearVoiceSessionLocked();
3792 // TODO: VI Should this terminate the voice session?
3793 }
3794 }
3795
3796 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3797 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3798 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3799 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3800 boolean wasRunningVoice = mRunningVoice != null;
3801 mRunningVoice = session;
3802 if (!wasRunningVoice) {
3803 mVoiceWakeLock.acquire();
3804 updateSleepIfNeededLocked();
3805 }
3806 }
3807 }
3808
3809 void finishRunningVoiceLocked() {
3810 if (mRunningVoice != null) {
3811 mRunningVoice = null;
3812 mVoiceWakeLock.release();
3813 updateSleepIfNeededLocked();
3814 }
3815 }
3816
3817 @Override
3818 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3819 synchronized (mGlobalLock) {
3820 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3821 if (keepAwake) {
3822 mVoiceWakeLock.acquire();
3823 } else {
3824 mVoiceWakeLock.release();
3825 }
3826 }
3827 }
3828 }
3829
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003830 @Override
3831 public ComponentName getActivityClassForToken(IBinder token) {
3832 synchronized (mGlobalLock) {
3833 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3834 if (r == null) {
3835 return null;
3836 }
3837 return r.intent.getComponent();
3838 }
3839 }
3840
3841 @Override
3842 public String getPackageForToken(IBinder token) {
3843 synchronized (mGlobalLock) {
3844 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3845 if (r == null) {
3846 return null;
3847 }
3848 return r.packageName;
3849 }
3850 }
3851
3852 @Override
3853 public void showLockTaskEscapeMessage(IBinder token) {
3854 synchronized (mGlobalLock) {
3855 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3856 if (r == null) {
3857 return;
3858 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003859 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003860 }
3861 }
3862
3863 @Override
3864 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003865 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003866 final long token = Binder.clearCallingIdentity();
3867 try {
3868 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003869 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003870 }
3871 } finally {
3872 Binder.restoreCallingIdentity(token);
3873 }
3874 }
3875
3876 /**
3877 * Try to place task to provided position. The final position might be different depending on
3878 * current user and stacks state. The task will be moved to target stack if it's currently in
3879 * different stack.
3880 */
3881 @Override
3882 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003883 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003884 synchronized (mGlobalLock) {
3885 long ident = Binder.clearCallingIdentity();
3886 try {
3887 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3888 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003889 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003890 if (task == null) {
3891 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3892 + taskId);
3893 }
3894
Louis Chang149d5c82019-12-30 09:47:39 +08003895 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003896
3897 if (stack == null) {
3898 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3899 + stackId);
3900 }
3901 if (!stack.isActivityTypeStandardOrUndefined()) {
3902 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3903 + " the position of task " + taskId + " in/to non-standard stack");
3904 }
3905
3906 // TODO: Have the callers of this API call a separate reparent method if that is
3907 // what they intended to do vs. having this method also do reparenting.
3908 if (task.getStack() == stack) {
3909 // Change position in current stack.
3910 stack.positionChildAt(task, position);
3911 } else {
3912 // Reparent to new stack.
3913 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3914 !DEFER_RESUME, "positionTaskInStack");
3915 }
3916 } finally {
3917 Binder.restoreCallingIdentity(ident);
3918 }
3919 }
3920 }
3921
3922 @Override
3923 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3924 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3925 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003926 + Arrays.toString(horizontalSizeConfiguration) + " "
3927 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003928 synchronized (mGlobalLock) {
3929 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3930 if (record == null) {
3931 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3932 + "found for: " + token);
3933 }
3934 record.setSizeConfigurations(horizontalSizeConfiguration,
3935 verticalSizeConfigurations, smallestSizeConfigurations);
3936 }
3937 }
3938
3939 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003940 * Dismisses Pip
3941 * @param animate True if the dismissal should be animated.
3942 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3943 * default animation duration should be used.
3944 */
3945 @Override
3946 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003947 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003948 final long ident = Binder.clearCallingIdentity();
3949 try {
3950 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003951 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08003952 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003953 if (stack == null) {
3954 Slog.w(TAG, "dismissPip: pinned stack not found.");
3955 return;
3956 }
3957 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3958 throw new IllegalArgumentException("Stack: " + stack
3959 + " doesn't support animated resize.");
3960 }
Hongwei Wang85cf41f2020-01-15 15:14:47 -08003961 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003962 }
3963 } finally {
3964 Binder.restoreCallingIdentity(ident);
3965 }
3966 }
3967
3968 @Override
3969 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003970 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003971 synchronized (mGlobalLock) {
3972 mSuppressResizeConfigChanges = suppress;
3973 }
3974 }
3975
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003976 @Override
3977 // TODO: API should just be about changing windowing modes...
3978 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003979 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003980 "moveTasksToFullscreenStack()");
3981 synchronized (mGlobalLock) {
3982 final long origId = Binder.clearCallingIdentity();
3983 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003984 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003985 if (stack != null){
3986 if (!stack.isActivityTypeStandardOrUndefined()) {
3987 throw new IllegalArgumentException(
3988 "You can't move tasks from non-standard stacks.");
3989 }
3990 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3991 }
3992 } finally {
3993 Binder.restoreCallingIdentity(origId);
3994 }
3995 }
3996 }
3997
3998 /**
3999 * Moves the top activity in the input stackId to the pinned stack.
4000 *
4001 * @param stackId Id of stack to move the top activity to pinned stack.
4002 * @param bounds Bounds to use for pinned stack.
4003 *
4004 * @return True if the top activity of the input stack was successfully moved to the pinned
4005 * stack.
4006 */
4007 @Override
4008 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004009 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004010 "moveTopActivityToPinnedStack()");
4011 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004012 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004013 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4014 + "Device doesn't support picture-in-picture mode");
4015 }
4016
4017 long ident = Binder.clearCallingIdentity();
4018 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004019 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004020 } finally {
4021 Binder.restoreCallingIdentity(ident);
4022 }
4023 }
4024 }
4025
4026 @Override
4027 public boolean isInMultiWindowMode(IBinder token) {
4028 final long origId = Binder.clearCallingIdentity();
4029 try {
4030 synchronized (mGlobalLock) {
4031 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4032 if (r == null) {
4033 return false;
4034 }
4035 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4036 return r.inMultiWindowMode();
4037 }
4038 } finally {
4039 Binder.restoreCallingIdentity(origId);
4040 }
4041 }
4042
4043 @Override
4044 public boolean isInPictureInPictureMode(IBinder token) {
4045 final long origId = Binder.clearCallingIdentity();
4046 try {
4047 synchronized (mGlobalLock) {
4048 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4049 }
4050 } finally {
4051 Binder.restoreCallingIdentity(origId);
4052 }
4053 }
4054
4055 private boolean isInPictureInPictureMode(ActivityRecord r) {
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004056 return r != null
4057 && r.getRootTask() != null
4058 && r.inPinnedWindowingMode()
4059 && r.getRootTask().isInStackLocked(r) != null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004060 }
4061
4062 @Override
4063 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4064 final long origId = Binder.clearCallingIdentity();
4065 try {
4066 synchronized (mGlobalLock) {
4067 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4068 "enterPictureInPictureMode", token, params);
4069
4070 // If the activity is already in picture in picture mode, then just return early
4071 if (isInPictureInPictureMode(r)) {
4072 return true;
4073 }
4074
4075 // Activity supports picture-in-picture, now check that we can enter PiP at this
4076 // point, if it is
4077 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4078 false /* beforeStopping */)) {
4079 return false;
4080 }
4081
4082 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004083 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004084 if (r.getParent() == null) {
4085 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4086 return;
4087 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004088 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004089 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004090 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4091 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4092 // Adjust the source bounds by the insets for the transition down
4093 final Rect sourceBounds = new Rect(
4094 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004095 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004096 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004097 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004098 stack.setPictureInPictureAspectRatio(aspectRatio);
4099 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004100 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4101 r.info.applicationInfo.uid, r.shortComponentName,
4102 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004103 logPictureInPictureArgs(params);
4104 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004105 };
4106
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004107 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004108 // If the keyguard is showing or occluded, then try and dismiss it before
4109 // entering picture-in-picture (this will prompt the user to authenticate if the
4110 // device is currently locked).
4111 dismissKeyguard(token, new KeyguardDismissCallback() {
4112 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004113 public void onDismissSucceeded() {
4114 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004115 }
4116 }, null /* message */);
4117 } else {
4118 // Enter picture in picture immediately otherwise
4119 enterPipRunnable.run();
4120 }
4121 return true;
4122 }
4123 } finally {
4124 Binder.restoreCallingIdentity(origId);
4125 }
4126 }
4127
4128 @Override
4129 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4130 final long origId = Binder.clearCallingIdentity();
4131 try {
4132 synchronized (mGlobalLock) {
4133 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4134 "setPictureInPictureParams", token, params);
4135
4136 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004137 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004138 if (r.inPinnedWindowingMode()) {
4139 // If the activity is already in picture-in-picture, update the pinned stack now
4140 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4141 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004142 final ActivityStack stack = r.getRootTask();
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004143 stack.setPictureInPictureAspectRatio(
4144 r.pictureInPictureArgs.getAspectRatio());
4145 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004146 }
4147 logPictureInPictureArgs(params);
4148 }
4149 } finally {
4150 Binder.restoreCallingIdentity(origId);
4151 }
4152 }
4153
4154 @Override
4155 public int getMaxNumPictureInPictureActions(IBinder token) {
4156 // Currently, this is a static constant, but later, we may change this to be dependent on
4157 // the context of the activity
4158 return 3;
4159 }
4160
4161 private void logPictureInPictureArgs(PictureInPictureParams params) {
4162 if (params.hasSetActions()) {
4163 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4164 params.getActions().size());
4165 }
4166 if (params.hasSetAspectRatio()) {
4167 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4168 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4169 MetricsLogger.action(lm);
4170 }
4171 }
4172
4173 /**
4174 * Checks the state of the system and the activity associated with the given {@param token} to
4175 * verify that picture-in-picture is supported for that activity.
4176 *
4177 * @return the activity record for the given {@param token} if all the checks pass.
4178 */
4179 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4180 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004181 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004182 throw new IllegalStateException(caller
4183 + ": Device doesn't support picture-in-picture mode.");
4184 }
4185
4186 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4187 if (r == null) {
4188 throw new IllegalStateException(caller
4189 + ": Can't find activity for token=" + token);
4190 }
4191
4192 if (!r.supportsPictureInPicture()) {
4193 throw new IllegalStateException(caller
4194 + ": Current activity does not support picture-in-picture.");
4195 }
4196
4197 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004198 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004199 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004200 final float minAspectRatio = mContext.getResources().getFloat(
4201 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4202 final float maxAspectRatio = mContext.getResources().getFloat(
4203 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4204 throw new IllegalArgumentException(String.format(caller
4205 + ": Aspect ratio is too extreme (must be between %f and %f).",
4206 minAspectRatio, maxAspectRatio));
4207 }
4208
4209 // Truncate the number of actions if necessary
4210 params.truncateActions(getMaxNumPictureInPictureActions(token));
4211
4212 return r;
4213 }
4214
4215 @Override
4216 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004217 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004218 synchronized (mGlobalLock) {
4219 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4220 if (r == null) {
4221 throw new IllegalArgumentException("Activity does not exist; token="
4222 + activityToken);
4223 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004224 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004225 }
4226 }
4227
4228 @Override
4229 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4230 Rect tempDockedTaskInsetBounds,
4231 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004232 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004233 long ident = Binder.clearCallingIdentity();
4234 try {
4235 synchronized (mGlobalLock) {
4236 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4237 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4238 PRESERVE_WINDOWS);
4239 }
4240 } finally {
4241 Binder.restoreCallingIdentity(ident);
4242 }
4243 }
4244
4245 @Override
4246 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004247 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004248 final long ident = Binder.clearCallingIdentity();
4249 try {
4250 synchronized (mGlobalLock) {
4251 mStackSupervisor.setSplitScreenResizing(resizing);
4252 }
4253 } finally {
4254 Binder.restoreCallingIdentity(ident);
4255 }
4256 }
4257
Evan Rosky0037e5f2019-11-05 10:26:24 -08004258 @Override
4259 public ITaskOrganizerController getTaskOrganizerController() {
4260 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
4261 "getTaskOrganizerController()");
4262 return mTaskOrganizerController;
4263 }
4264
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004265 /**
4266 * Check that we have the features required for VR-related API calls, and throw an exception if
4267 * not.
4268 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004269 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004270 if (!mContext.getPackageManager().hasSystemFeature(
4271 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4272 throw new UnsupportedOperationException("VR mode not supported on this device!");
4273 }
4274 }
4275
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004276 @Override
4277 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004278 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004279
4280 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4281
4282 ActivityRecord r;
4283 synchronized (mGlobalLock) {
4284 r = ActivityRecord.isInStackLocked(token);
4285 }
4286
4287 if (r == null) {
4288 throw new IllegalArgumentException();
4289 }
4290
4291 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004292 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004293 VrManagerInternal.NO_ERROR) {
4294 return err;
4295 }
4296
4297 // Clear the binder calling uid since this path may call moveToTask().
4298 final long callingId = Binder.clearCallingIdentity();
4299 try {
4300 synchronized (mGlobalLock) {
4301 r.requestedVrComponent = (enabled) ? packageName : null;
4302
4303 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004304 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004305 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004306 }
4307 return 0;
4308 }
4309 } finally {
4310 Binder.restoreCallingIdentity(callingId);
4311 }
4312 }
4313
4314 @Override
4315 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4316 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4317 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004318 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004319 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4320 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4321 }
Louis Changcdec0802019-11-11 11:45:07 +08004322 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004323 || activity.voiceSession != null) {
4324 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4325 return;
4326 }
4327 if (activity.pendingVoiceInteractionStart) {
4328 Slog.w(TAG, "Pending start of voice interaction already.");
4329 return;
4330 }
4331 activity.pendingVoiceInteractionStart = true;
4332 }
4333 LocalServices.getService(VoiceInteractionManagerInternal.class)
4334 .startLocalVoiceInteraction(callingActivity, options);
4335 }
4336
4337 @Override
4338 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4339 LocalServices.getService(VoiceInteractionManagerInternal.class)
4340 .stopLocalVoiceInteraction(callingActivity);
4341 }
4342
4343 @Override
4344 public boolean supportsLocalVoiceInteraction() {
4345 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4346 .supportsLocalVoiceInteraction();
4347 }
4348
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004349 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004350 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004351 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004352
4353 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004354 if (mWindowManager == null) {
4355 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4356 return false;
4357 }
4358
4359 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004360 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004361 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004362 }
4363
Riddle Hsua0022cd2019-09-09 21:12:41 +08004364 mH.sendMessage(PooledLambda.obtainMessage(
4365 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4366 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367
4368 final long origId = Binder.clearCallingIdentity();
4369 try {
4370 if (values != null) {
4371 Settings.System.clearConfiguration(values);
4372 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004373 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004374 UserHandle.USER_NULL, false /* deferResume */,
4375 mTmpUpdateConfigurationResult);
4376 return mTmpUpdateConfigurationResult.changes != 0;
4377 } finally {
4378 Binder.restoreCallingIdentity(origId);
4379 }
4380 }
4381 }
4382
4383 @Override
4384 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4385 CharSequence message) {
4386 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004387 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004388 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4389 }
4390 final long callingId = Binder.clearCallingIdentity();
4391 try {
4392 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004393 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004394 }
4395 } finally {
4396 Binder.restoreCallingIdentity(callingId);
4397 }
4398 }
4399
4400 @Override
4401 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004402 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004403 "cancelTaskWindowTransition()");
4404 final long ident = Binder.clearCallingIdentity();
4405 try {
4406 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004407 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004408 MATCH_TASK_IN_STACKS_ONLY);
4409 if (task == null) {
4410 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4411 return;
4412 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004413 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004414 }
4415 } finally {
4416 Binder.restoreCallingIdentity(ident);
4417 }
4418 }
4419
4420 @Override
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004421 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004422 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004423 final long ident = Binder.clearCallingIdentity();
4424 try {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004425 return getTaskSnapshot(taskId, isLowResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004426 } finally {
4427 Binder.restoreCallingIdentity(ident);
4428 }
4429 }
4430
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004431 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004432 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004433 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004434 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004435 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004436 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4437 if (task == null) {
4438 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4439 return null;
4440 }
4441 }
4442 // Don't call this while holding the lock as this operation might hit the disk.
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004443 return task.getSnapshot(isLowResolution, restoreFromDisk);
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004444 }
4445
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004446 @Override
4447 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4448 synchronized (mGlobalLock) {
4449 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4450 if (r == null) {
4451 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4452 + token);
4453 return;
4454 }
4455 final long origId = Binder.clearCallingIdentity();
4456 try {
4457 r.setDisablePreviewScreenshots(disable);
4458 } finally {
4459 Binder.restoreCallingIdentity(origId);
4460 }
4461 }
4462 }
4463
Riddle Hsu440f88b2019-11-06 22:17:35 +08004464 @Override
4465 public void invalidateHomeTaskSnapshot(IBinder token) {
4466 synchronized (mGlobalLock) {
4467 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4468 if (r == null || !r.isActivityTypeHome()) {
4469 return;
4470 }
4471 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4472 }
4473 }
4474
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004475 /** Return the user id of the last resumed activity. */
4476 @Override
4477 public @UserIdInt
4478 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004479 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004480 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4481 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004482 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004483 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004484 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004485 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004486 }
4487 }
4488
4489 @Override
4490 public void updateLockTaskFeatures(int userId, int flags) {
4491 final int callingUid = Binder.getCallingUid();
4492 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004493 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004494 "updateLockTaskFeatures()");
4495 }
4496 synchronized (mGlobalLock) {
4497 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4498 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004499 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004500 }
4501 }
4502
4503 @Override
4504 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4505 synchronized (mGlobalLock) {
4506 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4507 if (r == null) {
4508 return;
4509 }
4510 final long origId = Binder.clearCallingIdentity();
4511 try {
4512 r.setShowWhenLocked(showWhenLocked);
4513 } finally {
4514 Binder.restoreCallingIdentity(origId);
4515 }
4516 }
4517 }
4518
4519 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004520 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4521 synchronized (mGlobalLock) {
4522 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4523 if (r == null) {
4524 return;
4525 }
4526 final long origId = Binder.clearCallingIdentity();
4527 try {
4528 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4529 } finally {
4530 Binder.restoreCallingIdentity(origId);
4531 }
4532 }
4533 }
4534
4535 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004536 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4537 synchronized (mGlobalLock) {
4538 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4539 if (r == null) {
4540 return;
4541 }
4542 final long origId = Binder.clearCallingIdentity();
4543 try {
4544 r.setTurnScreenOn(turnScreenOn);
4545 } finally {
4546 Binder.restoreCallingIdentity(origId);
4547 }
4548 }
4549 }
4550
4551 @Override
4552 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004553 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004554 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004555 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004556 synchronized (mGlobalLock) {
4557 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4558 if (r == null) {
4559 return;
4560 }
4561 final long origId = Binder.clearCallingIdentity();
4562 try {
4563 r.registerRemoteAnimations(definition);
4564 } finally {
4565 Binder.restoreCallingIdentity(origId);
4566 }
4567 }
4568 }
4569
4570 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004571 public void unregisterRemoteAnimations(IBinder token) {
4572 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4573 "unregisterRemoteAnimations");
4574 synchronized (mGlobalLock) {
4575 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4576 if (r == null) {
4577 return;
4578 }
4579 final long origId = Binder.clearCallingIdentity();
4580 try {
4581 r.unregisterRemoteAnimations();
4582 } finally {
4583 Binder.restoreCallingIdentity(origId);
4584 }
4585 }
4586 }
4587
4588 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004589 public void registerRemoteAnimationForNextActivityStart(String packageName,
4590 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004591 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004592 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004593 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004594 synchronized (mGlobalLock) {
4595 final long origId = Binder.clearCallingIdentity();
4596 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004597 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004598 packageName, adapter);
4599 } finally {
4600 Binder.restoreCallingIdentity(origId);
4601 }
4602 }
4603 }
4604
Evan Rosky966759f2019-01-15 10:33:58 -08004605 @Override
4606 public void registerRemoteAnimationsForDisplay(int displayId,
4607 RemoteAnimationDefinition definition) {
4608 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4609 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004610 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004611 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004612 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004613 if (display == null) {
4614 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4615 return;
4616 }
4617 final long origId = Binder.clearCallingIdentity();
4618 try {
4619 display.mDisplayContent.registerRemoteAnimations(definition);
4620 } finally {
4621 Binder.restoreCallingIdentity(origId);
4622 }
4623 }
4624 }
4625
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004626 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4627 @Override
4628 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4629 synchronized (mGlobalLock) {
4630 final long origId = Binder.clearCallingIdentity();
4631 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004632 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004633 } finally {
4634 Binder.restoreCallingIdentity(origId);
4635 }
4636 }
4637 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004638
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004639 @Override
4640 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004641 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004642 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004643 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004644 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004645 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004646 }
4647 }
4648
4649 @Override
4650 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004651 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004652 != PERMISSION_GRANTED) {
4653 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4654 + Binder.getCallingPid()
4655 + ", uid=" + Binder.getCallingUid()
4656 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4657 Slog.w(TAG, msg);
4658 throw new SecurityException(msg);
4659 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004660 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004661 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004662 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004663 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004664 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004665 }
4666 }
4667
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004668 @Override
4669 public void stopAppSwitches() {
4670 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4671 synchronized (mGlobalLock) {
4672 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004673 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004674 mDidAppSwitch = false;
4675 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4676 }
4677 }
4678
4679 @Override
4680 public void resumeAppSwitches() {
4681 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4682 synchronized (mGlobalLock) {
4683 // Note that we don't execute any pending app switches... we will
4684 // let those wait until either the timeout, or the next start
4685 // activity request.
4686 mAppSwitchesAllowedTime = 0;
4687 }
4688 }
4689
Ricky Wai906af482019-06-03 17:25:28 +01004690 long getLastStopAppSwitchesTime() {
4691 return mLastStopAppSwitchesTime;
4692 }
4693
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004694 void onStartActivitySetDidAppSwitch() {
4695 if (mDidAppSwitch) {
4696 // This is the second allowed switch since we stopped switches, so now just generally
4697 // allow switches. Use case:
4698 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4699 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4700 // anyone to switch again).
4701 mAppSwitchesAllowedTime = 0;
4702 } else {
4703 mDidAppSwitch = true;
4704 }
4705 }
4706
4707 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004708 boolean shouldDisableNonVrUiLocked() {
4709 return mVrController.shouldDisableNonVrUiLocked();
4710 }
4711
Wale Ogunwale53783742018-09-16 10:21:51 -07004712 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004713 // 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 +00004714 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004715 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004716 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4717 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004718 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004719 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004720 }
4721 mH.post(() -> {
4722 if (!mVrController.onVrModeChanged(r)) {
4723 return;
4724 }
4725 synchronized (mGlobalLock) {
4726 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4727 mWindowManager.disableNonVrUi(disableNonVrUi);
4728 if (disableNonVrUi) {
4729 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4730 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004731 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004732 }
4733 }
4734 });
4735 }
4736
Wale Ogunwale53783742018-09-16 10:21:51 -07004737 @Override
4738 public int getPackageScreenCompatMode(String packageName) {
4739 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4740 synchronized (mGlobalLock) {
4741 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4742 }
4743 }
4744
4745 @Override
4746 public void setPackageScreenCompatMode(String packageName, int mode) {
4747 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4748 "setPackageScreenCompatMode");
4749 synchronized (mGlobalLock) {
4750 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4751 }
4752 }
4753
4754 @Override
4755 public boolean getPackageAskScreenCompat(String packageName) {
4756 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4757 synchronized (mGlobalLock) {
4758 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4759 }
4760 }
4761
4762 @Override
4763 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4764 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4765 "setPackageAskScreenCompat");
4766 synchronized (mGlobalLock) {
4767 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4768 }
4769 }
4770
Wale Ogunwale64258362018-10-16 15:13:37 -07004771 public static String relaunchReasonToString(int relaunchReason) {
4772 switch (relaunchReason) {
4773 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4774 return "window_resize";
4775 case RELAUNCH_REASON_FREE_RESIZE:
4776 return "free_resize";
4777 default:
4778 return null;
4779 }
4780 }
4781
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004782 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004783 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004784 }
4785
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004786 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004787 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004788 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4789 }
4790
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004791 boolean isKeyguardLocked() {
4792 return mKeyguardController.isKeyguardLocked();
4793 }
4794
Garfield Tan01548632018-11-27 10:15:48 -08004795 /**
4796 * Clears launch params for the given package.
4797 * @param packageNames the names of the packages of which the launch params are to be cleared
4798 */
4799 @Override
4800 public void clearLaunchParamsForPackages(List<String> packageNames) {
4801 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4802 "clearLaunchParamsForPackages");
4803 synchronized (mGlobalLock) {
4804 for (int i = 0; i < packageNames.size(); ++i) {
4805 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4806 }
4807 }
4808 }
4809
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004810 /**
4811 * Makes the display with the given id a single task instance display. I.e the display can only
4812 * contain one task.
4813 */
4814 @Override
4815 public void setDisplayToSingleTaskInstance(int displayId) {
4816 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4817 "setDisplayToSingleTaskInstance");
4818 final long origId = Binder.clearCallingIdentity();
4819 try {
Louis Chang677921f2019-12-06 16:44:24 +08004820 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004821 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004822 if (display != null) {
4823 display.setDisplayToSingleTaskInstance();
4824 }
4825 } finally {
4826 Binder.restoreCallingIdentity(origId);
4827 }
4828 }
4829
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004830 /**
4831 * Requests that an activity should enter picture-in-picture mode if possible.
4832 */
4833 @Override
4834 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4835 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4836 "requestPictureInPictureMode");
4837 final long origId = Binder.clearCallingIdentity();
4838 try {
4839 synchronized (mGlobalLock) {
4840 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4841 if (activity == null) {
4842 return;
4843 }
4844
4845 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4846 "requestPictureInPictureMode", /* beforeStopping */ false);
4847 if (!canEnterPictureInPicture) {
4848 throw new IllegalStateException(
4849 "Requested PIP on an activity that doesn't support it");
4850 }
4851
4852 try {
4853 final ClientTransaction transaction = ClientTransaction.obtain(
4854 activity.app.getThread(),
4855 activity.token);
4856 transaction.addCallback(EnterPipRequestedItem.obtain());
4857 getLifecycleManager().scheduleTransaction(transaction);
4858 } catch (Exception e) {
4859 Slog.w(TAG, "Failed to send enter pip requested item: "
4860 + activity.intent.getComponent(), e);
4861 }
4862 }
4863 } finally {
4864 Binder.restoreCallingIdentity(origId);
4865 }
4866 }
4867
Wale Ogunwale31913b52018-10-13 08:29:31 -07004868 void dumpLastANRLocked(PrintWriter pw) {
4869 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4870 if (mLastANRState == null) {
4871 pw.println(" <no ANR has occurred since boot>");
4872 } else {
4873 pw.println(mLastANRState);
4874 }
4875 }
4876
4877 void dumpLastANRTracesLocked(PrintWriter pw) {
4878 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4879
4880 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4881 if (ArrayUtils.isEmpty(files)) {
4882 pw.println(" <no ANR has occurred since boot>");
4883 return;
4884 }
4885 // Find the latest file.
4886 File latest = null;
4887 for (File f : files) {
4888 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4889 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004890 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004891 }
4892 pw.print("File: ");
4893 pw.print(latest.getName());
4894 pw.println();
4895 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4896 String line;
4897 while ((line = in.readLine()) != null) {
4898 pw.println(line);
4899 }
4900 } catch (IOException e) {
4901 pw.print("Unable to read: ");
4902 pw.print(e);
4903 pw.println();
4904 }
4905 }
4906
4907 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4908 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4909 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4910 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4911 }
4912
4913 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4914 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4915 pw.println(header);
4916
Louis Chang149d5c82019-12-30 09:47:39 +08004917 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004918 dumpPackage);
4919 boolean needSep = printedAnything;
4920
4921 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08004922 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004923 " ResumedActivity: ");
4924 if (printed) {
4925 printedAnything = true;
4926 needSep = false;
4927 }
4928
4929 if (dumpPackage == null) {
4930 if (needSep) {
4931 pw.println();
4932 }
4933 printedAnything = true;
4934 mStackSupervisor.dump(pw, " ");
4935 }
4936
4937 if (!printedAnything) {
4938 pw.println(" (nothing)");
4939 }
4940 }
4941
4942 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004943 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08004944 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004945 pw.println(" ");
4946 }
4947
4948 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4949 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4950 getActivityStartController().dump(pw, "", dumpPackage);
4951 }
4952
4953 /**
4954 * There are three things that cmd can be:
4955 * - a flattened component name that matches an existing activity
4956 * - the cmd arg isn't the flattened component name of an existing activity:
4957 * dump all activity whose component contains the cmd as a substring
4958 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004959 * <p>
4960 * The caller should not hold lock when calling this method because it will wait for the
4961 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004962 *
4963 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4964 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4965 */
4966 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4967 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4968 ArrayList<ActivityRecord> activities;
4969
4970 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004971 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004972 dumpFocusedStackOnly);
4973 }
4974
4975 if (activities.size() <= 0) {
4976 return false;
4977 }
4978
4979 String[] newArgs = new String[args.length - opti];
4980 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4981
Louis Changcdec0802019-11-11 11:45:07 +08004982 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004983 boolean needSep = false;
4984 for (int i = activities.size() - 1; i >= 0; i--) {
4985 ActivityRecord r = activities.get(i);
4986 if (needSep) {
4987 pw.println();
4988 }
4989 needSep = true;
4990 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08004991 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004992 if (lastTask != task) {
4993 lastTask = task;
4994 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07004995 pw.print(" id="); pw.print(lastTask.mTaskId);
4996 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004997 if (dumpAll) {
4998 lastTask.dump(pw, " ");
4999 }
5000 }
5001 }
5002 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5003 }
5004 return true;
5005 }
5006
5007 /**
5008 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5009 * there is a thread associated with the activity.
5010 */
5011 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5012 final ActivityRecord r, String[] args, boolean dumpAll) {
5013 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005014 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005015 synchronized (mGlobalLock) {
5016 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5017 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5018 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005019 if (r.hasProcess()) {
5020 pw.println(r.app.getPid());
5021 appThread = r.app.getThread();
5022 } else {
5023 pw.println("(not running)");
5024 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005025 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005026 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005027 }
5028 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005029 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005030 // flush anything that is already in the PrintWriter since the thread is going
5031 // to write to the file descriptor directly
5032 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005033 try (TransferPipe tp = new TransferPipe()) {
5034 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5035 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005036 } catch (IOException e) {
5037 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5038 } catch (RemoteException e) {
5039 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5040 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005041 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005042 }
5043
sanryhuang498e77e2018-12-06 14:57:01 +08005044 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5045 boolean testPssMode) {
5046 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5047 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5048 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005049 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005050 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5051 st.toString());
5052 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005053 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5054 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5055 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005056 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5057 testPssMode);
5058 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005059 }
5060
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005061 int getCurrentUserId() {
5062 return mAmInternal.getCurrentUserId();
5063 }
5064
5065 private void enforceNotIsolatedCaller(String caller) {
5066 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5067 throw new SecurityException("Isolated process not allowed to call " + caller);
5068 }
5069 }
5070
Wale Ogunwalef6733932018-06-27 05:14:34 -07005071 public Configuration getConfiguration() {
5072 Configuration ci;
5073 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005074 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005075 ci.userSetLocale = false;
5076 }
5077 return ci;
5078 }
5079
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005080 /**
5081 * Current global configuration information. Contains general settings for the entire system,
5082 * also corresponds to the merged configuration of the default display.
5083 */
5084 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005085 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005086 // while initializing process record for system, see {@link
5087 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005088 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005089 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005090 }
5091
5092 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5093 boolean initLocale) {
5094 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5095 }
5096
5097 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5098 boolean initLocale, boolean deferResume) {
5099 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5100 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5101 UserHandle.USER_NULL, deferResume);
5102 }
5103
Wale Ogunwale59507092018-10-29 09:00:30 -07005104 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005105 final long origId = Binder.clearCallingIdentity();
5106 try {
5107 synchronized (mGlobalLock) {
5108 updateConfigurationLocked(values, null, false, true, userId,
5109 false /* deferResume */);
5110 }
5111 } finally {
5112 Binder.restoreCallingIdentity(origId);
5113 }
5114 }
5115
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005116 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5117 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5118 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5119 deferResume, null /* result */);
5120 }
5121
5122 /**
5123 * Do either or both things: (1) change the current configuration, and (2)
5124 * make sure the given activity is running with the (now) current
5125 * configuration. Returns true if the activity has been left running, or
5126 * false if <var>starting</var> is being destroyed to match the new
5127 * configuration.
5128 *
5129 * @param userId is only used when persistent parameter is set to true to persist configuration
5130 * for that particular user
5131 */
5132 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5133 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5134 ActivityTaskManagerService.UpdateConfigurationResult result) {
5135 int changes = 0;
5136 boolean kept = true;
5137
Riddle Hsua0022cd2019-09-09 21:12:41 +08005138 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005139 try {
5140 if (values != null) {
5141 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5142 deferResume);
5143 }
5144
5145 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5146 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005147 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005148 }
5149
5150 if (result != null) {
5151 result.changes = changes;
5152 result.activityRelaunched = !kept;
5153 }
5154 return kept;
5155 }
5156
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005157 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005158 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005159 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005160
Louis Chang677921f2019-12-06 16:44:24 +08005161 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005162 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005163
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005164 mTempConfig.setTo(getGlobalConfiguration());
5165 final int changes = mTempConfig.updateFrom(values);
5166 if (changes == 0) {
5167 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5168 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5169 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5170 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005171 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005172 return 0;
5173 }
5174
5175 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5176 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005177 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005178 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005179 values.colorMode,
5180 values.densityDpi,
5181 values.fontScale,
5182 values.hardKeyboardHidden,
5183 values.keyboard,
5184 values.keyboardHidden,
5185 values.mcc,
5186 values.mnc,
5187 values.navigation,
5188 values.navigationHidden,
5189 values.orientation,
5190 values.screenHeightDp,
5191 values.screenLayout,
5192 values.screenWidthDp,
5193 values.smallestScreenWidthDp,
5194 values.touchscreen,
5195 values.uiMode);
5196
5197
5198 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5199 final LocaleList locales = values.getLocales();
5200 int bestLocaleIndex = 0;
5201 if (locales.size() > 1) {
5202 if (mSupportedSystemLocales == null) {
5203 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5204 }
5205 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5206 }
5207 SystemProperties.set("persist.sys.locale",
5208 locales.get(bestLocaleIndex).toLanguageTag());
5209 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005210
5211 final Message m = PooledLambda.obtainMessage(
5212 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5213 locales.get(bestLocaleIndex));
5214 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005215 }
5216
Yunfan Chen75157d72018-07-27 14:47:21 +09005217 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005218
5219 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005220 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005221
5222 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5223 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005224 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005225
5226 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005227 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005228
5229 AttributeCache ac = AttributeCache.instance();
5230 if (ac != null) {
5231 ac.updateConfiguration(mTempConfig);
5232 }
5233
5234 // Make sure all resources in our process are updated right now, so that anyone who is going
5235 // to retrieve resource values after we return will be sure to get the new ones. This is
5236 // especially important during boot, where the first config change needs to guarantee all
5237 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005238 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005239
5240 // We need another copy of global config because we're scheduling some calls instead of
5241 // running them in place. We need to be sure that object we send will be handled unchanged.
5242 final Configuration configCopy = new Configuration(mTempConfig);
5243 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005244 final Message msg = PooledLambda.obtainMessage(
5245 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5246 this, userId, configCopy);
5247 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005248 }
5249
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005250 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5251 for (int i = pidMap.size() - 1; i >= 0; i--) {
5252 final int pid = pidMap.keyAt(i);
5253 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005254 if (DEBUG_CONFIGURATION) {
5255 Slog.v(TAG_CONFIGURATION, "Update process config of "
5256 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005257 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005258 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005259 }
5260
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005261 final Message msg = PooledLambda.obtainMessage(
5262 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5263 mAmInternal, changes, initLocale);
5264 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005265
5266 // Override configuration of the default display duplicates global config, so we need to
5267 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005268 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005269 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005270
5271 return changes;
5272 }
5273
Riddle Hsua0022cd2019-09-09 21:12:41 +08005274 /** @see WindowSurfacePlacer#deferLayout */
5275 void deferWindowLayout() {
5276 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5277 // Reset the reasons at the first entrance because we only care about the changes in the
5278 // deferred scope.
5279 mLayoutReasons = 0;
5280 }
5281
5282 mWindowManager.mWindowPlacerLocked.deferLayout();
5283 }
5284
5285 /** @see WindowSurfacePlacer#continueLayout */
5286 void continueWindowLayout() {
5287 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5288 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5289 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5290 }
5291 }
5292
5293 /**
5294 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5295 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5296 * defer count is gone.
5297 */
5298 void addWindowLayoutReasons(@LayoutReason int reasons) {
5299 mLayoutReasons |= reasons;
5300 }
5301
Wale Ogunwalef6733932018-06-27 05:14:34 -07005302 private void updateEventDispatchingLocked(boolean booted) {
5303 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5304 }
5305
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005306 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5307 final ContentResolver resolver = mContext.getContentResolver();
5308 Settings.System.putConfigurationForUser(resolver, config, userId);
5309 }
5310
5311 private void sendLocaleToMountDaemonMsg(Locale l) {
5312 try {
5313 IBinder service = ServiceManager.getService("mount");
5314 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5315 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5316 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5317 } catch (RemoteException e) {
5318 Log.e(TAG, "Error storing locale for decryption UI", e);
5319 }
5320 }
5321
Alison Cichowlas3e340502018-08-07 17:15:01 -04005322 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5323 mStartActivitySources.remove(permissionToken);
5324 mExpiredStartAsCallerTokens.add(permissionToken);
5325 }
5326
5327 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5328 mExpiredStartAsCallerTokens.remove(permissionToken);
5329 }
5330
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005331 boolean isActivityStartsLoggingEnabled() {
5332 return mAmInternal.isActivityStartsLoggingEnabled();
5333 }
5334
Michal Karpinski8596ded2018-11-14 14:43:48 +00005335 boolean isBackgroundActivityStartsEnabled() {
5336 return mAmInternal.isBackgroundActivityStartsEnabled();
5337 }
5338
Wale Ogunwalef6733932018-06-27 05:14:34 -07005339 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005340 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005341 mWindowManager.enableScreenAfterBoot();
5342
5343 synchronized (mGlobalLock) {
5344 updateEventDispatchingLocked(booted);
5345 }
5346 }
5347
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005348 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5349 if (r == null || !r.hasProcess()) {
5350 return KEY_DISPATCHING_TIMEOUT_MS;
5351 }
5352 return getInputDispatchingTimeoutLocked(r.app);
5353 }
5354
5355 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005356 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005357 }
5358
Wale Ogunwalef6733932018-06-27 05:14:34 -07005359 /**
5360 * Decide based on the configuration whether we should show the ANR,
5361 * crash, etc dialogs. The idea is that if there is no affordance to
5362 * press the on-screen buttons, or the user experience would be more
5363 * greatly impacted than the crash itself, we shouldn't show the dialog.
5364 *
5365 * A thought: SystemUI might also want to get told about this, the Power
5366 * dialog / global actions also might want different behaviors.
5367 */
5368 private void updateShouldShowDialogsLocked(Configuration config) {
5369 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5370 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5371 && config.navigation == Configuration.NAVIGATION_NONAV);
5372 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5373 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5374 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5375 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5376 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5377 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5378 HIDE_ERROR_DIALOGS, 0) != 0;
5379 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5380 }
5381
5382 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5383 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5384 FONT_SCALE, 1.0f, userId);
5385
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005386 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005387 if (getGlobalConfiguration().fontScale == scaleFactor) {
5388 return;
5389 }
5390
5391 final Configuration configuration
5392 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5393 configuration.fontScale = scaleFactor;
5394 updatePersistentConfiguration(configuration, userId);
5395 }
5396 }
5397
5398 // Actually is sleeping or shutting down or whatever else in the future
5399 // is an inactive state.
5400 boolean isSleepingOrShuttingDownLocked() {
5401 return isSleepingLocked() || mShuttingDown;
5402 }
5403
5404 boolean isSleepingLocked() {
5405 return mSleeping;
5406 }
5407
Riddle Hsu16567132018-08-16 21:37:47 +08005408 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005409 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005410 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005411 if (task.isActivityTypeStandard()) {
5412 if (mCurAppTimeTracker != r.appTimeTracker) {
5413 // We are switching app tracking. Complete the current one.
5414 if (mCurAppTimeTracker != null) {
5415 mCurAppTimeTracker.stop();
5416 mH.obtainMessage(
5417 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005418 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005419 mCurAppTimeTracker = null;
5420 }
5421 if (r.appTimeTracker != null) {
5422 mCurAppTimeTracker = r.appTimeTracker;
5423 startTimeTrackingFocusedActivityLocked();
5424 }
5425 } else {
5426 startTimeTrackingFocusedActivityLocked();
5427 }
5428 } else {
5429 r.appTimeTracker = null;
5430 }
5431 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5432 // TODO: Probably not, because we don't want to resume voice on switching
5433 // back to this activity
5434 if (task.voiceInteractor != null) {
5435 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5436 } else {
5437 finishRunningVoiceLocked();
5438
5439 if (mLastResumedActivity != null) {
5440 final IVoiceInteractionSession session;
5441
Louis Changcdec0802019-11-11 11:45:07 +08005442 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005443 if (lastResumedActivityTask != null
5444 && lastResumedActivityTask.voiceSession != null) {
5445 session = lastResumedActivityTask.voiceSession;
5446 } else {
5447 session = mLastResumedActivity.voiceSession;
5448 }
5449
5450 if (session != null) {
5451 // We had been in a voice interaction session, but now focused has
5452 // move to something different. Just finish the session, we can't
5453 // return to it and retain the proper state and synchronization with
5454 // the voice interaction service.
5455 finishVoiceTask(session);
5456 }
5457 }
5458 }
5459
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005460 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5461 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005462 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005463 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5464
Wale Ogunwalef6733932018-06-27 05:14:34 -07005465 updateResumedAppTrace(r);
5466 mLastResumedActivity = r;
5467
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005468 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005469
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005470 if (prevTask == null || task != prevTask) {
5471 if (prevTask != null) {
5472 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5473 }
5474 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5475 }
5476
Wale Ogunwalef6733932018-06-27 05:14:34 -07005477 applyUpdateLockStateLocked(r);
5478 applyUpdateVrModeLocked(r);
5479
Jeff Changd136e772019-11-05 20:33:52 +08005480 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005481 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005482 r == null ? "NULL" : r.shortComponentName,
5483 reason);
5484 }
5485
5486 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5487 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005488 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005489 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005490 updateSleepIfNeededLocked();
5491 return token;
5492 }
5493 }
5494
5495 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005496 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005497 final boolean wasSleeping = mSleeping;
5498 boolean updateOomAdj = false;
5499
5500 if (!shouldSleep) {
5501 // If wasSleeping is true, we need to wake up activity manager state from when
5502 // we started sleeping. In either case, we need to apply the sleep tokens, which
5503 // will wake up stacks or put them to sleep as appropriate.
5504 if (wasSleeping) {
5505 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005506 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5507 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005508 startTimeTrackingFocusedActivityLocked();
5509 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005510 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005511 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5512 }
Louis Chang149d5c82019-12-30 09:47:39 +08005513 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005514 if (wasSleeping) {
5515 updateOomAdj = true;
5516 }
5517 } else if (!mSleeping && shouldSleep) {
5518 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005519 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5520 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005521 if (mCurAppTimeTracker != null) {
5522 mCurAppTimeTracker.stop();
5523 }
5524 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005525 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005526 mStackSupervisor.goingToSleepLocked();
5527 updateResumedAppTrace(null /* resumed */);
5528 updateOomAdj = true;
5529 }
5530 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005531 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005532 }
5533 }
5534
5535 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005536 mH.removeCallbacks(mUpdateOomAdjRunnable);
5537 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005538 }
5539
Wale Ogunwale53783742018-09-16 10:21:51 -07005540 void updateCpuStats() {
5541 mH.post(mAmInternal::updateCpuStats);
5542 }
5543
Hui Yu03d12402018-12-06 18:00:37 -08005544 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5545 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005546 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5547 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005548 mH.sendMessage(m);
5549 }
5550
Hui Yu03d12402018-12-06 18:00:37 -08005551 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005552 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005553 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005554 if (task != null) {
5555 final ActivityRecord rootActivity = task.getRootActivity();
5556 if (rootActivity != null) {
5557 taskRoot = rootActivity.mActivityComponent;
5558 }
5559 }
5560
Hui Yu03d12402018-12-06 18:00:37 -08005561 final Message m = PooledLambda.obtainMessage(
5562 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005563 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005564 mH.sendMessage(m);
5565 }
5566
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005567 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5568 String hostingType) {
5569 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005570 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5571 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005572 + activity.processName);
5573 }
5574 // Post message to start process to avoid possible deadlock of calling into AMS with the
5575 // ATMS lock held.
5576 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5577 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5578 isTop, hostingType, activity.intent.getComponent());
5579 mH.sendMessage(m);
5580 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005581 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005582 }
5583 }
5584
Wale Ogunwale53783742018-09-16 10:21:51 -07005585 void setBooting(boolean booting) {
5586 mAmInternal.setBooting(booting);
5587 }
5588
5589 boolean isBooting() {
5590 return mAmInternal.isBooting();
5591 }
5592
5593 void setBooted(boolean booted) {
5594 mAmInternal.setBooted(booted);
5595 }
5596
5597 boolean isBooted() {
5598 return mAmInternal.isBooted();
5599 }
5600
5601 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5602 mH.post(() -> {
5603 if (finishBooting) {
5604 mAmInternal.finishBooting();
5605 }
5606 if (enableScreen) {
5607 mInternal.enableScreenAfterBoot(isBooted());
5608 }
5609 });
5610 }
5611
5612 void setHeavyWeightProcess(ActivityRecord root) {
5613 mHeavyWeightProcess = root.app;
5614 final Message m = PooledLambda.obtainMessage(
5615 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005616 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005617 mH.sendMessage(m);
5618 }
5619
5620 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5621 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5622 return;
5623 }
5624
5625 mHeavyWeightProcess = null;
5626 final Message m = PooledLambda.obtainMessage(
5627 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5628 proc.mUserId);
5629 mH.sendMessage(m);
5630 }
5631
5632 private void cancelHeavyWeightProcessNotification(int userId) {
5633 final INotificationManager inm = NotificationManager.getService();
5634 if (inm == null) {
5635 return;
5636 }
5637 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005638 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005639 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5640 } catch (RuntimeException e) {
5641 Slog.w(TAG, "Error canceling notification for service", e);
5642 } catch (RemoteException e) {
5643 }
5644
5645 }
5646
5647 private void postHeavyWeightProcessNotification(
5648 WindowProcessController proc, Intent intent, int userId) {
5649 if (proc == null) {
5650 return;
5651 }
5652
5653 final INotificationManager inm = NotificationManager.getService();
5654 if (inm == null) {
5655 return;
5656 }
5657
5658 try {
5659 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5660 String text = mContext.getString(R.string.heavy_weight_notification,
5661 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5662 Notification notification =
5663 new Notification.Builder(context,
5664 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5665 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5666 .setWhen(0)
5667 .setOngoing(true)
5668 .setTicker(text)
5669 .setColor(mContext.getColor(
5670 com.android.internal.R.color.system_notification_accent_color))
5671 .setContentTitle(text)
5672 .setContentText(
5673 mContext.getText(R.string.heavy_weight_notification_detail))
5674 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5675 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5676 new UserHandle(userId)))
5677 .build();
5678 try {
5679 inm.enqueueNotificationWithTag("android", "android", null,
5680 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5681 } catch (RuntimeException e) {
5682 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5683 } catch (RemoteException e) {
5684 }
5685 } catch (PackageManager.NameNotFoundException e) {
5686 Slog.w(TAG, "Unable to create context for heavy notification", e);
5687 }
5688
5689 }
5690
Philip P. Moltmannee295092020-02-10 08:46:26 -08005691 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5692 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5693 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005694
5695 ActivityRecord activity = null;
5696 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5697 activity = ActivityRecord.isInStackLocked(token);
5698 if (activity == null) {
5699 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5700 return null;
5701 }
5702 if (activity.finishing) {
5703 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5704 return null;
5705 }
5706 }
5707
5708 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005709 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5710 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005711 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5712 if (noCreate) {
5713 return rec;
5714 }
5715 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5716 if (activity.pendingResults == null) {
5717 activity.pendingResults = new HashSet<>();
5718 }
5719 activity.pendingResults.add(rec.ref);
5720 }
5721 return rec;
5722 }
5723
Andrii Kulian52d255c2018-07-13 11:32:19 -07005724 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005725 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005726 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005727 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5728 mCurAppTimeTracker.start(resumedActivity.packageName);
5729 }
5730 }
5731
5732 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5733 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005734 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005735 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5736 }
5737 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005738 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005739 constructResumedTraceName(resumed.packageName), 0);
5740 }
5741 mTracedResumedActivity = resumed;
5742 }
5743
5744 private String constructResumedTraceName(String packageName) {
5745 return "focused app: " + packageName;
5746 }
5747
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005748 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005749 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005750 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005751 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005752 // mainStack is null during startup.
5753 if (mainStack != null) {
5754 if (changes != 0 && starting == null) {
5755 // If the configuration changed, and the caller is not already
5756 // in the process of starting an activity, then find the top
5757 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005758 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005759 }
5760
5761 if (starting != null) {
5762 kept = starting.ensureActivityConfiguration(changes,
5763 false /* preserveWindow */);
5764 // And we need to make sure at this point that all other activities
5765 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005766 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005767 !PRESERVE_WINDOWS);
5768 }
5769 }
5770
5771 return kept;
5772 }
5773
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005774 void scheduleAppGcsLocked() {
5775 mH.post(() -> mAmInternal.scheduleAppGcs());
5776 }
5777
Wale Ogunwale53783742018-09-16 10:21:51 -07005778 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5779 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5780 }
5781
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005782 /**
5783 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5784 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5785 * on demand.
5786 */
5787 IPackageManager getPackageManager() {
5788 return AppGlobals.getPackageManager();
5789 }
5790
5791 PackageManagerInternal getPackageManagerInternalLocked() {
5792 if (mPmInternal == null) {
5793 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5794 }
5795 return mPmInternal;
5796 }
5797
Hai Zhangf4da9be2019-05-01 13:46:06 +08005798 PermissionPolicyInternal getPermissionPolicyInternal() {
5799 if (mPermissionPolicyInternal == null) {
5800 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5801 }
5802 return mPermissionPolicyInternal;
5803 }
5804
Wale Ogunwale008163e2018-07-23 23:11:08 -07005805 AppWarnings getAppWarningsLocked() {
5806 return mAppWarnings;
5807 }
5808
Wale Ogunwale214f3482018-10-04 11:00:47 -07005809 Intent getHomeIntent() {
5810 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5811 intent.setComponent(mTopComponent);
5812 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5813 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5814 intent.addCategory(Intent.CATEGORY_HOME);
5815 }
5816 return intent;
5817 }
5818
Chilun2ef71f72018-11-16 17:57:15 +08005819 /**
5820 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5821 * activities.
5822 *
5823 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5824 * component defined in config_secondaryHomeComponent.
5825 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5826 */
5827 Intent getSecondaryHomeIntent(String preferredPackage) {
5828 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005829 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5830 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5831 if (preferredPackage == null || useSystemProvidedLauncher) {
5832 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005833 final String secondaryHomeComponent = mContext.getResources().getString(
5834 com.android.internal.R.string.config_secondaryHomeComponent);
5835 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5836 } else {
5837 intent.setPackage(preferredPackage);
5838 }
5839 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5840 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5841 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5842 }
5843 return intent;
5844 }
5845
Wale Ogunwale214f3482018-10-04 11:00:47 -07005846 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5847 if (info == null) return null;
5848 ApplicationInfo newInfo = new ApplicationInfo(info);
5849 newInfo.initForUser(userId);
5850 return newInfo;
5851 }
5852
Wale Ogunwale9c103022018-10-18 07:44:54 -07005853 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005854 if (uid == SYSTEM_UID) {
5855 // The system gets to run in any process. If there are multiple processes with the same
5856 // uid, just pick the first (this should never happen).
5857 final SparseArray<WindowProcessController> procs =
5858 mProcessNames.getMap().get(processName);
5859 if (procs == null) return null;
5860 final int procCount = procs.size();
5861 for (int i = 0; i < procCount; i++) {
5862 final int procUid = procs.keyAt(i);
5863 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5864 // Don't use an app process or different user process for system component.
5865 continue;
5866 }
5867 return procs.valueAt(i);
5868 }
5869 }
5870
5871 return mProcessNames.get(processName, uid);
5872 }
5873
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005874 WindowProcessController getProcessController(IApplicationThread thread) {
5875 if (thread == null) {
5876 return null;
5877 }
5878
5879 final IBinder threadBinder = thread.asBinder();
5880 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5881 for (int i = pmap.size()-1; i >= 0; i--) {
5882 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5883 for (int j = procs.size() - 1; j >= 0; j--) {
5884 final WindowProcessController proc = procs.valueAt(j);
5885 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5886 return proc;
5887 }
5888 }
5889 }
5890
5891 return null;
5892 }
5893
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005894 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005895 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005896 if (proc == null) return null;
5897 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5898 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005899 }
5900 return null;
5901 }
5902
Riddle Hsua0536432019-02-16 00:38:59 +08005903 int getUidState(int uid) {
5904 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005905 }
5906
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005907 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005908 // A uid is considered to be foreground if it has a visible non-toast window.
5909 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005910 }
5911
Ricky Wai96f5c352019-04-10 18:40:17 +01005912 boolean isDeviceOwner(int uid) {
5913 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005914 }
5915
Ricky Wai96f5c352019-04-10 18:40:17 +01005916 void setDeviceOwnerUid(int uid) {
5917 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005918 }
5919
Wale Ogunwale9de19442018-10-18 19:05:03 -07005920 /**
5921 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5922 * the whitelist
5923 */
5924 String getPendingTempWhitelistTagForUidLocked(int uid) {
5925 return mPendingTempWhitelist.get(uid);
5926 }
5927
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005928 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5929 if (true || Build.IS_USER) {
5930 return;
5931 }
5932
5933 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5934 StrictMode.allowThreadDiskWrites();
5935 try {
5936 File tracesDir = new File("/data/anr");
5937 File tracesFile = null;
5938 try {
5939 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5940
5941 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005942 String timeString =
5943 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5944 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005945 sb.append(": ");
5946 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5947 sb.append(" since ");
5948 sb.append(msg);
5949 FileOutputStream fos = new FileOutputStream(tracesFile);
5950 fos.write(sb.toString().getBytes());
5951 if (app == null) {
5952 fos.write("\n*** No application process!".getBytes());
5953 }
5954 fos.close();
5955 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5956 } catch (IOException e) {
5957 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5958 return;
5959 }
5960
5961 if (app != null && app.getPid() > 0) {
5962 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5963 firstPids.add(app.getPid());
5964 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5965 }
5966
5967 File lastTracesFile = null;
5968 File curTracesFile = null;
5969 for (int i=9; i>=0; i--) {
5970 String name = String.format(Locale.US, "slow%02d.txt", i);
5971 curTracesFile = new File(tracesDir, name);
5972 if (curTracesFile.exists()) {
5973 if (lastTracesFile != null) {
5974 curTracesFile.renameTo(lastTracesFile);
5975 } else {
5976 curTracesFile.delete();
5977 }
5978 }
5979 lastTracesFile = curTracesFile;
5980 }
5981 tracesFile.renameTo(curTracesFile);
5982 } finally {
5983 StrictMode.setThreadPolicy(oldPolicy);
5984 }
5985 }
5986
Michal Karpinskida34cd42019-04-02 19:46:52 +01005987 boolean isAssociatedCompanionApp(int userId, int uid) {
5988 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5989 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005990 return false;
5991 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005992 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005993 }
5994
Issei Suzuki734bc942019-06-05 13:59:52 +02005995 void notifySingleTaskDisplayEmpty(int displayId) {
5996 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
5997 }
5998
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005999 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006000 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006001
6002
Wale Ogunwale98875612018-10-12 07:53:02 -07006003 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6004 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006005
Riddle Hsud93a6c42018-11-29 21:50:06 +08006006 H(Looper looper) {
6007 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006008 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006009
6010 @Override
6011 public void handleMessage(Message msg) {
6012 switch (msg.what) {
6013 case REPORT_TIME_TRACKER_MSG: {
6014 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6015 tracker.deliverResult(mContext);
6016 } break;
6017 }
6018 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006019 }
6020
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006021 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006022 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006023
6024 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006025 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006026 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006027
6028 @Override
6029 public void handleMessage(Message msg) {
6030 switch (msg.what) {
6031 case DISMISS_DIALOG_UI_MSG: {
6032 final Dialog d = (Dialog) msg.obj;
6033 d.dismiss();
6034 break;
6035 }
6036 }
6037 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006038 }
6039
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006040 final class LocalService extends ActivityTaskManagerInternal {
6041 @Override
6042 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006043 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006044 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006045 }
6046
6047 @Override
6048 public ComponentName getHomeActivityForUser(int userId) {
6049 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006050 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006051 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006052 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006053 }
6054 }
6055
6056 @Override
6057 public void onLocalVoiceInteractionStarted(IBinder activity,
6058 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6059 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006060 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006061 }
6062 }
6063
6064 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006065 public void notifySingleTaskDisplayDrawn(int displayId) {
6066 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6067 }
6068
6069 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006070 public void notifyAppTransitionFinished() {
6071 synchronized (mGlobalLock) {
6072 mStackSupervisor.notifyAppTransitionDone();
6073 }
6074 }
6075
6076 @Override
6077 public void notifyAppTransitionCancelled() {
6078 synchronized (mGlobalLock) {
6079 mStackSupervisor.notifyAppTransitionDone();
6080 }
6081 }
6082
6083 @Override
6084 public List<IBinder> getTopVisibleActivities() {
6085 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006086 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006087 }
6088 }
6089
6090 @Override
6091 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6092 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006093 mRootWindowContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006094 }
6095 }
6096
6097 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006098 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6099 int userId, Intent[] intents, Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006100 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006101 final String[] resolvedTypes = new String[intents.length];
6102
6103 // UID of the package on user userId.
6104 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6105 // packageUid may not be initialized.
6106 int packageUid = 0;
6107 final long ident = Binder.clearCallingIdentity();
6108
6109 try {
6110 for (int i = 0; i < intents.length; i++) {
6111 resolvedTypes[i] =
6112 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6113 }
6114
6115 packageUid = AppGlobals.getPackageManager().getPackageUid(
6116 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6117 } catch (RemoteException e) {
6118 // Shouldn't happen.
6119 } finally {
6120 Binder.restoreCallingIdentity(ident);
6121 }
6122
Riddle Hsu591bf612019-02-14 17:55:31 +08006123 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006124 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006125 intents, resolvedTypes, null /* resultTo */,
6126 SafeActivityOptions.fromBundle(bOptions), userId,
6127 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6128 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006129 }
6130
6131 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006132 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006133 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6134 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6135 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006136 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006137 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006138 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006139 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006140 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6141 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006142 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006143 }
6144 }
6145
6146 @Override
6147 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006148 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6149 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6150 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6151 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006152 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006153 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006154 synchronized (mGlobalLock) {
6155 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006156 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6157 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6158 reason, validateIncomingUser, originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006159 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006160 }
6161 }
6162
6163 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006164 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006165 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6166 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006167 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006168 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006169 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006170 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006171 false /*validateIncomingUser*/);
6172 }
6173
6174 @Override
lumark588a3e82018-07-20 18:53:54 +08006175 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006176 synchronized (mGlobalLock) {
6177
6178 // We might change the visibilities here, so prepare an empty app transition which
6179 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006180 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006181 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006182 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006183 return;
6184 }
Louis Chang677921f2019-12-06 16:44:24 +08006185 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006186 final boolean wasTransitionSet =
6187 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006188 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006189 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006190 }
Louis Chang149d5c82019-12-30 09:47:39 +08006191 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006192
6193 // If there was a transition set already we don't want to interfere with it as we
6194 // might be starting it too early.
6195 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006196 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006197 }
6198 }
6199 if (callback != null) {
6200 callback.run();
6201 }
6202 }
6203
6204 @Override
6205 public void notifyKeyguardTrustedChanged() {
6206 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006207 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006208 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006209 }
6210 }
6211 }
6212
6213 /**
6214 * Called after virtual display Id is updated by
6215 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6216 * {@param vrVr2dDisplayId}.
6217 */
6218 @Override
6219 public void setVr2dDisplayId(int vr2dDisplayId) {
6220 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6221 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006222 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006223 }
6224 }
6225
6226 @Override
6227 public void setFocusedActivity(IBinder token) {
6228 synchronized (mGlobalLock) {
6229 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6230 if (r == null) {
6231 throw new IllegalArgumentException(
6232 "setFocusedActivity: No activity record matching token=" + token);
6233 }
Louis Chang19443452018-10-09 12:10:21 +08006234 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006235 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006236 }
6237 }
6238 }
6239
6240 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006241 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006242 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006243 }
6244
6245 @Override
6246 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006247 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006248 }
6249
6250 @Override
6251 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006252 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006253 }
6254
6255 @Override
6256 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6257 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6258 }
6259
6260 @Override
6261 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006262 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006263 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006264
6265 @Override
6266 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6267 synchronized (mGlobalLock) {
6268 mActiveVoiceInteractionServiceComponent = component;
6269 }
6270 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006271
6272 @Override
6273 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6274 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6275 return;
6276 }
6277 synchronized (mGlobalLock) {
6278 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6279 if (types == null) {
6280 if (uid < 0) {
6281 return;
6282 }
6283 types = new ArrayMap<>();
6284 mAllowAppSwitchUids.put(userId, types);
6285 }
6286 if (uid < 0) {
6287 types.remove(type);
6288 } else {
6289 types.put(type, uid);
6290 }
6291 }
6292 }
6293
6294 @Override
6295 public void onUserStopped(int userId) {
6296 synchronized (mGlobalLock) {
6297 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6298 mAllowAppSwitchUids.remove(userId);
6299 }
6300 }
6301
6302 @Override
6303 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6304 synchronized (mGlobalLock) {
6305 return ActivityTaskManagerService.this.isGetTasksAllowed(
6306 caller, callingPid, callingUid);
6307 }
6308 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006309
Riddle Hsua0536432019-02-16 00:38:59 +08006310 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006311 @Override
6312 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006313 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006314 mProcessNames.put(proc.mName, proc.mUid, proc);
6315 }
6316 }
6317
Riddle Hsua0536432019-02-16 00:38:59 +08006318 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006319 @Override
6320 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006321 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006322 mProcessNames.remove(name, uid);
6323 }
6324 }
6325
Riddle Hsua0536432019-02-16 00:38:59 +08006326 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006327 @Override
6328 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006329 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006330 if (proc == mHomeProcess) {
6331 mHomeProcess = null;
6332 }
6333 if (proc == mPreviousProcess) {
6334 mPreviousProcess = null;
6335 }
6336 }
6337 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006338
Riddle Hsua0536432019-02-16 00:38:59 +08006339 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006340 @Override
6341 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006342 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006343 return mTopProcessState;
6344 }
6345 }
6346
Riddle Hsua0536432019-02-16 00:38:59 +08006347 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006348 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006349 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006350 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006351 return proc == mHeavyWeightProcess;
6352 }
6353 }
6354
Riddle Hsua0536432019-02-16 00:38:59 +08006355 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006356 @Override
6357 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006358 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006359 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6360 }
6361 }
6362
6363 @Override
6364 public void finishHeavyWeightApp() {
6365 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006366 if (mHeavyWeightProcess != null) {
6367 mHeavyWeightProcess.finishActivities();
6368 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006369 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6370 mHeavyWeightProcess);
6371 }
6372 }
6373
Riddle Hsua0536432019-02-16 00:38:59 +08006374 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006375 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006376 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006377 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006378 return isSleepingLocked();
6379 }
6380 }
6381
6382 @Override
6383 public boolean isShuttingDown() {
6384 synchronized (mGlobalLock) {
6385 return mShuttingDown;
6386 }
6387 }
6388
6389 @Override
6390 public boolean shuttingDown(boolean booted, int timeout) {
6391 synchronized (mGlobalLock) {
6392 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006393 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006394 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006395 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006396 return mStackSupervisor.shutdownLocked(timeout);
6397 }
6398 }
6399
6400 @Override
6401 public void enableScreenAfterBoot(boolean booted) {
6402 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006403 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006404 mWindowManager.enableScreenAfterBoot();
6405 updateEventDispatchingLocked(booted);
6406 }
6407 }
6408
6409 @Override
6410 public boolean showStrictModeViolationDialog() {
6411 synchronized (mGlobalLock) {
6412 return mShowDialogs && !mSleeping && !mShuttingDown;
6413 }
6414 }
6415
6416 @Override
6417 public void showSystemReadyErrorDialogsIfNeeded() {
6418 synchronized (mGlobalLock) {
6419 try {
6420 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6421 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6422 + " data partition or your device will be unstable.");
6423 mUiHandler.post(() -> {
6424 if (mShowDialogs) {
6425 AlertDialog d = new BaseErrorDialog(mUiContext);
6426 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6427 d.setCancelable(false);
6428 d.setTitle(mUiContext.getText(R.string.android_system_label));
6429 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6430 d.setButton(DialogInterface.BUTTON_POSITIVE,
6431 mUiContext.getText(R.string.ok),
6432 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6433 d.show();
6434 }
6435 });
6436 }
6437 } catch (RemoteException e) {
6438 }
6439
6440 if (!Build.isBuildConsistent()) {
6441 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6442 mUiHandler.post(() -> {
6443 if (mShowDialogs) {
6444 AlertDialog d = new BaseErrorDialog(mUiContext);
6445 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6446 d.setCancelable(false);
6447 d.setTitle(mUiContext.getText(R.string.android_system_label));
6448 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6449 d.setButton(DialogInterface.BUTTON_POSITIVE,
6450 mUiContext.getText(R.string.ok),
6451 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6452 d.show();
6453 }
6454 });
6455 }
6456 }
6457 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006458
6459 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006460 public void onProcessMapped(int pid, WindowProcessController proc) {
6461 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006462 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006463 }
6464 }
6465
6466 @Override
6467 public void onProcessUnMapped(int pid) {
6468 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006469 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006470 }
6471 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006472
6473 @Override
6474 public void onPackageDataCleared(String name) {
6475 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006476 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006477 mAppWarnings.onPackageDataCleared(name);
6478 }
6479 }
6480
6481 @Override
6482 public void onPackageUninstalled(String name) {
6483 synchronized (mGlobalLock) {
6484 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006485 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006486 }
6487 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006488
6489 @Override
6490 public void onPackageAdded(String name, boolean replacing) {
6491 synchronized (mGlobalLock) {
6492 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6493 }
6494 }
6495
6496 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006497 public void onPackageReplaced(ApplicationInfo aInfo) {
6498 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006499 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006500 }
6501 }
6502
6503 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006504 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6505 synchronized (mGlobalLock) {
6506 return compatibilityInfoForPackageLocked(ai);
6507 }
6508 }
6509
Yunfan Chen75157d72018-07-27 14:47:21 +09006510 /**
6511 * Set the corresponding display information for the process global configuration. To be
6512 * called when we need to show IME on a different display.
6513 *
6514 * @param pid The process id associated with the IME window.
6515 * @param displayId The ID of the display showing the IME.
6516 */
6517 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006518 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006519 // Don't update process-level configuration for Multi-Client IME process since other
6520 // IMEs on other displays will also receive this configuration change due to IME
6521 // services use the same application config/context.
6522 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006523
Yunfan Chen75157d72018-07-27 14:47:21 +09006524 if (pid == MY_PID || pid < 0) {
6525 if (DEBUG_CONFIGURATION) {
6526 Slog.w(TAG,
6527 "Trying to update display configuration for system/invalid process.");
6528 }
6529 return;
6530 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006531 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006532 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006533 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006534 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006535 // Call might come when display is not yet added or has been removed.
6536 if (DEBUG_CONFIGURATION) {
6537 Slog.w(TAG, "Trying to update display configuration for non-existing "
6538 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006539 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006540 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006541 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006542 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006543 if (process == null) {
6544 if (DEBUG_CONFIGURATION) {
6545 Slog.w(TAG, "Trying to update display configuration for invalid "
6546 + "process, pid=" + pid);
6547 }
6548 return;
6549 }
lumarkddc77fb2019-06-27 22:22:23 +08006550 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006551 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006552 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006553 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006554
6555 @Override
6556 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006557 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006558 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006559 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006560 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006561 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006562 }
6563 }
6564 }
6565
6566 @Override
6567 public void clearPendingResultForActivity(IBinder activityToken,
6568 WeakReference<PendingIntentRecord> pir) {
6569 synchronized (mGlobalLock) {
6570 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6571 if (r != null && r.pendingResults != null) {
6572 r.pendingResults.remove(pir);
6573 }
6574 }
6575 }
6576
6577 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006578 public ActivityTokens getTopActivityForTask(int taskId) {
6579 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006580 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006581 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006582 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6583 + " Requested task not found");
6584 return null;
6585 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006586 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006587 if (activity == null) {
6588 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6589 + " Requested activity not found");
6590 return null;
6591 }
6592 if (!activity.attachedToProcess()) {
6593 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6594 + activity);
6595 return null;
6596 }
6597 return new ActivityTokens(activity.appToken, activity.assistToken,
6598 activity.app.getThread());
6599 }
6600 }
6601
6602 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006603 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006604 @Nullable String featureId, int callingUid, int userId, IBinder token,
6605 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6606 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006607 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006608 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6609 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006610 }
6611 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006612
6613 @Override
6614 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6615 synchronized (mGlobalLock) {
6616 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6617 if (r == null) {
6618 return null;
6619 }
6620 if (r.mServiceConnectionsHolder == null) {
6621 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6622 ActivityTaskManagerService.this, r);
6623 }
6624
6625 return r.mServiceConnectionsHolder;
6626 }
6627 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006628
6629 @Override
6630 public Intent getHomeIntent() {
6631 synchronized (mGlobalLock) {
6632 return ActivityTaskManagerService.this.getHomeIntent();
6633 }
6634 }
6635
6636 @Override
6637 public boolean startHomeActivity(int userId, String reason) {
6638 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006639 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006640 }
6641 }
6642
6643 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006644 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006645 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006646 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006647 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006648 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006649 }
Chilun8b1f1be2019-03-13 17:14:36 +08006650 }
6651
6652 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006653 public boolean startHomeOnAllDisplays(int userId, String reason) {
6654 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006655 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006656 }
6657 }
6658
Riddle Hsua0536432019-02-16 00:38:59 +08006659 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006660 @Override
6661 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006662 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006663 if (mFactoryTest == FACTORY_TEST_OFF) {
6664 return false;
6665 }
6666 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6667 && wpc.mName.equals(mTopComponent.getPackageName())) {
6668 return true;
6669 }
6670 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6671 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6672 }
6673 }
6674
6675 @Override
6676 public void updateTopComponentForFactoryTest() {
6677 synchronized (mGlobalLock) {
6678 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6679 return;
6680 }
6681 final ResolveInfo ri = mContext.getPackageManager()
6682 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6683 final CharSequence errorMsg;
6684 if (ri != null) {
6685 final ActivityInfo ai = ri.activityInfo;
6686 final ApplicationInfo app = ai.applicationInfo;
6687 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6688 mTopAction = Intent.ACTION_FACTORY_TEST;
6689 mTopData = null;
6690 mTopComponent = new ComponentName(app.packageName, ai.name);
6691 errorMsg = null;
6692 } else {
6693 errorMsg = mContext.getResources().getText(
6694 com.android.internal.R.string.factorytest_not_system);
6695 }
6696 } else {
6697 errorMsg = mContext.getResources().getText(
6698 com.android.internal.R.string.factorytest_no_action);
6699 }
6700 if (errorMsg == null) {
6701 return;
6702 }
6703
6704 mTopAction = null;
6705 mTopData = null;
6706 mTopComponent = null;
6707 mUiHandler.post(() -> {
6708 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6709 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006710 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006711 });
6712 }
6713 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006714
Riddle Hsua0536432019-02-16 00:38:59 +08006715 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006716 @Override
6717 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6718 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006719 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006720 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006721 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006722
6723 wpc.clearRecentTasks();
6724 wpc.clearActivities();
6725
6726 if (wpc.isInstrumenting()) {
6727 finishInstrumentationCallback.run();
6728 }
6729
Jorim Jaggid0752812018-10-16 16:07:20 +02006730 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006731 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006732 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006733 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006734 // If there was nothing to resume, and we are not already restarting
6735 // this process, but there is a visible activity that is hosted by the
6736 // process...then make sure all visible activities are running, taking
6737 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006738 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006739 !PRESERVE_WINDOWS);
6740 }
6741 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006742 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006743 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006744 }
6745 }
6746 }
6747
6748 @Override
6749 public void closeSystemDialogs(String reason) {
6750 enforceNotIsolatedCaller("closeSystemDialogs");
6751
6752 final int pid = Binder.getCallingPid();
6753 final int uid = Binder.getCallingUid();
6754 final long origId = Binder.clearCallingIdentity();
6755 try {
6756 synchronized (mGlobalLock) {
6757 // Only allow this from foreground processes, so that background
6758 // applications can't abuse it to prevent system UI from being shown.
6759 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006760 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006761 if (!proc.isPerceptible()) {
6762 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6763 + " from background process " + proc);
6764 return;
6765 }
6766 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006767 mWindowManager.closeSystemDialogs(reason);
6768
Louis Chang149d5c82019-12-30 09:47:39 +08006769 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006770 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006771 // Call into AM outside the synchronized block.
6772 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006773 } finally {
6774 Binder.restoreCallingIdentity(origId);
6775 }
6776 }
6777
6778 @Override
6779 public void cleanupDisabledPackageComponents(
6780 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6781 synchronized (mGlobalLock) {
6782 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006783 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006784 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006785 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006786 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006787 }
6788
6789 // Clean-up disabled tasks
6790 getRecentTasks().cleanupDisabledPackageTasksLocked(
6791 packageName, disabledClasses, userId);
6792 }
6793 }
6794
6795 @Override
6796 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6797 int userId) {
6798 synchronized (mGlobalLock) {
6799
6800 boolean didSomething =
6801 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006802 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006803 null, doit, evenPersistent, userId);
6804 return didSomething;
6805 }
6806 }
6807
6808 @Override
6809 public void resumeTopActivities(boolean scheduleIdle) {
6810 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006811 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006812 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006813 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006814 }
6815 }
6816 }
6817
Riddle Hsua0536432019-02-16 00:38:59 +08006818 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006819 @Override
6820 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006821 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006822 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6823 }
6824 }
6825
Riddle Hsua0536432019-02-16 00:38:59 +08006826 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006827 @Override
6828 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006829 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006830 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6831 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6832 }
6833 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006834 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006835 } finally {
6836 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6837 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006838 }
6839 }
6840
6841 @Override
6842 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6843 try {
6844 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6845 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6846 }
6847 } catch (RemoteException ex) {
6848 throw new SecurityException("Fail to check is caller a privileged app", ex);
6849 }
6850
6851 synchronized (mGlobalLock) {
6852 final long ident = Binder.clearCallingIdentity();
6853 try {
6854 if (mAmInternal.shouldConfirmCredentials(userId)) {
6855 if (mKeyguardController.isKeyguardLocked()) {
6856 // Showing launcher to avoid user entering credential twice.
6857 startHomeActivity(currentUserId, "notifyLockedProfile");
6858 }
Louis Chang149d5c82019-12-30 09:47:39 +08006859 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006860 }
6861 } finally {
6862 Binder.restoreCallingIdentity(ident);
6863 }
6864 }
6865 }
6866
6867 @Override
6868 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6869 mAmInternal.enforceCallingPermission(
6870 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6871
6872 synchronized (mGlobalLock) {
6873 final long ident = Binder.clearCallingIdentity();
6874 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006875 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6876 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006877 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006878 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6879 UserHandle.CURRENT);
6880 } finally {
6881 Binder.restoreCallingIdentity(ident);
6882 }
6883 }
6884 }
6885
6886 @Override
6887 public void writeActivitiesToProto(ProtoOutputStream proto) {
6888 synchronized (mGlobalLock) {
6889 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006890 mRootWindowContainer.dumpDebug(
6891 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006892 }
6893 }
6894
6895 @Override
6896 public void saveANRState(String reason) {
6897 synchronized (mGlobalLock) {
6898 final StringWriter sw = new StringWriter();
6899 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6900 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6901 if (reason != null) {
6902 pw.println(" Reason: " + reason);
6903 }
6904 pw.println();
6905 getActivityStartController().dump(pw, " ", null);
6906 pw.println();
6907 pw.println("-------------------------------------------------------------------------------");
6908 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6909 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6910 "" /* header */);
6911 pw.println();
6912 pw.close();
6913
6914 mLastANRState = sw.toString();
6915 }
6916 }
6917
6918 @Override
6919 public void clearSavedANRState() {
6920 synchronized (mGlobalLock) {
6921 mLastANRState = null;
6922 }
6923 }
6924
6925 @Override
6926 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6927 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6928 synchronized (mGlobalLock) {
6929 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6930 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6931 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6932 dumpLastANRLocked(pw);
6933 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6934 dumpLastANRTracesLocked(pw);
6935 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6936 dumpActivityStarterLocked(pw, dumpPackage);
6937 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6938 dumpActivityContainersLocked(pw);
6939 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6940 if (getRecentTasks() != null) {
6941 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6942 }
6943 }
6944 }
6945 }
6946
6947 @Override
6948 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6949 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6950 int wakefulness) {
6951 synchronized (mGlobalLock) {
6952 if (mHomeProcess != null && (dumpPackage == null
6953 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6954 if (needSep) {
6955 pw.println();
6956 needSep = false;
6957 }
6958 pw.println(" mHomeProcess: " + mHomeProcess);
6959 }
6960 if (mPreviousProcess != null && (dumpPackage == null
6961 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6962 if (needSep) {
6963 pw.println();
6964 needSep = false;
6965 }
6966 pw.println(" mPreviousProcess: " + mPreviousProcess);
6967 }
6968 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6969 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6970 StringBuilder sb = new StringBuilder(128);
6971 sb.append(" mPreviousProcessVisibleTime: ");
6972 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6973 pw.println(sb);
6974 }
6975 if (mHeavyWeightProcess != null && (dumpPackage == null
6976 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6977 if (needSep) {
6978 pw.println();
6979 needSep = false;
6980 }
6981 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6982 }
6983 if (dumpPackage == null) {
6984 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08006985 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006986 }
6987 if (dumpAll) {
6988 if (dumpPackage == null) {
6989 pw.println(" mConfigWillChange: "
6990 + getTopDisplayFocusedStack().mConfigWillChange);
6991 }
6992 if (mCompatModePackages.getPackages().size() > 0) {
6993 boolean printed = false;
6994 for (Map.Entry<String, Integer> entry
6995 : mCompatModePackages.getPackages().entrySet()) {
6996 String pkg = entry.getKey();
6997 int mode = entry.getValue();
6998 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6999 continue;
7000 }
7001 if (!printed) {
7002 pw.println(" mScreenCompatPackages:");
7003 printed = true;
7004 }
7005 pw.println(" " + pkg + ": " + mode);
7006 }
7007 }
7008 }
7009
7010 if (dumpPackage == null) {
7011 pw.println(" mWakefulness="
7012 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007013 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007014 if (mRunningVoice != null) {
7015 pw.println(" mRunningVoice=" + mRunningVoice);
7016 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7017 }
7018 pw.println(" mSleeping=" + mSleeping);
7019 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7020 pw.println(" mVrController=" + mVrController);
7021 }
7022 if (mCurAppTimeTracker != null) {
7023 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7024 }
7025 if (mAllowAppSwitchUids.size() > 0) {
7026 boolean printed = false;
7027 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7028 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7029 for (int j = 0; j < types.size(); j++) {
7030 if (dumpPackage == null ||
7031 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7032 if (needSep) {
7033 pw.println();
7034 needSep = false;
7035 }
7036 if (!printed) {
7037 pw.println(" mAllowAppSwitchUids:");
7038 printed = true;
7039 }
7040 pw.print(" User ");
7041 pw.print(mAllowAppSwitchUids.keyAt(i));
7042 pw.print(": Type ");
7043 pw.print(types.keyAt(j));
7044 pw.print(" = ");
7045 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7046 pw.println();
7047 }
7048 }
7049 }
7050 }
7051 if (dumpPackage == null) {
7052 if (mController != null) {
7053 pw.println(" mController=" + mController
7054 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7055 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007056 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7057 pw.println(" mLaunchingActivityWakeLock="
7058 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007059 }
7060
7061 return needSep;
7062 }
7063 }
7064
7065 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007066 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7067 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007068 synchronized (mGlobalLock) {
7069 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007070 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007071 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007072 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7073 if (mRunningVoice != null) {
7074 final long vrToken = proto.start(
7075 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7076 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7077 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007078 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007079 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7080 proto.end(vrToken);
7081 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007082 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007083 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007084 if (mController != null) {
7085 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007086 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7087 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007088 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7089 proto.end(token);
7090 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007091 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7092 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007093 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007094 }
7095
7096 if (mHomeProcess != null && (dumpPackage == null
7097 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007098 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007099 }
7100
7101 if (mPreviousProcess != null && (dumpPackage == null
7102 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007103 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007104 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7105 }
7106
7107 if (mHeavyWeightProcess != null && (dumpPackage == null
7108 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007109 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007110 }
7111
7112 for (Map.Entry<String, Integer> entry
7113 : mCompatModePackages.getPackages().entrySet()) {
7114 String pkg = entry.getKey();
7115 int mode = entry.getValue();
7116 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7117 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7118 proto.write(PACKAGE, pkg);
7119 proto.write(MODE, mode);
7120 proto.end(compatToken);
7121 }
7122 }
7123
7124 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007125 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007126 }
7127
7128 }
7129 }
7130
7131 @Override
7132 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7133 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7134 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007135 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7136 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007137 }
7138
7139 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007140 public void dumpForOom(PrintWriter pw) {
7141 synchronized (mGlobalLock) {
7142 pw.println(" mHomeProcess: " + mHomeProcess);
7143 pw.println(" mPreviousProcess: " + mPreviousProcess);
7144 if (mHeavyWeightProcess != null) {
7145 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7146 }
7147 }
7148 }
7149
7150 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007151 public boolean canGcNow() {
7152 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007153 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007154 }
7155 }
7156
Riddle Hsua0536432019-02-16 00:38:59 +08007157 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007158 @Override
7159 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007160 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007161 if (mRootWindowContainer == null) {
7162 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007163 // oomadj after AMS created.
7164 return null;
7165 }
Louis Chang149d5c82019-12-30 09:47:39 +08007166 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007167 return top != null ? top.app : null;
7168 }
7169 }
7170
Riddle Hsua0536432019-02-16 00:38:59 +08007171 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007172 @Override
7173 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007174 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007175 if (mRootWindowContainer != null) {
7176 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007177 }
7178 }
7179 }
7180
7181 @Override
7182 public void scheduleDestroyAllActivities(String reason) {
7183 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007184 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007185 }
7186 }
7187
7188 @Override
7189 public void removeUser(int userId) {
7190 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007191 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007192 }
7193 }
7194
7195 @Override
7196 public boolean switchUser(int userId, UserState userState) {
7197 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007198 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007199 }
7200 }
7201
7202 @Override
7203 public void onHandleAppCrash(WindowProcessController wpc) {
7204 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007205 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007206 }
7207 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007208
7209 @Override
7210 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7211 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007212 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007213 }
7214 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007215
Riddle Hsua0536432019-02-16 00:38:59 +08007216 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007217 @Override
7218 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007219 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007220 }
7221
Riddle Hsua0536432019-02-16 00:38:59 +08007222 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007223 @Override
7224 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007225 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007226 }
7227
Riddle Hsua0536432019-02-16 00:38:59 +08007228 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007229 @Override
7230 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007231 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007232 }
7233
Riddle Hsua0536432019-02-16 00:38:59 +08007234 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007235 @Override
7236 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007237 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007238 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007239
7240 @Override
7241 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007242 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007243 mPendingTempWhitelist.put(uid, tag);
7244 }
7245 }
7246
7247 @Override
7248 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007249 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007250 mPendingTempWhitelist.remove(uid);
7251 }
7252 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007253
7254 @Override
7255 public boolean handleAppCrashInActivityController(String processName, int pid,
7256 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7257 Runnable killCrashingAppCallback) {
7258 synchronized (mGlobalLock) {
7259 if (mController == null) {
7260 return false;
7261 }
7262
7263 try {
7264 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7265 stackTrace)) {
7266 killCrashingAppCallback.run();
7267 return true;
7268 }
7269 } catch (RemoteException e) {
7270 mController = null;
7271 Watchdog.getInstance().setActivityController(null);
7272 }
7273 return false;
7274 }
7275 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007276
7277 @Override
7278 public void removeRecentTasksByPackageName(String packageName, int userId) {
7279 synchronized (mGlobalLock) {
7280 mRecentTasks.removeTasksByPackageName(packageName, userId);
7281 }
7282 }
7283
7284 @Override
7285 public void cleanupRecentTasksForUser(int userId) {
7286 synchronized (mGlobalLock) {
7287 mRecentTasks.cleanupLocked(userId);
7288 }
7289 }
7290
7291 @Override
7292 public void loadRecentTasksForUser(int userId) {
7293 synchronized (mGlobalLock) {
7294 mRecentTasks.loadUserRecentsLocked(userId);
7295 }
7296 }
7297
7298 @Override
7299 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7300 synchronized (mGlobalLock) {
7301 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7302 }
7303 }
7304
7305 @Override
7306 public void flushRecentTasks() {
7307 mRecentTasks.flush();
7308 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007309
7310 @Override
7311 public WindowProcessController getHomeProcess() {
7312 synchronized (mGlobalLock) {
7313 return mHomeProcess;
7314 }
7315 }
7316
7317 @Override
7318 public WindowProcessController getPreviousProcess() {
7319 synchronized (mGlobalLock) {
7320 return mPreviousProcess;
7321 }
7322 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007323
7324 @Override
7325 public void clearLockedTasks(String reason) {
7326 synchronized (mGlobalLock) {
7327 getLockTaskController().clearLockedTasks(reason);
7328 }
7329 }
7330
7331 @Override
7332 public void updateUserConfiguration() {
7333 synchronized (mGlobalLock) {
7334 final Configuration configuration = new Configuration(getGlobalConfiguration());
7335 final int currentUserId = mAmInternal.getCurrentUserId();
7336 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7337 configuration, currentUserId, Settings.System.canWrite(mContext));
7338 updateConfigurationLocked(configuration, null /* starting */,
7339 false /* initLocale */, false /* persistent */, currentUserId,
7340 false /* deferResume */);
7341 }
7342 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007343
7344 @Override
7345 public boolean canShowErrorDialogs() {
7346 synchronized (mGlobalLock) {
7347 return mShowDialogs && !mSleeping && !mShuttingDown
7348 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7349 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7350 mAmInternal.getCurrentUserId())
7351 && !(UserManager.isDeviceInDemoMode(mContext)
7352 && mAmInternal.getCurrentUser().isDemo());
7353 }
7354 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007355
7356 @Override
7357 public void setProfileApp(String profileApp) {
7358 synchronized (mGlobalLock) {
7359 mProfileApp = profileApp;
7360 }
7361 }
7362
7363 @Override
7364 public void setProfileProc(WindowProcessController wpc) {
7365 synchronized (mGlobalLock) {
7366 mProfileProc = wpc;
7367 }
7368 }
7369
7370 @Override
7371 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7372 synchronized (mGlobalLock) {
7373 mProfilerInfo = profilerInfo;
7374 }
7375 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007376
7377 @Override
7378 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7379 synchronized (mGlobalLock) {
7380 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7381 }
7382 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007383
7384 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007385 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
Peter Kalauskas4dc04602020-02-12 18:49:03 -08007386 boolean isLowResolution) {
7387 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007388 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007389 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007390
7391 @Override
7392 public boolean isUidForeground(int uid) {
7393 synchronized (mGlobalLock) {
7394 return ActivityTaskManagerService.this.isUidForeground(uid);
7395 }
7396 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007397
7398 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007399 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007400 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007401 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007402 }
7403 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007404
7405 @Override
7406 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007407 // Translate package names into UIDs
7408 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007409 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007410 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7411 if (uid >= 0) {
7412 result.add(uid);
7413 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007414 }
7415 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007416 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007417 }
7418 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007419 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007420}