blob: 911812bc741037dabc3031f6535d69febf497324 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Jonathan Scott92335342019-12-17 14:46:26 +000031import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070035import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
36import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070037import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
38import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Evan Rosky73a7fe92019-11-18 18:28:01 -080039import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070041import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070042import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070043import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070044import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070045import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
46import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070047import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070048import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070049import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
50import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070052import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070053import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080054import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070055import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070059import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
60import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070061import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040062import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.view.Display.DEFAULT_DISPLAY;
64import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070065import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070066
Yunfan Chen79b96062018-10-17 12:45:23 -070067import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
68import static com.android.server.am.ActivityManagerService.MY_PID;
69import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
70import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwalef342f062020-01-27 07:34:13 -080071import static com.android.server.am.ActivityManagerServiceDumpActivitiesProto.ROOT_WINDOW_CONTAINER;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Jeff Changd136e772019-11-05 20:33:52 +080086import static com.android.server.am.EventLogTags.writeBootProgressEnableScreen;
87import static com.android.server.am.EventLogTags.writeConfigurationChanged;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070088import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
89import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Louis Chang149d5c82019-12-30 09:47:39 +0800120import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
Louis Changcdec0802019-11-11 11:45:07 +0800122import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800127import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700128import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.annotation.Nullable;
130import android.annotation.UserIdInt;
131import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700132import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700133import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.ActivityOptions;
135import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700136import android.app.ActivityThread;
137import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700138import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100139import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700140import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700141import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700142import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.IApplicationThread;
144import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400146import android.app.IRequestFinishCallback;
Evan Rosky0037e5f2019-11-05 10:26:24 -0800147import android.app.ITaskOrganizerController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700149import android.app.Notification;
150import android.app.NotificationManager;
151import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700152import android.app.PictureInPictureParams;
153import android.app.ProfilerInfo;
154import android.app.RemoteAction;
155import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700156import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.app.admin.DevicePolicyCache;
158import android.app.assist.AssistContent;
159import android.app.assist.AssistStructure;
jorgegil@google.com06bc3232019-10-31 14:51:22 -0700160import android.app.servertransaction.ClientTransaction;
161import android.app.servertransaction.EnterPipRequestedItem;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700162import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700163import android.content.ActivityNotFoundException;
164import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700166import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.IIntentSender;
169import android.content.Intent;
170import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700171import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900172import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700173import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700174import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.content.pm.ParceledListSlice;
177import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700178import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700180import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700181import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.graphics.Bitmap;
183import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700184import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700185import android.metrics.LogMaker;
186import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700187import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700189import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700190import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700191import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700192import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700193import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700194import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700195import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800196import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700197import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700200import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100201import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700204import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700205import android.os.SystemClock;
206import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700207import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700208import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700210import android.os.UserManager;
211import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700212import android.os.storage.IStorageManager;
213import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700214import android.provider.Settings;
Galia Peycheva6861e912019-08-21 10:20:23 +0200215import android.service.dreams.DreamActivity;
Galia Peycheva52e89222020-02-18 23:41:43 +0100216import android.service.dreams.DreamManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700217import android.service.voice.IVoiceInteractionSession;
218import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900219import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700220import android.telecom.TelecomManager;
221import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100222import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700223import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700224import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700225import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700226import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700227import android.util.SparseArray;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700228import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700229import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700230import android.view.IRecentsAnimationRunner;
231import android.view.RemoteAnimationAdapter;
232import android.view.RemoteAnimationDefinition;
Evan Roskyaf9f27c2020-02-18 18:58:35 +0000233import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700234import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700235
Evan Rosky4505b352018-09-06 11:20:40 -0700236import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700237import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.app.AssistUtils;
239import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700240import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700243import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
244import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700245import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700246import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700247import com.android.internal.policy.IKeyguardDismissCallback;
248import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700249import com.android.internal.util.ArrayUtils;
250import com.android.internal.util.FastPrintWriter;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800251import com.android.internal.util.FrameworkStatsLog;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800252import com.android.internal.util.function.pooled.PooledConsumer;
253import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700254import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700255import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700256import com.android.server.LocalServices;
257import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700258import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800259import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700260import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700261import com.android.server.am.ActivityManagerService;
Wale Ogunwale59507092018-10-29 09:00:30 -0700262import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
263import com.android.server.am.AppTimeTracker;
264import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700265import com.android.server.am.PendingIntentController;
266import com.android.server.am.PendingIntentRecord;
267import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700268import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700269import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700270import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800271import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700272import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700276import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700278import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700280import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700281import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700282import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800283import java.lang.annotation.ElementType;
284import java.lang.annotation.Retention;
285import java.lang.annotation.RetentionPolicy;
286import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700287import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700288import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700290import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700291import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400292import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700293import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700295import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700296import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000297import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700298import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700299
300/**
301 * System service for managing activities and their containers (task, stacks, displays,... ).
302 *
303 * {@hide}
304 */
305public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700306 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800307 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000308 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700309 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
310 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
311 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
312 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700313 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700314
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700316 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700318 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100319 // How long we permit background activity starts after an activity in the process
320 // started or finished.
321 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700322
Wale Ogunwale98875612018-10-12 07:53:02 -0700323 /** Used to indicate that an app transition should be animated. */
324 static final boolean ANIMATE = true;
325
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700326 /** Hardware-reported OpenGLES version. */
327 final int GL_ES_VERSION;
328
Wale Ogunwale31913b52018-10-13 08:29:31 -0700329 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
330 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
331 public static final String DUMP_LASTANR_CMD = "lastanr" ;
332 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
333 public static final String DUMP_STARTER_CMD = "starter" ;
334 public static final String DUMP_CONTAINERS_CMD = "containers" ;
335 public static final String DUMP_RECENTS_CMD = "recents" ;
336 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
337
Wale Ogunwale64258362018-10-16 15:13:37 -0700338 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
339 public static final int RELAUNCH_REASON_NONE = 0;
340 /** This activity is being relaunched due to windowing mode change. */
341 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
342 /** This activity is being relaunched due to a free-resize operation. */
343 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
344
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700345 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700346
Wale Ogunwalef6733932018-06-27 05:14:34 -0700347 /**
348 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
349 * change at runtime. Use mContext for non-UI purposes.
350 */
351 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700352 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700353 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700354 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700355 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700356 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700357 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800358 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800359 @VisibleForTesting
360 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700361 PowerManagerInternal mPowerManagerInternal;
362 private UsageStatsManagerInternal mUsageStatsInternal;
363
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700364 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700365 IntentFirewall mIntentFirewall;
366
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700367 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800368 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800369 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700370 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800371 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
372 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
373 *
374 * @see WindowManagerThreadPriorityBooster
375 */
376 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700377 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800378 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700379 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700380 private UserManagerService mUserManager;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800381 private AppOpsManager mAppOpsManager;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700382 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800383 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700384 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700385 /** All processes currently running that might have a window organized by name. */
386 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100387 /** All processes we currently have running mapped by pid and uid */
388 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700389 /** This is the process holding what we currently consider to be the "home" activity. */
390 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700391 /** The currently running heavy-weight process, if any. */
392 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700393 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700394 /**
395 * This is the process holding the activity the user last visited that is in a different process
396 * from the one they are currently in.
397 */
398 WindowProcessController mPreviousProcess;
399 /** The time at which the previous process was last visible. */
400 long mPreviousProcessVisibleTime;
401
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700402 /** List of intents that were used to start the most recent tasks. */
403 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700404 /** State of external calls telling us if the device is awake or asleep. */
405 private boolean mKeyguardShown = false;
406
407 // Wrapper around VoiceInteractionServiceManager
408 private AssistUtils mAssistUtils;
409
410 // VoiceInteraction session ID that changes for each new request except when
411 // being called for multi-window assist in a single session.
412 private int mViSessionId = 1000;
413
414 // How long to wait in getAssistContextExtras for the activity and foreground services
415 // to respond with the result.
416 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
417
418 // How long top wait when going through the modern assist (which doesn't need to block
419 // on getting this result before starting to launch its UI).
420 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
421
422 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
423 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
424
Alison Cichowlas3e340502018-08-07 17:15:01 -0400425 // Permission tokens are used to temporarily granted a trusted app the ability to call
426 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
427 // showing any appropriate error messages to the user.
428 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
429 10 * MINUTE_IN_MILLIS;
430
431 // How long before the service actually expires a token. This is slightly longer than
432 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
433 // expiration exception.
434 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
435 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
436
437 // How long the service will remember expired tokens, for the purpose of providing error
438 // messaging when a client uses an expired token.
439 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
440 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
441
442 // Activity tokens of system activities that are delegating their call to
443 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
444 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
445
446 // Permission tokens that have expired, but we remember for error reporting.
447 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
448
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700449 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
450
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700451 // Keeps track of the active voice interaction service component, notified from
452 // VoiceInteractionManagerService
453 ComponentName mActiveVoiceInteractionServiceComponent;
454
Michal Karpinskida34cd42019-04-02 19:46:52 +0100455 // A map userId and all its companion app uids
456 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000457
Wale Ogunwalee2172292018-10-25 10:11:10 -0700458 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700459 KeyguardController mKeyguardController;
460 private final ClientLifecycleManager mLifecycleManager;
461 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700462 /** The controller for all operations related to locktask. */
463 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700464 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700465
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700466 boolean mSuppressResizeConfigChanges;
467
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700468 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700469 new UpdateConfigurationResult();
470
471 static final class UpdateConfigurationResult {
472 // Configuration changes that were updated.
473 int changes;
474 // If the activity was relaunched to match the new configuration.
475 boolean activityRelaunched;
476
477 void reset() {
478 changes = 0;
479 activityRelaunched = false;
480 }
481 }
482
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700483 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700484 private int mConfigurationSeq;
485 // To cache the list of supported system locales
486 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700487
488 /**
489 * Temp object used when global and/or display override configuration is updated. It is also
490 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
491 * anyone...
492 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700493 private Configuration mTempConfig = new Configuration();
494
Wale Ogunwalef6733932018-06-27 05:14:34 -0700495 /** Temporary to avoid allocations. */
496 final StringBuilder mStringBuilder = new StringBuilder(256);
497
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700498 // Amount of time after a call to stopAppSwitches() during which we will
499 // prevent further untrusted switches from happening.
500 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
501
502 /**
503 * The time at which we will allow normal application switches again,
504 * after a call to {@link #stopAppSwitches()}.
505 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700506 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700507 /**
508 * This is set to true after the first switch after mAppSwitchesAllowedTime
509 * is set; any switches after that will clear the time.
510 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700511 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700512
Ricky Wai906af482019-06-03 17:25:28 +0100513 /**
514 * Last stop app switches time, apps finished before this time cannot start background activity
515 * even if they are in grace period.
516 */
517 private long mLastStopAppSwitchesTime;
518
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700519 IActivityController mController = null;
520 boolean mControllerIsAMonkey = false;
521
Wale Ogunwale214f3482018-10-04 11:00:47 -0700522 final int mFactoryTest;
523
524 /** Used to control how we initialize the service. */
525 ComponentName mTopComponent;
526 String mTopAction = Intent.ACTION_MAIN;
527 String mTopData;
528
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800529 /** Profiling app information. */
530 String mProfileApp = null;
531 WindowProcessController mProfileProc = null;
532 ProfilerInfo mProfilerInfo = null;
533
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700534 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700535 * Dump of the activity state at the time of the last ANR. Cleared after
536 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
537 */
538 String mLastANRState;
539
540 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700541 * Used to retain an update lock when the foreground activity is in
542 * immersive mode.
543 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700544 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700545
546 /**
547 * Packages that are being allowed to perform unrestricted app switches. Mapping is
548 * User -> Type -> uid.
549 */
550 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
551
552 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700553 private int mThumbnailWidth;
554 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700555
556 /**
557 * Flag that indicates if multi-window is enabled.
558 *
559 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
560 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
561 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
562 * At least one of the forms of multi-window must be enabled in order for this flag to be
563 * initialized to 'true'.
564 *
565 * @see #mSupportsSplitScreenMultiWindow
566 * @see #mSupportsFreeformWindowManagement
567 * @see #mSupportsPictureInPicture
568 * @see #mSupportsMultiDisplay
569 */
570 boolean mSupportsMultiWindow;
571 boolean mSupportsSplitScreenMultiWindow;
572 boolean mSupportsFreeformWindowManagement;
573 boolean mSupportsPictureInPicture;
574 boolean mSupportsMultiDisplay;
575 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700576 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700577
578 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
579
580 // VR Vr2d Display Id.
581 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700582
Wale Ogunwalef6733932018-06-27 05:14:34 -0700583 /**
584 * Set while we are wanting to sleep, to prevent any
585 * activities from being started/resumed.
586 *
587 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
588 *
589 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
590 * while in the sleep state until there is a pending transition out of sleep, in which case
591 * mSleeping is set to false, and remains false while awake.
592 *
593 * Whether mSleeping can quickly toggled between true/false without the device actually
594 * display changing states is undefined.
595 */
596 private boolean mSleeping = false;
597
598 /**
599 * The process state used for processes that are running the top activities.
600 * This changes between TOP and TOP_SLEEPING to following mSleeping.
601 */
602 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
603
Riddle Hsua0022cd2019-09-09 21:12:41 +0800604 @Retention(RetentionPolicy.SOURCE)
605 @IntDef({
606 LAYOUT_REASON_CONFIG_CHANGED,
607 LAYOUT_REASON_VISIBILITY_CHANGED,
608 })
609 @interface LayoutReason {}
610 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
611 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
612
613 /** The reasons to perform surface placement. */
614 @LayoutReason
615 private int mLayoutReasons;
616
Wale Ogunwalef6733932018-06-27 05:14:34 -0700617 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
618 // automatically. Important for devices without direct input devices.
619 private boolean mShowDialogs = true;
620
621 /** Set if we are shutting down the system, similar to sleeping. */
622 boolean mShuttingDown = false;
623
624 /**
625 * We want to hold a wake lock while running a voice interaction session, since
626 * this may happen with the screen off and we need to keep the CPU running to
627 * be able to continue to interact with the user.
628 */
629 PowerManager.WakeLock mVoiceWakeLock;
630
631 /**
632 * Set while we are running a voice interaction. This overrides sleeping while it is active.
633 */
634 IVoiceInteractionSession mRunningVoice;
635
636 /**
637 * The last resumed activity. This is identical to the current resumed activity most
638 * of the time but could be different when we're pausing one activity before we resume
639 * another activity.
640 */
641 ActivityRecord mLastResumedActivity;
642
643 /**
644 * The activity that is currently being traced as the active resumed activity.
645 *
646 * @see #updateResumedAppTrace
647 */
648 private @Nullable ActivityRecord mTracedResumedActivity;
649
650 /** If non-null, we are tracking the time the user spends in the currently focused app. */
651 AppTimeTracker mCurAppTimeTracker;
652
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700653 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700654
Wale Ogunwale53783742018-09-16 10:21:51 -0700655 /**
656 * Packages that the user has asked to have run in screen size
657 * compatibility mode instead of filling the screen.
658 */
659 CompatModePackages mCompatModePackages;
660
Wale Ogunwalef6733932018-06-27 05:14:34 -0700661 private FontScaleSettingObserver mFontScaleSettingObserver;
662
Robert Carr8a2f9132019-11-11 15:03:15 -0800663 /**
664 * Stores the registration and state of TaskOrganizers in use.
665 */
Evan Rosky0037e5f2019-11-05 10:26:24 -0800666 TaskOrganizerController mTaskOrganizerController = new TaskOrganizerController(this);
Robert Carr8a2f9132019-11-11 15:03:15 -0800667
Ricky Wai96f5c352019-04-10 18:40:17 +0100668 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000669
Wale Ogunwalef6733932018-06-27 05:14:34 -0700670 private final class FontScaleSettingObserver extends ContentObserver {
671 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
672 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
673
674 public FontScaleSettingObserver() {
675 super(mH);
676 final ContentResolver resolver = mContext.getContentResolver();
677 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
678 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
679 UserHandle.USER_ALL);
680 }
681
682 @Override
683 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
684 if (mFontScaleUri.equals(uri)) {
685 updateFontScaleIfNeeded(userId);
686 } else if (mHideErrorDialogsUri.equals(uri)) {
687 synchronized (mGlobalLock) {
688 updateShouldShowDialogsLocked(getGlobalConfiguration());
689 }
690 }
691 }
692 }
693
Riddle Hsua0536432019-02-16 00:38:59 +0800694 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
695 @Target(ElementType.METHOD)
696 @Retention(RetentionPolicy.SOURCE)
697 @interface HotPath {
698 int NONE = 0;
699 int OOM_ADJUSTMENT = 1;
700 int LRU_UPDATE = 2;
701 int PROCESS_CHANGE = 3;
702 int caller() default NONE;
703 }
704
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800705 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
706 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900707 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800708 mAmInternal.updateOomAdj();
709 }
710 };
711
Charles Chen8d98dd22018-12-26 17:36:54 +0800712 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
713 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700714 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700715 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700716 mSystemThread = ActivityThread.currentActivityThread();
717 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700718 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800719 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700720 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700721 }
722
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700723 public void onSystemReady() {
724 synchronized (mGlobalLock) {
725 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
726 PackageManager.FEATURE_CANT_SAVE_STATE);
727 mAssistUtils = new AssistUtils(mContext);
728 mVrController.onSystemReady();
729 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700730 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700731 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700732 }
733
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700734 public void onInitPowerManagement() {
735 synchronized (mGlobalLock) {
736 mStackSupervisor.initPowerManagement();
737 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
738 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
739 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
740 mVoiceWakeLock.setReferenceCounted(false);
741 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700742 }
743
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700744 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700745 mFontScaleSettingObserver = new FontScaleSettingObserver();
746 }
747
Wale Ogunwale59507092018-10-29 09:00:30 -0700748 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700749 final boolean freeformWindowManagement =
750 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
751 || Settings.Global.getInt(
752 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
753
754 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
755 final boolean supportsPictureInPicture = supportsMultiWindow &&
756 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
757 final boolean supportsSplitScreenMultiWindow =
758 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
759 final boolean supportsMultiDisplay = mContext.getPackageManager()
760 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700761 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
762 final boolean forceResizable = Settings.Global.getInt(
763 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700764 final boolean sizeCompatFreeform = Settings.Global.getInt(
765 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700766
767 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900768 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700769
770 final Configuration configuration = new Configuration();
771 Settings.System.getConfiguration(resolver, configuration);
772 if (forceRtl) {
773 // This will take care of setting the correct layout direction flags
774 configuration.setLayoutDirection(configuration.locale);
775 }
776
777 synchronized (mGlobalLock) {
778 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700779 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700780 final boolean multiWindowFormEnabled = freeformWindowManagement
781 || supportsSplitScreenMultiWindow
782 || supportsPictureInPicture
783 || supportsMultiDisplay;
784 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
785 mSupportsMultiWindow = true;
786 mSupportsFreeformWindowManagement = freeformWindowManagement;
787 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
788 mSupportsPictureInPicture = supportsPictureInPicture;
789 mSupportsMultiDisplay = supportsMultiDisplay;
790 } else {
791 mSupportsMultiWindow = false;
792 mSupportsFreeformWindowManagement = false;
793 mSupportsSplitScreenMultiWindow = false;
794 mSupportsPictureInPicture = false;
795 mSupportsMultiDisplay = false;
796 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700797 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700798 // This happens before any activities are started, so we can change global configuration
799 // in-place.
800 updateConfigurationLocked(configuration, null, true);
801 final Configuration globalConfig = getGlobalConfiguration();
802 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
803
804 // Load resources only after the current configuration has been set.
805 final Resources res = mContext.getResources();
806 mThumbnailWidth = res.getDimensionPixelSize(
807 com.android.internal.R.dimen.thumbnail_width);
808 mThumbnailHeight = res.getDimensionPixelSize(
809 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700810 }
811 }
812
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800813 public WindowManagerGlobalLock getGlobalLock() {
814 return mGlobalLock;
815 }
816
Yunfan Chen585f2932019-01-29 16:04:45 +0900817 /** For test purpose only. */
818 @VisibleForTesting
819 public ActivityTaskManagerInternal getAtmInternal() {
820 return mInternal;
821 }
822
Riddle Hsud93a6c42018-11-29 21:50:06 +0800823 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
824 Looper looper) {
825 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700826 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700827 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700828 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800829 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700830 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700831 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700832 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700833
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700834 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700835 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700836 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700837 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700838 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700839 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700840 mKeyguardController = mStackSupervisor.getKeyguardController();
841 }
842
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700843 public void onActivityManagerInternalAdded() {
844 synchronized (mGlobalLock) {
845 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
846 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
847 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700848 }
849
Yunfan Chen75157d72018-07-27 14:47:21 +0900850 int increaseConfigurationSeqLocked() {
851 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
852 return mConfigurationSeq;
853 }
854
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700855 protected ActivityStackSupervisor createStackSupervisor() {
856 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
857 supervisor.initialize();
858 return supervisor;
859 }
860
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800861 protected AppWarnings createAppWarnings(
862 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
863 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
864 }
865
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700866 public void setWindowManager(WindowManagerService wm) {
867 synchronized (mGlobalLock) {
868 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800869 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800870 mTempConfig.setToDefaults();
871 mTempConfig.setLocales(LocaleList.getDefault());
872 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800873 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700874 mLockTaskController.setWindowManager(wm);
875 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800876 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700877 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700878 }
879
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700880 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
881 synchronized (mGlobalLock) {
882 mUsageStatsInternal = usageStatsManager;
883 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700884 }
885
Wale Ogunwalef6733932018-06-27 05:14:34 -0700886 UserManagerService getUserManager() {
887 if (mUserManager == null) {
888 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
889 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
890 }
891 return mUserManager;
892 }
893
Philip P. Moltmannee295092020-02-10 08:46:26 -0800894 AppOpsManager getAppOpsManager() {
895 if (mAppOpsManager == null) {
896 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Wale Ogunwalef6733932018-06-27 05:14:34 -0700897 }
Philip P. Moltmannee295092020-02-10 08:46:26 -0800898 return mAppOpsManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700899 }
900
901 boolean hasUserRestriction(String restriction, int userId) {
902 return getUserManager().hasUserRestriction(restriction, userId);
903 }
904
Michal Karpinski15486842019-04-25 17:33:42 +0100905 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
Philip P. Moltmannee295092020-02-10 08:46:26 -0800906 final int mode = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
907 callingUid, callingPackage, /* featureId */ null, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100908 if (mode == AppOpsManager.MODE_DEFAULT) {
909 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
910 == PERMISSION_GRANTED;
911 }
912 return mode == AppOpsManager.MODE_ALLOWED;
913 }
914
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700915 @VisibleForTesting
916 protected void setRecentTasks(RecentTasks recentTasks) {
917 mRecentTasks = recentTasks;
918 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700919 }
920
921 RecentTasks getRecentTasks() {
922 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700923 }
924
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700925 ClientLifecycleManager getLifecycleManager() {
926 return mLifecycleManager;
927 }
928
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700929 ActivityStartController getActivityStartController() {
930 return mActivityStartController;
931 }
932
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700933 TaskChangeNotificationController getTaskChangeNotificationController() {
934 return mTaskChangeNotificationController;
935 }
936
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700937 LockTaskController getLockTaskController() {
938 return mLockTaskController;
939 }
940
Yunfan Chen75157d72018-07-27 14:47:21 +0900941 /**
942 * Return the global configuration used by the process corresponding to the input pid. This is
943 * usually the global configuration with some overrides specific to that process.
944 */
945 Configuration getGlobalConfigurationForCallingPid() {
946 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800947 return getGlobalConfigurationForPid(pid);
948 }
949
950 /**
951 * Return the global configuration used by the process corresponding to the given pid.
952 */
953 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900954 if (pid == MY_PID || pid < 0) {
955 return getGlobalConfiguration();
956 }
957 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100958 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900959 return app != null ? app.getConfiguration() : getGlobalConfiguration();
960 }
961 }
962
963 /**
964 * Return the device configuration info used by the process corresponding to the input pid.
965 * The value is consistent with the global configuration for the process.
966 */
967 @Override
968 public ConfigurationInfo getDeviceConfigurationInfo() {
969 ConfigurationInfo config = new ConfigurationInfo();
970 synchronized (mGlobalLock) {
971 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
972 config.reqTouchScreen = globalConfig.touchscreen;
973 config.reqKeyboardType = globalConfig.keyboard;
974 config.reqNavigation = globalConfig.navigation;
975 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
976 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
977 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
978 }
979 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
980 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
981 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
982 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700983 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900984 }
985 return config;
986 }
987
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700988 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700989 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700990 }
991
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700992 public static final class Lifecycle extends SystemService {
993 private final ActivityTaskManagerService mService;
994
995 public Lifecycle(Context context) {
996 super(context);
997 mService = new ActivityTaskManagerService(context);
998 }
999
1000 @Override
1001 public void onStart() {
1002 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001003 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001004 }
1005
Garfield Tan891146c2018-10-09 12:14:00 -07001006 @Override
1007 public void onUnlockUser(int userId) {
1008 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001009 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001010 }
1011 }
1012
1013 @Override
1014 public void onCleanupUser(int userId) {
1015 synchronized (mService.getGlobalLock()) {
1016 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1017 }
1018 }
1019
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001020 public ActivityTaskManagerService getService() {
1021 return mService;
1022 }
1023 }
1024
1025 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001026 public final int startActivity(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001027 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1028 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1029 Bundle bOptions) {
1030 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1031 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001032 UserHandle.getCallingUserId());
1033 }
1034
1035 @Override
1036 public final int startActivities(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001037 String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
1038 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001039 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001041 enforceNotIsolatedCaller(reason);
1042 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001044 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001045 callingFeatureId, intents, resolvedTypes, resultTo,
1046 SafeActivityOptions.fromBundle(bOptions), userId, reason,
1047 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001048 }
1049
1050 @Override
1051 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001052 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1053 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1054 Bundle bOptions, int userId) {
1055 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1056 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001057 true /*validateIncomingUser*/);
1058 }
1059
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001060 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001061 @Nullable String callingFeatureId, Intent intent, String resolvedType,
1062 IBinder resultTo, String resultWho, int requestCode, int startFlags,
1063 ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001064 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001065 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001067 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001068 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1069
1070 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001071 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001072 .setCaller(caller)
1073 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001074 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001075 .setResolvedType(resolvedType)
1076 .setResultTo(resultTo)
1077 .setResultWho(resultWho)
1078 .setRequestCode(requestCode)
1079 .setStartFlags(startFlags)
1080 .setProfilerInfo(profilerInfo)
1081 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001082 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001083 .execute();
1084
1085 }
1086
1087 @Override
1088 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1089 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001090 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1091 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001092 // Refuse possible leaked file descriptors
1093 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1094 throw new IllegalArgumentException("File descriptors passed in Intent");
1095 }
1096
1097 if (!(target instanceof PendingIntentRecord)) {
1098 throw new IllegalArgumentException("Bad PendingIntent object");
1099 }
1100
1101 PendingIntentRecord pir = (PendingIntentRecord)target;
1102
1103 synchronized (mGlobalLock) {
1104 // If this is coming from the currently resumed activity, it is
1105 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001106 final ActivityStack stack = getTopDisplayFocusedStack();
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001107 if (stack != null && stack.mResumedActivity != null
1108 && stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001109 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001110 }
1111 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001112 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001113 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001114 }
1115
1116 @Override
1117 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1118 Bundle bOptions) {
1119 // Refuse possible leaked file descriptors
1120 if (intent != null && intent.hasFileDescriptors()) {
1121 throw new IllegalArgumentException("File descriptors passed in Intent");
1122 }
1123 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1124
1125 synchronized (mGlobalLock) {
1126 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1127 if (r == null) {
1128 SafeActivityOptions.abort(options);
1129 return false;
1130 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001131 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001132 // The caller is not running... d'oh!
1133 SafeActivityOptions.abort(options);
1134 return false;
1135 }
1136 intent = new Intent(intent);
1137 // The caller is not allowed to change the data.
1138 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1139 // And we are resetting to find the next component...
1140 intent.setComponent(null);
1141
1142 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1143
1144 ActivityInfo aInfo = null;
1145 try {
1146 List<ResolveInfo> resolves =
1147 AppGlobals.getPackageManager().queryIntentActivities(
1148 intent, r.resolvedType,
1149 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1150 UserHandle.getCallingUserId()).getList();
1151
1152 // Look for the original activity in the list...
1153 final int N = resolves != null ? resolves.size() : 0;
1154 for (int i=0; i<N; i++) {
1155 ResolveInfo rInfo = resolves.get(i);
1156 if (rInfo.activityInfo.packageName.equals(r.packageName)
1157 && rInfo.activityInfo.name.equals(r.info.name)) {
1158 // We found the current one... the next matching is
1159 // after it.
1160 i++;
1161 if (i<N) {
1162 aInfo = resolves.get(i).activityInfo;
1163 }
1164 if (debug) {
1165 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1166 + "/" + r.info.name);
1167 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1168 ? "null" : aInfo.packageName + "/" + aInfo.name));
1169 }
1170 break;
1171 }
1172 }
1173 } catch (RemoteException e) {
1174 }
1175
1176 if (aInfo == null) {
1177 // Nobody who is next!
1178 SafeActivityOptions.abort(options);
1179 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1180 return false;
1181 }
1182
1183 intent.setComponent(new ComponentName(
1184 aInfo.applicationInfo.packageName, aInfo.name));
1185 intent.setFlags(intent.getFlags()&~(
1186 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1187 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1188 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1189 FLAG_ACTIVITY_NEW_TASK));
1190
1191 // Okay now we need to start the new activity, replacing the currently running activity.
1192 // This is a little tricky because we want to start the new one as if the current one is
1193 // finished, but not finish the current one first so that there is no flicker.
1194 // And thus...
1195 final boolean wasFinishing = r.finishing;
1196 r.finishing = true;
1197
1198 // Propagate reply information over to the new activity.
1199 final ActivityRecord resultTo = r.resultTo;
1200 final String resultWho = r.resultWho;
1201 final int requestCode = r.requestCode;
1202 r.resultTo = null;
1203 if (resultTo != null) {
1204 resultTo.removeResultsLocked(r, resultWho, requestCode);
1205 }
1206
1207 final long origId = Binder.clearCallingIdentity();
1208 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001209 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001210 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001211 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001212 .setResolvedType(r.resolvedType)
1213 .setActivityInfo(aInfo)
1214 .setResultTo(resultTo != null ? resultTo.appToken : null)
1215 .setResultWho(resultWho)
1216 .setRequestCode(requestCode)
1217 .setCallingPid(-1)
1218 .setCallingUid(r.launchedFromUid)
1219 .setCallingPackage(r.launchedFromPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001220 .setCallingFeatureId(r.launchedFromFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001221 .setRealCallingPid(-1)
1222 .setRealCallingUid(r.launchedFromUid)
1223 .setActivityOptions(options)
1224 .execute();
1225 Binder.restoreCallingIdentity(origId);
1226
1227 r.finishing = wasFinishing;
1228 if (res != ActivityManager.START_SUCCESS) {
1229 return false;
1230 }
1231 return true;
1232 }
1233 }
1234
1235 @Override
Galia Peycheva6861e912019-08-21 10:20:23 +02001236 public boolean startDreamActivity(Intent intent) {
Galia Peycheva52e89222020-02-18 23:41:43 +01001237 final WindowProcessController process = mProcessMap.getProcess(Binder.getCallingPid());
1238 final long origId = Binder.clearCallingIdentity();
1239
1240 // The dream activity is only called for non-doze dreams.
1241 final ComponentName currentDream = LocalServices.getService(DreamManagerInternal.class)
1242 .getActiveDreamComponent(/* doze= */ false);
1243
1244 if (currentDream == null || currentDream.getPackageName() == null
1245 || !currentDream.getPackageName().equals(process.mInfo.packageName)) {
1246 Slog.e(TAG, "Calling package is not the current dream package. "
1247 + "Aborting startDreamActivity...");
1248 return false;
1249 }
1250
Galia Peycheva6861e912019-08-21 10:20:23 +02001251 final ActivityInfo a = new ActivityInfo();
1252 a.theme = com.android.internal.R.style.Theme_Dream;
1253 a.exported = true;
1254 a.name = DreamActivity.class.getName();
1255
Galia Peycheva6861e912019-08-21 10:20:23 +02001256
1257 a.packageName = process.mInfo.packageName;
1258 a.applicationInfo = process.mInfo;
1259 a.processName = process.mInfo.processName;
1260 a.uiOptions = process.mInfo.uiOptions;
1261 a.taskAffinity = "android:" + a.packageName + "/dream";
1262 a.enabled = true;
1263 a.launchMode = ActivityInfo.LAUNCH_SINGLE_INSTANCE;
1264
1265 a.persistableMode = ActivityInfo.PERSIST_NEVER;
1266 a.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1267 a.colorMode = ActivityInfo.COLOR_MODE_DEFAULT;
1268 a.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1269
Galia Peycheva6861e912019-08-21 10:20:23 +02001270 try {
1271 getActivityStartController().obtainStarter(intent, "dream")
1272 .setActivityInfo(a)
1273 .setIsDream(true)
1274 .execute();
1275 return true;
1276 } finally {
1277 Binder.restoreCallingIdentity(origId);
1278 }
1279 }
1280
1281 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001282 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001283 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1284 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1285 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001286 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001287 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001288 enforceNotIsolatedCaller("startActivityAndWait");
1289 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1290 userId, "startActivityAndWait");
1291 // TODO: Switch to user app stacks here.
1292 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1293 .setCaller(caller)
1294 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001295 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001296 .setResolvedType(resolvedType)
1297 .setResultTo(resultTo)
1298 .setResultWho(resultWho)
1299 .setRequestCode(requestCode)
1300 .setStartFlags(startFlags)
1301 .setActivityOptions(bOptions)
1302 .setUserId(userId)
1303 .setProfilerInfo(profilerInfo)
1304 .setWaitResult(res)
1305 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001306 return res;
1307 }
1308
1309 @Override
1310 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001311 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1312 String resultWho, int requestCode, int startFlags, Configuration config,
1313 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001314 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001315 enforceNotIsolatedCaller("startActivityWithConfig");
1316 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1317 "startActivityWithConfig");
1318 // TODO: Switch to user app stacks here.
1319 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1320 .setCaller(caller)
1321 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001322 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001323 .setResolvedType(resolvedType)
1324 .setResultTo(resultTo)
1325 .setResultWho(resultWho)
1326 .setRequestCode(requestCode)
1327 .setStartFlags(startFlags)
1328 .setGlobalConfiguration(config)
1329 .setActivityOptions(bOptions)
1330 .setUserId(userId)
1331 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001332 }
1333
Robert Carr8a2f9132019-11-11 15:03:15 -08001334 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001335 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1336 int callingUid = Binder.getCallingUid();
1337 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1338 throw new SecurityException("Only the system process can request a permission token, "
1339 + "received request from uid: " + callingUid);
1340 }
1341 IBinder permissionToken = new Binder();
1342 synchronized (mGlobalLock) {
1343 mStartActivitySources.put(permissionToken, delegatorToken);
1344 }
1345
1346 Message expireMsg = PooledLambda.obtainMessage(
1347 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1348 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1349
1350 Message forgetMsg = PooledLambda.obtainMessage(
1351 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1352 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1353
1354 return permissionToken;
1355 }
1356
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001357 @Override
1358 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1359 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001360 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1361 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001362 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001363 // permission grants) as any app that may launch one of your own activities. So we only
1364 // allow this in two cases:
1365 // 1) The caller is an activity that is part of the core framework, and then only when it
1366 // is running as the system.
1367 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1368 // can only be requested by a system activity, which may then delegate this call to
1369 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001370 final ActivityRecord sourceRecord;
1371 final int targetUid;
1372 final String targetPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001373 final String targetFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001374 final boolean isResolver;
1375 synchronized (mGlobalLock) {
1376 if (resultTo == null) {
1377 throw new SecurityException("Must be called from an activity");
1378 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001379 final IBinder sourceToken;
1380 if (permissionToken != null) {
1381 // To even attempt to use a permissionToken, an app must also have this signature
1382 // permission.
1383 mAmInternal.enforceCallingPermission(
1384 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1385 "startActivityAsCaller");
1386 // If called with a permissionToken, we want the sourceRecord from the delegator
1387 // activity that requested this token.
1388 sourceToken = mStartActivitySources.remove(permissionToken);
1389 if (sourceToken == null) {
1390 // Invalid permissionToken, check if it recently expired.
1391 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1392 throw new SecurityException("Called with expired permission token: "
1393 + permissionToken);
1394 } else {
1395 throw new SecurityException("Called with invalid permission token: "
1396 + permissionToken);
1397 }
1398 }
1399 } else {
1400 // This method was called directly by the source.
1401 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001402 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001403
Louis Chang149d5c82019-12-30 09:47:39 +08001404 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001405 if (sourceRecord == null) {
1406 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001407 }
1408 if (sourceRecord.app == null) {
1409 throw new SecurityException("Called without a process attached to activity");
1410 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001411
1412 // Whether called directly or from a delegate, the source activity must be from the
1413 // android package.
1414 if (!sourceRecord.info.packageName.equals("android")) {
1415 throw new SecurityException("Must be called from an activity that is "
1416 + "declared in the android package");
1417 }
1418
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001419 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001420 // This is still okay, as long as this activity is running under the
1421 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001422 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001423 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001424 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001425 + " must be system uid or original calling uid "
1426 + sourceRecord.launchedFromUid);
1427 }
1428 }
1429 if (ignoreTargetSecurity) {
1430 if (intent.getComponent() == null) {
1431 throw new SecurityException(
1432 "Component must be specified with ignoreTargetSecurity");
1433 }
1434 if (intent.getSelector() != null) {
1435 throw new SecurityException(
1436 "Selector not allowed with ignoreTargetSecurity");
1437 }
1438 }
1439 targetUid = sourceRecord.launchedFromUid;
1440 targetPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001441 targetFeatureId = sourceRecord.launchedFromFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001442 isResolver = sourceRecord.isResolverOrChildActivity();
1443 }
1444
1445 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001446 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001447 }
1448
1449 // TODO: Switch to user app stacks here.
1450 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001451 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452 .setCallingUid(targetUid)
1453 .setCallingPackage(targetPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001454 .setCallingFeatureId(targetFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455 .setResolvedType(resolvedType)
1456 .setResultTo(resultTo)
1457 .setResultWho(resultWho)
1458 .setRequestCode(requestCode)
1459 .setStartFlags(startFlags)
1460 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001461 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001462 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1463 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001464 // The target may well be in the background, which would normally prevent it
1465 // from starting an activity. Here we definitely want the start to succeed.
1466 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001467 .execute();
1468 } catch (SecurityException e) {
1469 // XXX need to figure out how to propagate to original app.
1470 // A SecurityException here is generally actually a fault of the original
1471 // calling activity (such as a fairly granting permissions), so propagate it
1472 // back to them.
1473 /*
1474 StringBuilder msg = new StringBuilder();
1475 msg.append("While launching");
1476 msg.append(intent.toString());
1477 msg.append(": ");
1478 msg.append(e.getMessage());
1479 */
1480 throw e;
1481 }
1482 }
1483
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001484 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1485 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001486 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001487 }
1488
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001489 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001490 public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1491 int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001492 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1493 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001494 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001495 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001496 if (session == null || interactor == null) {
1497 throw new NullPointerException("null session or interactor");
1498 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001499 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001500 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001501 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001502 .setCallingUid(callingUid)
1503 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001504 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001505 .setResolvedType(resolvedType)
1506 .setVoiceSession(session)
1507 .setVoiceInteractor(interactor)
1508 .setStartFlags(startFlags)
1509 .setProfilerInfo(profilerInfo)
1510 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001511 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001512 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001513 .execute();
1514 }
1515
1516 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001517 public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1518 int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1519 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001520 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001521 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1522 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001523
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001524 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001525 .setCallingUid(callingUid)
1526 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001527 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001528 .setResolvedType(resolvedType)
1529 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001530 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001531 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001532 .execute();
1533 }
1534
Riddle Hsu609a8e22019-06-27 16:46:29 -06001535 /**
1536 * Start the recents activity to perform the recents animation.
1537 *
1538 * @param intent The intent to start the recents activity.
1539 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1540 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001541 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001542 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1543 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001544 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001545 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001546 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001547 final long origId = Binder.clearCallingIdentity();
1548 try {
1549 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001550 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
Philip P. Moltmannee295092020-02-10 08:46:26 -08001551 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001552 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001553 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001554
1555 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001556 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001557 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001558 recentsFeatureId, recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001559 if (recentsAnimationRunner == null) {
1560 anim.preloadRecentsActivity();
1561 } else {
1562 anim.startRecentsActivity(recentsAnimationRunner);
1563 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001564 }
1565 } finally {
1566 Binder.restoreCallingIdentity(origId);
1567 }
1568 }
1569
1570 @Override
1571 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001572 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001573 "startActivityFromRecents()");
1574
1575 final int callingPid = Binder.getCallingPid();
1576 final int callingUid = Binder.getCallingUid();
1577 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1578 final long origId = Binder.clearCallingIdentity();
1579 try {
1580 synchronized (mGlobalLock) {
1581 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1582 safeOptions);
1583 }
1584 } finally {
1585 Binder.restoreCallingIdentity(origId);
1586 }
1587 }
1588
1589 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001590 * Public API to check if the client is allowed to start an activity on specified display.
1591 *
1592 * If the target display is private or virtual, some restrictions will apply.
1593 *
1594 * @param displayId Target display id.
1595 * @param intent Intent used to launch the activity.
1596 * @param resolvedType The MIME type of the intent.
1597 * @param userId The id of the user for whom the call is made.
1598 * @return {@code true} if a call to start an activity on the target display should succeed and
1599 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1600 */
1601 @Override
1602 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1603 String resolvedType, int userId) {
1604 final int callingUid = Binder.getCallingUid();
1605 final int callingPid = Binder.getCallingPid();
1606 final long origId = Binder.clearCallingIdentity();
1607
1608 try {
1609 // Collect information about the target of the Intent.
1610 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1611 0 /* startFlags */, null /* profilerInfo */, userId,
1612 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1613 UserHandle.USER_NULL));
1614 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1615
1616 synchronized (mGlobalLock) {
1617 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1618 aInfo);
1619 }
1620 } finally {
1621 Binder.restoreCallingIdentity(origId);
1622 }
1623 }
1624
1625 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001626 * This is the internal entry point for handling Activity.finish().
1627 *
1628 * @param token The Binder token referencing the Activity we want to finish.
1629 * @param resultCode Result code, if any, from this Activity.
1630 * @param resultData Result data (Intent), if any, from this Activity.
1631 * @param finishTask Whether to finish the task associated with this Activity.
1632 *
1633 * @return Returns true if the activity successfully finished, or false if it is still running.
1634 */
1635 @Override
1636 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1637 int finishTask) {
1638 // Refuse possible leaked file descriptors
1639 if (resultData != null && resultData.hasFileDescriptors()) {
1640 throw new IllegalArgumentException("File descriptors passed in Intent");
1641 }
1642
1643 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001644 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001645 if (r == null) {
1646 return true;
1647 }
1648 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001649 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001650 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001651 if (rootR == null) {
1652 Slog.w(TAG, "Finishing task with all activities already finished");
1653 }
1654 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1655 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001656 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001657 return false;
1658 }
1659
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001660 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1661 // We should consolidate.
1662 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001663 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001664 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001665 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001666 if (next != null) {
1667 // ask watcher if this is allowed
1668 boolean resumeOK = true;
1669 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001670 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001671 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001672 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001673 Watchdog.getInstance().setActivityController(null);
1674 }
1675
1676 if (!resumeOK) {
1677 Slog.i(TAG, "Not finishing activity because controller resumed");
1678 return false;
1679 }
1680 }
1681 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001682
1683 // note down that the process has finished an activity and is in background activity
1684 // starts grace period
1685 if (r.app != null) {
1686 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1687 }
1688
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001689 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001690 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001691 try {
1692 boolean res;
1693 final boolean finishWithRootActivity =
1694 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1695 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1696 || (finishWithRootActivity && r == rootR)) {
1697 // If requested, remove the task that is associated to this activity only if it
1698 // was the root activity in the task. The result code and data is ignored
1699 // because we don't support returning them across task boundaries. Also, to
1700 // keep backwards compatibility we remove the task from recents when finishing
1701 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001702 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001703 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001704 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001705 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001706 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001707 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001708 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001709 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001710 if (!res) {
1711 Slog.i(TAG, "Failed to finish by app-request");
1712 }
1713 }
1714 return res;
1715 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001716 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001717 Binder.restoreCallingIdentity(origId);
1718 }
1719 }
1720 }
1721
1722 @Override
1723 public boolean finishActivityAffinity(IBinder token) {
1724 synchronized (mGlobalLock) {
1725 final long origId = Binder.clearCallingIdentity();
1726 try {
1727 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1728 if (r == null) {
1729 return false;
1730 }
1731
1732 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1733 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001734 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001735 return false;
1736 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001737
1738 final PooledFunction p = PooledLambda.obtainFunction(
1739 ActivityRecord::finishIfSameAffinity, r,
1740 PooledLambda.__(ActivityRecord.class));
1741 r.getTask().forAllActivities(
1742 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1743 p.recycle();
1744
Andrii Kuliande93eff2019-07-12 12:21:27 -07001745 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001746 } finally {
1747 Binder.restoreCallingIdentity(origId);
1748 }
1749 }
1750 }
1751
1752 @Override
1753 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1754 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001755 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001756 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001757 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001758 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1759 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001760 return;
1761 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001762 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1763 false /* processPausingActivities */, config);
1764 if (stopProfiling && r.hasProcess()) {
1765 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001766 }
1767 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001768 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001769 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001770 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001771 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001772 }
1773
1774 @Override
1775 public final void activityResumed(IBinder token) {
1776 final long origId = Binder.clearCallingIdentity();
1777 synchronized (mGlobalLock) {
1778 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001779 }
1780 Binder.restoreCallingIdentity(origId);
1781 }
1782
1783 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001784 public final void activityTopResumedStateLost() {
1785 final long origId = Binder.clearCallingIdentity();
1786 synchronized (mGlobalLock) {
1787 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1788 }
1789 Binder.restoreCallingIdentity(origId);
1790 }
1791
1792 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001793 public final void activityPaused(IBinder token) {
1794 final long origId = Binder.clearCallingIdentity();
1795 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001796 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001797 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1798 if (r != null) {
1799 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001801 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001802 }
1803 Binder.restoreCallingIdentity(origId);
1804 }
1805
1806 @Override
1807 public final void activityStopped(IBinder token, Bundle icicle,
1808 PersistableBundle persistentState, CharSequence description) {
1809 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1810
1811 // Refuse possible leaked file descriptors
1812 if (icicle != null && icicle.hasFileDescriptors()) {
1813 throw new IllegalArgumentException("File descriptors passed in Bundle");
1814 }
1815
1816 final long origId = Binder.clearCallingIdentity();
1817
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001818 String restartingName = null;
1819 int restartingUid = 0;
1820 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001821 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001822 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001823 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001824 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001825 if (r.attachedToProcess()
1826 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1827 // The activity was requested to restart from
1828 // {@link #restartActivityProcessIfVisible}.
1829 restartingName = r.app.mName;
1830 restartingUid = r.app.mUid;
1831 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001832 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001833 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001834 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001835 }
1836
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001837 if (restartingName != null) {
1838 // In order to let the foreground activity can be restarted with its saved state from
1839 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1840 // until the activity reports stopped with the state. And the activity record will be
1841 // kept because the record state is restarting, then the activity will be restarted
1842 // immediately if it is still the top one.
1843 mStackSupervisor.removeRestartTimeouts(r);
1844 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1845 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001846 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001847
1848 Binder.restoreCallingIdentity(origId);
1849 }
1850
1851 @Override
1852 public final void activityDestroyed(IBinder token) {
1853 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1854 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001855 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001856 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001857 try {
1858 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1859 if (activity != null) {
1860 activity.destroyed("activityDestroyed");
1861 }
1862 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001863 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001864 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001865 }
1866 }
1867 }
1868
1869 @Override
1870 public final void activityRelaunched(IBinder token) {
1871 final long origId = Binder.clearCallingIdentity();
1872 synchronized (mGlobalLock) {
1873 mStackSupervisor.activityRelaunchedLocked(token);
1874 }
1875 Binder.restoreCallingIdentity(origId);
1876 }
1877
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001878 @Override
1879 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1880 synchronized (mGlobalLock) {
1881 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1882 if (r == null) {
1883 return;
1884 }
1885 final long origId = Binder.clearCallingIdentity();
1886 try {
1887 r.setRequestedOrientation(requestedOrientation);
1888 } finally {
1889 Binder.restoreCallingIdentity(origId);
1890 }
1891 }
1892 }
1893
1894 @Override
1895 public int getRequestedOrientation(IBinder token) {
1896 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001897 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1898 return (r != null)
1899 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001900 }
1901 }
1902
1903 @Override
1904 public void setImmersive(IBinder token, boolean immersive) {
1905 synchronized (mGlobalLock) {
1906 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1907 if (r == null) {
1908 throw new IllegalArgumentException();
1909 }
1910 r.immersive = immersive;
1911
1912 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001913 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001914 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001915 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001916 }
1917 }
1918 }
1919
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001920 void applyUpdateLockStateLocked(ActivityRecord r) {
1921 // Modifications to the UpdateLock state are done on our handler, outside
1922 // the activity manager's locks. The new state is determined based on the
1923 // state *now* of the relevant activity record. The object is passed to
1924 // the handler solely for logging detail, not to be consulted/modified.
1925 final boolean nextState = r != null && r.immersive;
1926 mH.post(() -> {
1927 if (mUpdateLock.isHeld() != nextState) {
1928 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1929 "Applying new update lock state '" + nextState + "' for " + r);
1930 if (nextState) {
1931 mUpdateLock.acquire();
1932 } else {
1933 mUpdateLock.release();
1934 }
1935 }
1936 });
1937 }
1938
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001939 @Override
1940 public boolean isImmersive(IBinder token) {
1941 synchronized (mGlobalLock) {
1942 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1943 if (r == null) {
1944 throw new IllegalArgumentException();
1945 }
1946 return r.immersive;
1947 }
1948 }
1949
1950 @Override
1951 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001952 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001953 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001954 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
1955 if (topFocusedStack == null) {
1956 return false;
1957 }
1958
1959 final ActivityRecord r = topFocusedStack.topRunningActivity();
1960 return r != null && r.immersive;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001961 }
1962 }
1963
1964 @Override
1965 public void overridePendingTransition(IBinder token, String packageName,
1966 int enterAnim, int exitAnim) {
1967 synchronized (mGlobalLock) {
1968 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1969 if (self == null) {
1970 return;
1971 }
1972
1973 final long origId = Binder.clearCallingIdentity();
1974
1975 if (self.isState(
1976 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001977 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001978 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001979 }
1980
1981 Binder.restoreCallingIdentity(origId);
1982 }
1983 }
1984
1985 @Override
1986 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001987 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001988 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001989 final ActivityStack stack = getTopDisplayFocusedStack();
1990 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001991 if (r == null) {
1992 return ActivityManager.COMPAT_MODE_UNKNOWN;
1993 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001994 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001995 }
1996 }
1997
1998 @Override
1999 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002000 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002001 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002002 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002003 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002004 final ActivityStack stack = getTopDisplayFocusedStack();
2005 final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002006 if (r == null) {
2007 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
2008 return;
2009 }
2010 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07002011 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002012 }
2013 }
2014
2015 @Override
2016 public int getLaunchedFromUid(IBinder activityToken) {
2017 ActivityRecord srec;
2018 synchronized (mGlobalLock) {
2019 srec = ActivityRecord.forTokenLocked(activityToken);
2020 }
2021 if (srec == null) {
2022 return -1;
2023 }
2024 return srec.launchedFromUid;
2025 }
2026
2027 @Override
2028 public String getLaunchedFromPackage(IBinder activityToken) {
2029 ActivityRecord srec;
2030 synchronized (mGlobalLock) {
2031 srec = ActivityRecord.forTokenLocked(activityToken);
2032 }
2033 if (srec == null) {
2034 return null;
2035 }
2036 return srec.launchedFromPackage;
2037 }
2038
2039 @Override
2040 public boolean convertFromTranslucent(IBinder token) {
2041 final long origId = Binder.clearCallingIdentity();
2042 try {
2043 synchronized (mGlobalLock) {
2044 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2045 if (r == null) {
2046 return false;
2047 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002048 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002049 }
2050 } finally {
2051 Binder.restoreCallingIdentity(origId);
2052 }
2053 }
2054
2055 @Override
2056 public boolean convertToTranslucent(IBinder token, Bundle options) {
2057 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2058 final long origId = Binder.clearCallingIdentity();
2059 try {
2060 synchronized (mGlobalLock) {
2061 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2062 if (r == null) {
2063 return false;
2064 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002065 final ActivityRecord under = r.getTask().getActivityBelow(r);
2066 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002067 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2068 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002069 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002070 }
2071 } finally {
2072 Binder.restoreCallingIdentity(origId);
2073 }
2074 }
2075
2076 @Override
2077 public void notifyActivityDrawn(IBinder token) {
2078 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2079 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002080 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002081 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002082 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002083 }
2084 }
2085 }
2086
2087 @Override
2088 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2089 synchronized (mGlobalLock) {
2090 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2091 if (r == null) {
2092 return;
2093 }
2094 r.reportFullyDrawnLocked(restoredFromBundle);
2095 }
2096 }
2097
2098 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002099 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002100 synchronized (mGlobalLock) {
2101 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002102 if (stack != null) {
2103 final int displayId = stack.getDisplayId();
2104 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002105 }
2106 return DEFAULT_DISPLAY;
2107 }
2108 }
2109
2110 @Override
2111 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002112 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002113 long ident = Binder.clearCallingIdentity();
2114 try {
2115 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002116 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002117 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002118 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002119 }
2120 return null;
2121 }
2122 } finally {
2123 Binder.restoreCallingIdentity(ident);
2124 }
2125 }
2126
2127 @Override
2128 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002129 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002130 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2131 final long callingId = Binder.clearCallingIdentity();
2132 try {
2133 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002134 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002135 if (stack == null) {
2136 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2137 return;
2138 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002139 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002140 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002141 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002142 }
2143 }
2144 } finally {
2145 Binder.restoreCallingIdentity(callingId);
2146 }
2147 }
2148
2149 @Override
2150 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002151 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002152 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2153 final long callingId = Binder.clearCallingIdentity();
2154 try {
2155 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002156 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002157 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002158 if (task == null) {
2159 return;
2160 }
2161 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002162 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002163 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002164 }
2165 }
2166 } finally {
2167 Binder.restoreCallingIdentity(callingId);
2168 }
2169 }
2170
2171 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002172 public void restartActivityProcessIfVisible(IBinder activityToken) {
2173 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2174 final long callingId = Binder.clearCallingIdentity();
2175 try {
2176 synchronized (mGlobalLock) {
2177 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2178 if (r == null) {
2179 return;
2180 }
2181 r.restartProcessIfVisible();
2182 }
2183 } finally {
2184 Binder.restoreCallingIdentity(callingId);
2185 }
2186 }
2187
2188 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002189 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002190 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002191 synchronized (mGlobalLock) {
2192 final long ident = Binder.clearCallingIdentity();
2193 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002194 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002195 "remove-task");
2196 } finally {
2197 Binder.restoreCallingIdentity(ident);
2198 }
2199 }
2200 }
2201
2202 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002203 public void removeAllVisibleRecentTasks() {
2204 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2205 synchronized (mGlobalLock) {
2206 final long ident = Binder.clearCallingIdentity();
2207 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002208 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002209 } finally {
2210 Binder.restoreCallingIdentity(ident);
2211 }
2212 }
2213 }
2214
2215 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002216 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2217 synchronized (mGlobalLock) {
2218 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2219 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002220 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002221 }
2222 }
2223 return false;
2224 }
2225
2226 @Override
2227 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2228 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002229
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002230 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002231 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2232 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002233 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002234 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002235 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002236 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002237 }
2238 }
2239
2240 /**
2241 * Attempts to move a task backwards in z-order (the order of activities within the task is
2242 * unchanged).
2243 *
2244 * There are several possible results of this call:
2245 * - if the task is locked, then we will show the lock toast
2246 * - if there is a task behind the provided task, then that task is made visible and resumed as
2247 * this task is moved to the back
2248 * - otherwise, if there are no other tasks in the stack:
2249 * - if this task is in the pinned stack, then we remove the stack completely, which will
2250 * have the effect of moving the task to the top or bottom of the fullscreen stack
2251 * (depending on whether it is visible)
2252 * - otherwise, we simply return home and hide this task
2253 *
2254 * @param token A reference to the activity we wish to move
2255 * @param nonRoot If false then this only works if the activity is the root
2256 * of a task; if true it will work for any activity in a task.
2257 * @return Returns true if the move completed, false if not.
2258 */
2259 @Override
2260 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002261 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002262 synchronized (mGlobalLock) {
2263 final long origId = Binder.clearCallingIdentity();
2264 try {
2265 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002266 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002267 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002268 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002269 }
2270 } finally {
2271 Binder.restoreCallingIdentity(origId);
2272 }
2273 }
2274 return false;
2275 }
2276
2277 @Override
2278 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002279 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002280 long ident = Binder.clearCallingIdentity();
2281 Rect rect = new Rect();
2282 try {
2283 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002284 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002285 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2286 if (task == null) {
2287 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2288 return rect;
2289 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002290 if (task.getParent() != null) {
2291 rect.set(task.getBounds());
2292 } else if (task.mLastNonFullscreenBounds != null) {
2293 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002294 }
2295 }
2296 } finally {
2297 Binder.restoreCallingIdentity(ident);
2298 }
2299 return rect;
2300 }
2301
2302 @Override
2303 public ActivityManager.TaskDescription getTaskDescription(int id) {
2304 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002305 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002306 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002307 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002308 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2309 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002310 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002311 }
2312 }
2313 return null;
2314 }
2315
2316 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002317 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002318 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08002319 return setTaskWindowingModeSplitScreenPrimary(taskId, toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002320 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002321 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002322 synchronized (mGlobalLock) {
2323 final long ident = Binder.clearCallingIdentity();
2324 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002325 if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2326 return setTaskWindowingModeSplitScreen(taskId, windowingMode, toTop);
2327 }
Louis Chang149d5c82019-12-30 09:47:39 +08002328 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002329 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002330 if (task == null) {
2331 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002332 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002333 }
2334
2335 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2336 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2337
2338 if (!task.isActivityTypeStandardOrUndefined()) {
2339 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2340 + " non-standard task " + taskId + " to windowing mode="
2341 + windowingMode);
2342 }
2343
2344 final ActivityStack stack = task.getStack();
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002345 // Convert some windowing-mode changes into root-task reparents for split-screen.
2346 if (stack.getTile() != null) {
2347 stack.getDisplay().onSplitScreenModeDismissed();
2348 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002349 if (toTop) {
2350 stack.moveToFront("setTaskWindowingMode", task);
2351 }
2352 stack.setWindowingMode(windowingMode);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002353 stack.getDisplay().ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2354 true /* notifyClients */);
Winson Chung7ccc6812020-01-23 16:15:10 -08002355 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002356 } finally {
2357 Binder.restoreCallingIdentity(ident);
2358 }
2359 }
2360 }
2361
2362 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002363 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002364 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002365 ActivityRecord r = getCallingRecordLocked(token);
2366 return r != null ? r.info.packageName : null;
2367 }
2368 }
2369
2370 @Override
2371 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002372 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002373 ActivityRecord r = getCallingRecordLocked(token);
2374 return r != null ? r.intent.getComponent() : null;
2375 }
2376 }
2377
2378 private ActivityRecord getCallingRecordLocked(IBinder token) {
2379 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2380 if (r == null) {
2381 return null;
2382 }
2383 return r.resultTo;
2384 }
2385
2386 @Override
2387 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002388 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002389
2390 synchronized (mGlobalLock) {
2391 final long origId = Binder.clearCallingIdentity();
2392 try {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002393 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
2394 if (topFocusedStack != null) {
2395 topFocusedStack.unhandledBackLocked();
2396 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002397 } finally {
2398 Binder.restoreCallingIdentity(origId);
2399 }
2400 }
2401 }
2402
Mark Renouf446251d2019-04-26 10:22:41 -04002403 @Override
2404 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2405 synchronized (mGlobalLock) {
2406 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2407 if (r == null) {
2408 return;
2409 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002410 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002411 if (stack != null && stack.isSingleTaskInstance()) {
2412 // Single-task stacks are used for activities which are presented in floating
2413 // windows above full screen activities. Instead of directly finishing the
2414 // task, a task change listener is used to notify SystemUI so the action can be
2415 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002416 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002417 mTaskChangeNotificationController
2418 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2419 } else {
2420 try {
2421 callback.requestFinish();
2422 } catch (RemoteException e) {
2423 Slog.e(TAG, "Failed to invoke request finish callback", e);
2424 }
2425 }
2426 }
2427 }
2428
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002429 /**
2430 * TODO: Add mController hook
2431 */
2432 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002433 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2434 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002435 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002436
2437 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2438 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002439 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2440 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002441 }
2442 }
2443
Ricky Waiaca8a772019-04-04 16:01:06 +01002444 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2445 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002446 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002447 final int callingPid = Binder.getCallingPid();
2448 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002449 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002450 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002451 SafeActivityOptions.abort(options);
2452 return;
2453 }
2454 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002455 WindowProcessController callerApp = null;
2456 if (appThread != null) {
2457 callerApp = getProcessController(appThread);
2458 }
2459 final ActivityStarter starter = getActivityStartController().obtainStarter(
2460 null /* intent */, "moveTaskToFront");
2461 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
Galia Peycheva6861e912019-08-21 10:20:23 +02002462 -1, callerApp, null, false, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002463 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002464 return;
2465 }
2466 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002467 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002468 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002469 if (task == null) {
2470 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002471 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002472 return;
2473 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002474 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002475 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002476 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002477 return;
2478 }
2479 ActivityOptions realOptions = options != null
2480 ? options.getOptions(mStackSupervisor)
2481 : null;
2482 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2483 false /* forceNonResizable */);
2484
Wale Ogunwale21e06482019-11-18 05:14:15 -08002485 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002486 if (topActivity != null) {
2487
2488 // We are reshowing a task, use a starting window to hide the initial draw delay
2489 // so the transition can start earlier.
2490 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2491 true /* taskSwitch */, fromRecents);
2492 }
2493 } finally {
2494 Binder.restoreCallingIdentity(origId);
2495 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002496 }
2497
Ricky Waiaca8a772019-04-04 16:01:06 +01002498 /**
2499 * Return true if callingUid is system, or packageName belongs to that callingUid.
2500 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002501 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002502 try {
2503 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2504 if (packageName == null) {
2505 return false;
2506 }
2507 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2508 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2509 UserHandle.getUserId(callingUid));
2510 return UserHandle.isSameApp(callingUid, uid);
2511 }
2512 } catch (RemoteException e) {
2513 // Should not happen
2514 }
2515 return true;
2516 }
2517
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002518 /**
2519 * Checks that the provided package name matches the current calling UID, throws a security
2520 * exception if it doesn't.
2521 */
2522 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2523 final int callingUid = Binder.getCallingUid();
2524 if (isSameApp(callingUid, packageName)) {
2525 return;
2526 }
2527 final String msg = "Permission Denial: package=" + packageName
2528 + " does not belong to uid=" + callingUid;
2529 Slog.w(TAG, msg);
2530 throw new SecurityException(msg);
2531 }
2532
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002533 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2534 int callingPid, int callingUid, String name) {
2535 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2536 return true;
2537 }
2538
2539 if (getRecentTasks().isCallerRecents(sourceUid)) {
2540 return true;
2541 }
2542
2543 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2544 if (perm == PackageManager.PERMISSION_GRANTED) {
2545 return true;
2546 }
2547 if (checkAllowAppSwitchUid(sourceUid)) {
2548 return true;
2549 }
2550
2551 // If the actual IPC caller is different from the logical source, then
2552 // also see if they are allowed to control app switches.
2553 if (callingUid != -1 && callingUid != sourceUid) {
2554 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2555 if (perm == PackageManager.PERMISSION_GRANTED) {
2556 return true;
2557 }
2558 if (checkAllowAppSwitchUid(callingUid)) {
2559 return true;
2560 }
2561 }
2562
2563 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2564 return false;
2565 }
2566
2567 private boolean checkAllowAppSwitchUid(int uid) {
2568 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2569 if (types != null) {
2570 for (int i = types.size() - 1; i >= 0; i--) {
2571 if (types.valueAt(i).intValue() == uid) {
2572 return true;
2573 }
2574 }
2575 }
2576 return false;
2577 }
2578
2579 @Override
2580 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2581 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2582 "setActivityController()");
2583 synchronized (mGlobalLock) {
2584 mController = controller;
2585 mControllerIsAMonkey = imAMonkey;
2586 Watchdog.getInstance().setActivityController(controller);
2587 }
2588 }
2589
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002590 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002591 synchronized (mGlobalLock) {
2592 return mController != null && mControllerIsAMonkey;
2593 }
2594 }
2595
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002596 @Override
2597 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2598 synchronized (mGlobalLock) {
2599 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2600 }
2601 }
2602
2603 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002604 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2605 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2606 }
2607
2608 @Override
2609 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2610 @WindowConfiguration.ActivityType int ignoreActivityType,
2611 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2612 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002613 final int callingPid = Binder.getCallingPid();
2614 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002615 final int[] profileIds = getUserManager().getProfileIds(
2616 UserHandle.getUserId(callingUid), true);
2617 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2618 for (int i = 0; i < profileIds.length; i++) {
2619 callingProfileIds.add(profileIds[i]);
2620 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002621 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2622
2623 synchronized (mGlobalLock) {
2624 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2625
Nicholas Sauer0259e532019-08-30 08:24:55 -07002626 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002627 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002628 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002629 }
2630
2631 return list;
2632 }
2633
2634 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002635 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2636 synchronized (mGlobalLock) {
2637 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002638 try {
2639 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2640 if (r == null) return;
2641
2642 final PooledConsumer c = PooledLambda.obtainConsumer(
2643 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2644 r, resultWho, requestCode);
2645 // TODO: This should probably only loop over the task since you need to be in the
2646 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002647 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002648 c.recycle();
2649
2650 updateOomAdj();
2651 } finally {
2652 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002653 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002654 }
2655 }
2656
2657 @Override
2658 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002659 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002660 ActivityStack stack = ActivityRecord.getStackLocked(token);
2661 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002662 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002663 }
2664 return false;
2665 }
2666 }
2667
2668 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002669 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002670 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002671 synchronized (mGlobalLock) {
2672 final long ident = Binder.clearCallingIdentity();
2673 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002674 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002675 if (task == null) {
2676 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2677 return;
2678 }
2679
2680 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2681 + " to stackId=" + stackId + " toTop=" + toTop);
2682
Louis Chang149d5c82019-12-30 09:47:39 +08002683 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002684 if (stack == null) {
2685 throw new IllegalStateException(
2686 "moveTaskToStack: No stack for stackId=" + stackId);
2687 }
2688 if (!stack.isActivityTypeStandardOrUndefined()) {
2689 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2690 + taskId + " to stack " + stackId);
2691 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002692 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2693 "moveTaskToStack");
2694 } finally {
2695 Binder.restoreCallingIdentity(ident);
2696 }
2697 }
2698 }
2699
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002700 /**
2701 * Moves the specified task to the primary-split-screen stack.
2702 *
2703 * @param taskId Id of task to move.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002704 * @param toTop If the task and stack should be moved to the top.
Winson Chung7ccc6812020-01-23 16:15:10 -08002705 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002706 */
2707 @Override
Evan Rosky73a7fe92019-11-18 18:28:01 -08002708 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002709 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002710 "setTaskWindowingModeSplitScreenPrimary()");
2711 synchronized (mGlobalLock) {
2712 final long ident = Binder.clearCallingIdentity();
2713 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002714 return setTaskWindowingModeSplitScreen(taskId, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY,
2715 toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002716 } finally {
2717 Binder.restoreCallingIdentity(ident);
2718 }
2719 }
2720 }
2721
2722 /**
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002723 * Moves the specified task into a split-screen tile.
2724 */
2725 private boolean setTaskWindowingModeSplitScreen(int taskId, int windowingMode, boolean toTop) {
2726 if (!WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2727 throw new IllegalArgumentException("Calling setTaskWindowingModeSplitScreen with non"
2728 + "split-screen mode: " + windowingMode);
2729 }
2730 if (isInLockTaskMode()) {
2731 Slog.w(TAG, "setTaskWindowingModeSplitScreen: Is in lock task mode="
2732 + getLockTaskModeState());
2733 return false;
2734 }
2735
2736 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2737 MATCH_TASK_IN_STACKS_ONLY);
2738 if (task == null) {
2739 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2740 return false;
2741 }
2742 if (!task.isActivityTypeStandardOrUndefined()) {
2743 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2744 + " non-standard task " + taskId + " to split-screen windowing mode");
2745 }
Wale Ogunwale0d465192020-01-23 19:14:44 -08002746 if (!task.supportsSplitScreenWindowingMode()) {
2747 return false;
2748 }
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002749
2750 final int prevMode = task.getWindowingMode();
Wale Ogunwale0d465192020-01-23 19:14:44 -08002751 moveTaskToSplitScreenPrimaryTile(task, toTop);
2752 return prevMode != task.getWindowingMode();
2753 }
2754
2755 void moveTaskToSplitScreenPrimaryTile(Task task, boolean toTop) {
2756 ActivityStack stack = task.getStack();
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002757 TaskTile tile = null;
2758 for (int i = stack.getDisplay().getStackCount() - 1; i >= 0; --i) {
2759 tile = stack.getDisplay().getStackAt(i).asTile();
2760 if (tile != null && tile.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2761 break;
2762 }
2763 }
2764 if (tile == null) {
2765 throw new IllegalStateException("Can't enter split without associated tile");
2766 }
2767 WindowContainerTransaction wct = new WindowContainerTransaction();
2768 wct.reparent(stack.mRemoteToken, tile.mRemoteToken, toTop);
2769 mTaskOrganizerController.applyContainerTransaction(wct, null);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002770 }
2771
2772 /**
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002773 * Removes stacks in the input windowing modes from the system if they are of activity type
2774 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2775 */
2776 @Override
2777 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002778 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002779 "removeStacksInWindowingModes()");
2780
2781 synchronized (mGlobalLock) {
2782 final long ident = Binder.clearCallingIdentity();
2783 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002784 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002785 } finally {
2786 Binder.restoreCallingIdentity(ident);
2787 }
2788 }
2789 }
2790
2791 @Override
2792 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002793 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002794 "removeStacksWithActivityTypes()");
2795
2796 synchronized (mGlobalLock) {
2797 final long ident = Binder.clearCallingIdentity();
2798 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002799 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002800 } finally {
2801 Binder.restoreCallingIdentity(ident);
2802 }
2803 }
2804 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002805
2806 @Override
2807 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2808 int userId) {
2809 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002810 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2811 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002812 callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002813 synchronized (mGlobalLock) {
Winson Chung66b08f02020-03-03 14:32:35 -08002814 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, userId, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002815 }
2816 }
2817
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002818 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002819 @Override
2820 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002821 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002822 long ident = Binder.clearCallingIdentity();
2823 try {
2824 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002825 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 }
2827 } finally {
2828 Binder.restoreCallingIdentity(ident);
2829 }
2830 }
2831
2832 @Override
2833 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002834 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002835 long ident = Binder.clearCallingIdentity();
2836 try {
2837 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002838 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002839 }
2840 } finally {
2841 Binder.restoreCallingIdentity(ident);
2842 }
2843 }
2844
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002845 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002846 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002847 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2848 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2849 long ident = Binder.clearCallingIdentity();
2850 try {
2851 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002852 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002853 }
2854 } finally {
2855 Binder.restoreCallingIdentity(ident);
2856 }
2857 }
2858
2859 @Override
2860 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2861 int displayId) {
2862 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2863 long ident = Binder.clearCallingIdentity();
2864 try {
2865 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002866 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002867 }
2868 } finally {
2869 Binder.restoreCallingIdentity(ident);
2870 }
2871 }
2872
2873 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002874 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002875 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002876 final long callingUid = Binder.getCallingUid();
2877 final long origId = Binder.clearCallingIdentity();
2878 try {
2879 synchronized (mGlobalLock) {
2880 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002881 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002882 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2883 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2884 }
2885 } finally {
2886 Binder.restoreCallingIdentity(origId);
2887 }
2888 }
2889
2890 @Override
2891 public void startLockTaskModeByToken(IBinder token) {
2892 synchronized (mGlobalLock) {
2893 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2894 if (r == null) {
2895 return;
2896 }
Louis Changcdec0802019-11-11 11:45:07 +08002897 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002898 }
2899 }
2900
2901 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002902 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002903 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002904 // This makes inner call to look as if it was initiated by system.
2905 long ident = Binder.clearCallingIdentity();
2906 try {
2907 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002908 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002909 MATCH_TASK_IN_STACKS_ONLY);
2910 if (task == null) {
2911 return;
2912 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002913
2914 // When starting lock task mode the stack must be in front and focused
2915 task.getStack().moveToFront("startSystemLockTaskMode");
2916 startLockTaskModeLocked(task, true /* isSystemCaller */);
2917 }
2918 } finally {
2919 Binder.restoreCallingIdentity(ident);
2920 }
2921 }
2922
2923 @Override
2924 public void stopLockTaskModeByToken(IBinder token) {
2925 synchronized (mGlobalLock) {
2926 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2927 if (r == null) {
2928 return;
2929 }
Louis Changcdec0802019-11-11 11:45:07 +08002930 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002931 }
2932 }
2933
2934 /**
2935 * This API should be called by SystemUI only when user perform certain action to dismiss
2936 * lock task mode. We should only dismiss pinned lock task mode in this case.
2937 */
2938 @Override
2939 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002940 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002941 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2942 }
2943
Louis Changcdec0802019-11-11 11:45:07 +08002944 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002945 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2946 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2947 return;
2948 }
2949
Louis Chang149d5c82019-12-30 09:47:39 +08002950 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002951 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952 throw new IllegalArgumentException("Invalid task, not in foreground");
2953 }
2954
2955 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2956 // system or a specific app.
2957 // * System-initiated requests will only start the pinned mode (screen pinning)
2958 // * App-initiated requests
2959 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2960 // - will start the pinned mode, otherwise
2961 final int callingUid = Binder.getCallingUid();
2962 long ident = Binder.clearCallingIdentity();
2963 try {
2964 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002965 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002966
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002967 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002968 } finally {
2969 Binder.restoreCallingIdentity(ident);
2970 }
2971 }
2972
Louis Changcdec0802019-11-11 11:45:07 +08002973 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002974 final int callingUid = Binder.getCallingUid();
2975 long ident = Binder.clearCallingIdentity();
2976 try {
2977 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002978 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002979 }
2980 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2981 // task and jumping straight into a call in the case of emergency call back.
2982 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2983 if (tm != null) {
2984 tm.showInCallScreen(false);
2985 }
2986 } finally {
2987 Binder.restoreCallingIdentity(ident);
2988 }
2989 }
2990
2991 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002992 public void updateLockTaskPackages(int userId, String[] packages) {
2993 final int callingUid = Binder.getCallingUid();
2994 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2995 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2996 "updateLockTaskPackages()");
2997 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002998 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002999 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
3000 + Arrays.toString(packages));
3001 getLockTaskController().updateLockTaskPackages(userId, packages);
3002 }
3003 }
3004
3005 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003006 public boolean isInLockTaskMode() {
3007 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3008 }
3009
3010 @Override
3011 public int getLockTaskModeState() {
3012 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003013 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003014 }
3015 }
3016
3017 @Override
3018 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3019 synchronized (mGlobalLock) {
3020 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3021 if (r != null) {
3022 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003023 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003024 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003025 }
3026 }
3027 }
3028
3029 @Override
3030 public Bundle getActivityOptions(IBinder token) {
3031 final long origId = Binder.clearCallingIdentity();
3032 try {
3033 synchronized (mGlobalLock) {
3034 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3035 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003036 final ActivityOptions activityOptions = r.takeOptionsLocked(
3037 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003038 return activityOptions == null ? null : activityOptions.toBundle();
3039 }
3040 return null;
3041 }
3042 } finally {
3043 Binder.restoreCallingIdentity(origId);
3044 }
3045 }
3046
3047 @Override
3048 public List<IBinder> getAppTasks(String callingPackage) {
3049 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003050 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003051 long ident = Binder.clearCallingIdentity();
3052 try {
3053 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003054 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003055 }
3056 } finally {
3057 Binder.restoreCallingIdentity(ident);
3058 }
3059 }
3060
3061 @Override
3062 public void finishVoiceTask(IVoiceInteractionSession session) {
3063 synchronized (mGlobalLock) {
3064 final long origId = Binder.clearCallingIdentity();
3065 try {
3066 // TODO: VI Consider treating local voice interactions and voice tasks
3067 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003068 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003069 } finally {
3070 Binder.restoreCallingIdentity(origId);
3071 }
3072 }
3073
3074 }
3075
3076 @Override
3077 public boolean isTopOfTask(IBinder token) {
3078 synchronized (mGlobalLock) {
3079 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003080 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003081 }
3082 }
3083
3084 @Override
3085 public void notifyLaunchTaskBehindComplete(IBinder token) {
3086 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3087 }
3088
3089 @Override
3090 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003091 mH.post(() -> {
3092 synchronized (mGlobalLock) {
3093 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003094 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003095 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003096 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003097 } catch (RemoteException e) {
3098 }
3099 }
3100 }
3101
3102 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003103 }
3104
3105 /** Called from an app when assist data is ready. */
3106 @Override
3107 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3108 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003109 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003110 synchronized (pae) {
3111 pae.result = extras;
3112 pae.structure = structure;
3113 pae.content = content;
3114 if (referrer != null) {
3115 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3116 }
3117 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003118 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003119 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003120 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003121 structure.setHomeActivity(pae.isHome);
3122 }
3123 pae.haveResult = true;
3124 pae.notifyAll();
3125 if (pae.intent == null && pae.receiver == null) {
3126 // Caller is just waiting for the result.
3127 return;
3128 }
3129 }
3130 // We are now ready to launch the assist activity.
3131 IAssistDataReceiver sendReceiver = null;
3132 Bundle sendBundle = null;
3133 synchronized (mGlobalLock) {
3134 buildAssistBundleLocked(pae, extras);
3135 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003136 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003137 if (!exists) {
3138 // Timed out.
3139 return;
3140 }
3141
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003142 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003143 // Caller wants result sent back to them.
3144 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003145 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003146 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003147 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3148 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003149 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3150 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3151 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3152 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3153 }
3154 }
3155 if (sendReceiver != null) {
3156 try {
3157 sendReceiver.onHandleAssistData(sendBundle);
3158 } catch (RemoteException e) {
3159 }
3160 return;
3161 }
3162
3163 final long ident = Binder.clearCallingIdentity();
3164 try {
3165 if (TextUtils.equals(pae.intent.getAction(),
3166 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003167 // Start voice interaction through VoiceInteractionManagerService.
3168 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3169 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003170 } else {
3171 pae.intent.replaceExtras(pae.extras);
3172 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3173 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3174 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003175 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003176
3177 try {
3178 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3179 } catch (ActivityNotFoundException e) {
3180 Slog.w(TAG, "No activity to handle assist action.", e);
3181 }
3182 }
3183 } finally {
3184 Binder.restoreCallingIdentity(ident);
3185 }
3186 }
3187
3188 @Override
3189 public int addAppTask(IBinder activityToken, Intent intent,
3190 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3191 final int callingUid = Binder.getCallingUid();
3192 final long callingIdent = Binder.clearCallingIdentity();
3193
3194 try {
3195 synchronized (mGlobalLock) {
3196 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3197 if (r == null) {
3198 throw new IllegalArgumentException("Activity does not exist; token="
3199 + activityToken);
3200 }
3201 ComponentName comp = intent.getComponent();
3202 if (comp == null) {
3203 throw new IllegalArgumentException("Intent " + intent
3204 + " must specify explicit component");
3205 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003206 if (thumbnail.getWidth() != mThumbnailWidth
3207 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003208 throw new IllegalArgumentException("Bad thumbnail size: got "
3209 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003210 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003211 }
3212 if (intent.getSelector() != null) {
3213 intent.setSelector(null);
3214 }
3215 if (intent.getSourceBounds() != null) {
3216 intent.setSourceBounds(null);
3217 }
3218 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3219 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3220 // The caller has added this as an auto-remove task... that makes no
3221 // sense, so turn off auto-remove.
3222 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3223 }
3224 }
3225 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3226 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3227 if (ainfo.applicationInfo.uid != callingUid) {
3228 throw new SecurityException(
3229 "Can't add task for another application: target uid="
3230 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3231 }
3232
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003233 final ActivityStack stack = r.getRootTask();
Wale Ogunwale0d465192020-01-23 19:14:44 -08003234 final Task task = stack.getDisplay().createStack(stack.getWindowingMode(),
3235 stack.getActivityType(), !ON_TOP, ainfo, intent);
3236
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003237 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003238 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003239 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003240 return INVALID_TASK_ID;
3241 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003242 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003243
3244 // TODO: Send the thumbnail to WM to store it.
3245
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003246 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003247 }
3248 } finally {
3249 Binder.restoreCallingIdentity(callingIdent);
3250 }
3251 }
3252
3253 @Override
3254 public Point getAppTaskThumbnailSize() {
3255 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003256 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003257 }
3258 }
3259
3260 @Override
3261 public void setTaskResizeable(int taskId, int resizeableMode) {
3262 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003263 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003264 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3265 if (task == null) {
3266 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3267 return;
3268 }
3269 task.setResizeMode(resizeableMode);
3270 }
3271 }
3272
3273 @Override
3274 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003275 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003276 long ident = Binder.clearCallingIdentity();
3277 try {
3278 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003279 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003280 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003281 if (task == null) {
3282 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3283 return;
3284 }
3285 // Place the task in the right stack if it isn't there already based on
3286 // the requested bounds.
3287 // The stack transition logic is:
3288 // - a null bounds on a freeform task moves that task to fullscreen
3289 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3290 // that task to freeform
3291 // - otherwise the task is not moved
3292 ActivityStack stack = task.getStack();
3293 if (!task.getWindowConfiguration().canResizeTask()) {
3294 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3295 }
3296 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3297 stack = stack.getDisplay().getOrCreateStack(
3298 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3299 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3300 stack = stack.getDisplay().getOrCreateStack(
3301 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3302 }
3303
3304 // Reparent the task to the right stack if necessary
3305 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3306 if (stack != task.getStack()) {
3307 // Defer resume until the task is resized below
3308 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3309 DEFER_RESUME, "resizeTask");
3310 preserveWindow = false;
3311 }
3312
3313 // After reparenting (which only resizes the task to the stack bounds), resize the
3314 // task to the actual bounds provided
3315 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3316 }
3317 } finally {
3318 Binder.restoreCallingIdentity(ident);
3319 }
3320 }
3321
3322 @Override
3323 public boolean releaseActivityInstance(IBinder token) {
3324 synchronized (mGlobalLock) {
3325 final long origId = Binder.clearCallingIdentity();
3326 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003327 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3328 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003329 return false;
3330 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003331 r.destroyImmediately(true /* removeFromApp */, "app-req");
3332 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003333 } finally {
3334 Binder.restoreCallingIdentity(origId);
3335 }
3336 }
3337 }
3338
3339 @Override
3340 public void releaseSomeActivities(IApplicationThread appInt) {
3341 synchronized (mGlobalLock) {
3342 final long origId = Binder.clearCallingIdentity();
3343 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003344 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003345 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003346 } finally {
3347 Binder.restoreCallingIdentity(origId);
3348 }
3349 }
3350 }
3351
3352 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003353 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003354 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003355 != PackageManager.PERMISSION_GRANTED) {
3356 throw new SecurityException("Requires permission "
3357 + android.Manifest.permission.DEVICE_POWER);
3358 }
3359
3360 synchronized (mGlobalLock) {
3361 long ident = Binder.clearCallingIdentity();
3362 if (mKeyguardShown != keyguardShowing) {
3363 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003364 final Message msg = PooledLambda.obtainMessage(
3365 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3366 keyguardShowing);
3367 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003368 }
3369 try {
wilsonshih177261f2019-02-22 12:02:18 +08003370 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003371 } finally {
3372 Binder.restoreCallingIdentity(ident);
3373 }
3374 }
3375
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003376 mH.post(() -> {
3377 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3378 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3379 }
3380 });
3381 }
3382
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003383 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003384 mH.post(() -> {
3385 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3386 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3387 }
3388 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003389 }
3390
3391 @Override
3392 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003393 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3394 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003395
3396 final File passedIconFile = new File(filePath);
3397 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3398 passedIconFile.getName());
3399 if (!legitIconFile.getPath().equals(filePath)
3400 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3401 throw new IllegalArgumentException("Bad file path: " + filePath
3402 + " passed for userId " + userId);
3403 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003404 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003405 }
3406
3407 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003408 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003409 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003410 synchronized (mGlobalLock) {
3411 final long ident = Binder.clearCallingIdentity();
3412 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003413 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003414 if (stack == null) {
3415 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3416 return;
3417 }
3418 if (!stack.isActivityTypeStandardOrUndefined()) {
3419 throw new IllegalArgumentException(
3420 "Removing non-standard stack is not allowed.");
3421 }
3422 mStackSupervisor.removeStack(stack);
3423 } finally {
3424 Binder.restoreCallingIdentity(ident);
3425 }
3426 }
3427 }
3428
3429 @Override
3430 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003431 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003432
3433 synchronized (mGlobalLock) {
3434 final long ident = Binder.clearCallingIdentity();
3435 try {
3436 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3437 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003438 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003439 } finally {
3440 Binder.restoreCallingIdentity(ident);
3441 }
3442 }
3443 }
3444
3445 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003446 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003447 synchronized (mGlobalLock) {
3448 long ident = Binder.clearCallingIdentity();
3449 try {
3450 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3451 if (r == null) {
3452 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003453 "toggleFreeformWindowingMode: No activity record matching token="
3454 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003455 }
3456
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003457 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003458 if (stack == null) {
3459 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3460 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003461 }
3462
Yunfan Chend967af82019-01-17 18:30:18 +09003463 if (!stack.inFreeformWindowingMode()
3464 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3465 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3466 + "toggle between fullscreen and freeform.");
3467 }
3468
3469 if (stack.inFreeformWindowingMode()) {
3470 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003471 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003472 throw new IllegalStateException("Size-compat windows are currently not"
3473 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003474 } else if (stack.getParent().inFreeformWindowingMode()) {
3475 // If the window is on a freeform display, set it to undefined. It will be
3476 // resolved to freeform and it can adjust windowing mode when the display mode
3477 // changes in runtime.
3478 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003479 } else {
3480 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3481 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003482 } finally {
3483 Binder.restoreCallingIdentity(ident);
3484 }
3485 }
3486 }
3487
3488 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3489 @Override
3490 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003491 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003492 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003493 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003494 }
3495
3496 /** Unregister a task stack listener so that it stops receiving callbacks. */
3497 @Override
3498 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003499 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003500 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003501 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003502 }
3503
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003504 @Override
3505 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3506 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3507 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3508 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3509 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3510 }
3511
3512 @Override
3513 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3514 IBinder activityToken, int flags) {
3515 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3516 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3517 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3518 }
3519
3520 @Override
3521 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3522 Bundle args) {
3523 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3524 true /* focused */, true /* newSessionId */, userHandle, args,
3525 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3526 }
3527
3528 @Override
3529 public Bundle getAssistContextExtras(int requestType) {
3530 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3531 null, null, true /* focused */, true /* newSessionId */,
3532 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3533 if (pae == null) {
3534 return null;
3535 }
3536 synchronized (pae) {
3537 while (!pae.haveResult) {
3538 try {
3539 pae.wait();
3540 } catch (InterruptedException e) {
3541 }
3542 }
3543 }
3544 synchronized (mGlobalLock) {
3545 buildAssistBundleLocked(pae, pae.result);
3546 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003547 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003548 }
3549 return pae.extras;
3550 }
3551
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003552 /**
3553 * Binder IPC calls go through the public entry point.
3554 * This can be called with or without the global lock held.
3555 */
3556 private static int checkCallingPermission(String permission) {
3557 return checkPermission(
3558 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3559 }
3560
3561 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003562 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003563 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3564 mAmInternal.enforceCallingPermission(permission, func);
3565 }
3566 }
3567
3568 @VisibleForTesting
3569 int checkGetTasksPermission(String permission, int pid, int uid) {
3570 return checkPermission(permission, pid, uid);
3571 }
3572
3573 static int checkPermission(String permission, int pid, int uid) {
3574 if (permission == null) {
3575 return PackageManager.PERMISSION_DENIED;
3576 }
3577 return checkComponentPermission(permission, pid, uid, -1, true);
3578 }
3579
Wale Ogunwale214f3482018-10-04 11:00:47 -07003580 public static int checkComponentPermission(String permission, int pid, int uid,
3581 int owningUid, boolean exported) {
3582 return ActivityManagerService.checkComponentPermission(
3583 permission, pid, uid, owningUid, exported);
3584 }
3585
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003586 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3587 if (getRecentTasks().isCallerRecents(callingUid)) {
3588 // Always allow the recents component to get tasks
3589 return true;
3590 }
3591
3592 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3593 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3594 if (!allowed) {
3595 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3596 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3597 // Temporary compatibility: some existing apps on the system image may
3598 // still be requesting the old permission and not switched to the new
3599 // one; if so, we'll still allow them full access. This means we need
3600 // to see if they are holding the old permission and are a system app.
3601 try {
3602 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3603 allowed = true;
3604 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3605 + " is using old GET_TASKS but privileged; allowing");
3606 }
3607 } catch (RemoteException e) {
3608 }
3609 }
3610 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3611 + " does not hold REAL_GET_TASKS; limiting output");
3612 }
3613 return allowed;
3614 }
3615
Nicholas Sauer0259e532019-08-30 08:24:55 -07003616 boolean isCrossUserAllowed(int pid, int uid) {
3617 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3618 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3619 }
3620
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003621 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3622 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3623 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3624 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003625 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003626 "enqueueAssistContext()");
3627
3628 synchronized (mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08003629 final ActivityStack stack = getTopDisplayFocusedStack();
3630 ActivityRecord activity = stack != null ? stack.getTopNonFinishingActivity() : null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003631 if (activity == null) {
3632 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3633 return null;
3634 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003635 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003636 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3637 return null;
3638 }
3639 if (focused) {
3640 if (activityToken != null) {
3641 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3642 if (activity != caller) {
3643 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3644 + " is not current top " + activity);
3645 return null;
3646 }
3647 }
3648 } else {
3649 activity = ActivityRecord.forTokenLocked(activityToken);
3650 if (activity == null) {
3651 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3652 + " couldn't be found");
3653 return null;
3654 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003655 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003656 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3657 return null;
3658 }
3659 }
3660
3661 PendingAssistExtras pae;
3662 Bundle extras = new Bundle();
3663 if (args != null) {
3664 extras.putAll(args);
3665 }
3666 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003667 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003668
3669 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3670 userHandle);
3671 pae.isHome = activity.isActivityTypeHome();
3672
3673 // Increment the sessionId if necessary
3674 if (newSessionId) {
3675 mViSessionId++;
3676 }
3677 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003678 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3679 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003680 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003681 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003682 } catch (RemoteException e) {
3683 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3684 return null;
3685 }
3686 return pae;
3687 }
3688 }
3689
3690 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3691 if (result != null) {
3692 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3693 }
3694 if (pae.hint != null) {
3695 pae.extras.putBoolean(pae.hint, true);
3696 }
3697 }
3698
3699 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3700 IAssistDataReceiver receiver;
3701 synchronized (mGlobalLock) {
3702 mPendingAssistExtras.remove(pae);
3703 receiver = pae.receiver;
3704 }
3705 if (receiver != null) {
3706 // Caller wants result sent back to them.
3707 Bundle sendBundle = new Bundle();
3708 // At least return the receiver extras
3709 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3710 try {
3711 pae.receiver.onHandleAssistData(sendBundle);
3712 } catch (RemoteException e) {
3713 }
3714 }
3715 }
3716
3717 public class PendingAssistExtras extends Binder implements Runnable {
3718 public final ActivityRecord activity;
3719 public boolean isHome;
3720 public final Bundle extras;
3721 public final Intent intent;
3722 public final String hint;
3723 public final IAssistDataReceiver receiver;
3724 public final int userHandle;
3725 public boolean haveResult = false;
3726 public Bundle result = null;
3727 public AssistStructure structure = null;
3728 public AssistContent content = null;
3729 public Bundle receiverExtras;
3730
3731 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3732 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3733 int _userHandle) {
3734 activity = _activity;
3735 extras = _extras;
3736 intent = _intent;
3737 hint = _hint;
3738 receiver = _receiver;
3739 receiverExtras = _receiverExtras;
3740 userHandle = _userHandle;
3741 }
3742
3743 @Override
3744 public void run() {
3745 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3746 synchronized (this) {
3747 haveResult = true;
3748 notifyAll();
3749 }
3750 pendingAssistExtrasTimedOut(this);
3751 }
3752 }
3753
3754 @Override
3755 public boolean isAssistDataAllowedOnCurrentActivity() {
3756 int userId;
3757 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003758 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003759 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3760 return false;
3761 }
3762
Wale Ogunwale21e06482019-11-18 05:14:15 -08003763 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003764 if (activity == null) {
3765 return false;
3766 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003767 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003768 }
3769 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3770 }
3771
3772 @Override
3773 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3774 long ident = Binder.clearCallingIdentity();
3775 try {
3776 synchronized (mGlobalLock) {
3777 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003778 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003779 if (top != caller) {
3780 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3781 + " is not current top " + top);
3782 return false;
3783 }
3784 if (!top.nowVisible) {
3785 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3786 + " is not visible");
3787 return false;
3788 }
3789 }
3790 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3791 token);
3792 } finally {
3793 Binder.restoreCallingIdentity(ident);
3794 }
3795 }
3796
3797 @Override
3798 public boolean isRootVoiceInteraction(IBinder token) {
3799 synchronized (mGlobalLock) {
3800 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3801 if (r == null) {
3802 return false;
3803 }
3804 return r.rootVoiceInteraction;
3805 }
3806 }
3807
Wale Ogunwalef6733932018-06-27 05:14:34 -07003808 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3809 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3810 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3811 if (activityToCallback == null) return;
3812 activityToCallback.setVoiceSessionLocked(voiceSession);
3813
3814 // Inform the activity
3815 try {
3816 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3817 voiceInteractor);
3818 long token = Binder.clearCallingIdentity();
3819 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003820 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003821 } finally {
3822 Binder.restoreCallingIdentity(token);
3823 }
3824 // TODO: VI Should we cache the activity so that it's easier to find later
3825 // rather than scan through all the stacks and activities?
3826 } catch (RemoteException re) {
3827 activityToCallback.clearVoiceSessionLocked();
3828 // TODO: VI Should this terminate the voice session?
3829 }
3830 }
3831
3832 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3833 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3834 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3835 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3836 boolean wasRunningVoice = mRunningVoice != null;
3837 mRunningVoice = session;
3838 if (!wasRunningVoice) {
3839 mVoiceWakeLock.acquire();
3840 updateSleepIfNeededLocked();
3841 }
3842 }
3843 }
3844
3845 void finishRunningVoiceLocked() {
3846 if (mRunningVoice != null) {
3847 mRunningVoice = null;
3848 mVoiceWakeLock.release();
3849 updateSleepIfNeededLocked();
3850 }
3851 }
3852
3853 @Override
3854 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3855 synchronized (mGlobalLock) {
3856 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3857 if (keepAwake) {
3858 mVoiceWakeLock.acquire();
3859 } else {
3860 mVoiceWakeLock.release();
3861 }
3862 }
3863 }
3864 }
3865
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003866 @Override
3867 public ComponentName getActivityClassForToken(IBinder token) {
3868 synchronized (mGlobalLock) {
3869 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3870 if (r == null) {
3871 return null;
3872 }
3873 return r.intent.getComponent();
3874 }
3875 }
3876
3877 @Override
3878 public String getPackageForToken(IBinder token) {
3879 synchronized (mGlobalLock) {
3880 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3881 if (r == null) {
3882 return null;
3883 }
3884 return r.packageName;
3885 }
3886 }
3887
3888 @Override
3889 public void showLockTaskEscapeMessage(IBinder token) {
3890 synchronized (mGlobalLock) {
3891 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3892 if (r == null) {
3893 return;
3894 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003895 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003896 }
3897 }
3898
3899 @Override
3900 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003901 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003902 final long token = Binder.clearCallingIdentity();
3903 try {
3904 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003905 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003906 }
3907 } finally {
3908 Binder.restoreCallingIdentity(token);
3909 }
3910 }
3911
3912 /**
3913 * Try to place task to provided position. The final position might be different depending on
3914 * current user and stacks state. The task will be moved to target stack if it's currently in
3915 * different stack.
3916 */
3917 @Override
3918 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003919 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003920 synchronized (mGlobalLock) {
3921 long ident = Binder.clearCallingIdentity();
3922 try {
3923 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3924 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003925 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003926 if (task == null) {
3927 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3928 + taskId);
3929 }
3930
Louis Chang149d5c82019-12-30 09:47:39 +08003931 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003932
3933 if (stack == null) {
3934 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3935 + stackId);
3936 }
3937 if (!stack.isActivityTypeStandardOrUndefined()) {
3938 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3939 + " the position of task " + taskId + " in/to non-standard stack");
3940 }
3941
3942 // TODO: Have the callers of this API call a separate reparent method if that is
3943 // what they intended to do vs. having this method also do reparenting.
3944 if (task.getStack() == stack) {
3945 // Change position in current stack.
3946 stack.positionChildAt(task, position);
3947 } else {
3948 // Reparent to new stack.
3949 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3950 !DEFER_RESUME, "positionTaskInStack");
3951 }
3952 } finally {
3953 Binder.restoreCallingIdentity(ident);
3954 }
3955 }
3956 }
3957
3958 @Override
3959 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3960 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3961 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003962 + Arrays.toString(horizontalSizeConfiguration) + " "
3963 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003964 synchronized (mGlobalLock) {
3965 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3966 if (record == null) {
3967 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3968 + "found for: " + token);
3969 }
3970 record.setSizeConfigurations(horizontalSizeConfiguration,
3971 verticalSizeConfigurations, smallestSizeConfigurations);
3972 }
3973 }
3974
3975 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003976 * Dismisses Pip
3977 * @param animate True if the dismissal should be animated.
3978 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3979 * default animation duration should be used.
3980 */
3981 @Override
3982 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003983 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003984 final long ident = Binder.clearCallingIdentity();
3985 try {
3986 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003987 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08003988 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003989 if (stack == null) {
3990 Slog.w(TAG, "dismissPip: pinned stack not found.");
3991 return;
3992 }
3993 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3994 throw new IllegalArgumentException("Stack: " + stack
3995 + " doesn't support animated resize.");
3996 }
Hongwei Wang85cf41f2020-01-15 15:14:47 -08003997 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003998 }
3999 } finally {
4000 Binder.restoreCallingIdentity(ident);
4001 }
4002 }
4003
4004 @Override
4005 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004006 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004007 synchronized (mGlobalLock) {
4008 mSuppressResizeConfigChanges = suppress;
4009 }
4010 }
4011
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004012 @Override
4013 // TODO: API should just be about changing windowing modes...
4014 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004015 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004016 "moveTasksToFullscreenStack()");
4017 synchronized (mGlobalLock) {
4018 final long origId = Binder.clearCallingIdentity();
4019 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004020 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004021 if (stack != null){
4022 if (!stack.isActivityTypeStandardOrUndefined()) {
4023 throw new IllegalArgumentException(
4024 "You can't move tasks from non-standard stacks.");
4025 }
4026 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4027 }
4028 } finally {
4029 Binder.restoreCallingIdentity(origId);
4030 }
4031 }
4032 }
4033
4034 /**
4035 * Moves the top activity in the input stackId to the pinned stack.
4036 *
4037 * @param stackId Id of stack to move the top activity to pinned stack.
4038 * @param bounds Bounds to use for pinned stack.
4039 *
4040 * @return True if the top activity of the input stack was successfully moved to the pinned
4041 * stack.
4042 */
4043 @Override
4044 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004045 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004046 "moveTopActivityToPinnedStack()");
4047 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004048 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004049 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4050 + "Device doesn't support picture-in-picture mode");
4051 }
4052
4053 long ident = Binder.clearCallingIdentity();
4054 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004055 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004056 } finally {
4057 Binder.restoreCallingIdentity(ident);
4058 }
4059 }
4060 }
4061
4062 @Override
4063 public boolean isInMultiWindowMode(IBinder token) {
4064 final long origId = Binder.clearCallingIdentity();
4065 try {
4066 synchronized (mGlobalLock) {
4067 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4068 if (r == null) {
4069 return false;
4070 }
4071 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4072 return r.inMultiWindowMode();
4073 }
4074 } finally {
4075 Binder.restoreCallingIdentity(origId);
4076 }
4077 }
4078
4079 @Override
4080 public boolean isInPictureInPictureMode(IBinder token) {
4081 final long origId = Binder.clearCallingIdentity();
4082 try {
4083 synchronized (mGlobalLock) {
4084 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4085 }
4086 } finally {
4087 Binder.restoreCallingIdentity(origId);
4088 }
4089 }
4090
4091 private boolean isInPictureInPictureMode(ActivityRecord r) {
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004092 return r != null
4093 && r.getRootTask() != null
4094 && r.inPinnedWindowingMode()
4095 && r.getRootTask().isInStackLocked(r) != null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004096 }
4097
4098 @Override
4099 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4100 final long origId = Binder.clearCallingIdentity();
4101 try {
4102 synchronized (mGlobalLock) {
4103 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4104 "enterPictureInPictureMode", token, params);
4105
4106 // If the activity is already in picture in picture mode, then just return early
4107 if (isInPictureInPictureMode(r)) {
4108 return true;
4109 }
4110
4111 // Activity supports picture-in-picture, now check that we can enter PiP at this
4112 // point, if it is
4113 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4114 false /* beforeStopping */)) {
4115 return false;
4116 }
4117
4118 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004119 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004120 if (r.getParent() == null) {
4121 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4122 return;
4123 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004124 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004125 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004126 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4127 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4128 // Adjust the source bounds by the insets for the transition down
4129 final Rect sourceBounds = new Rect(
4130 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004131 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004132 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004133 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004134 stack.setPictureInPictureAspectRatio(aspectRatio);
4135 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004136 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4137 r.info.applicationInfo.uid, r.shortComponentName,
4138 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004139 logPictureInPictureArgs(params);
4140 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004141 };
4142
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004143 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004144 // If the keyguard is showing or occluded, then try and dismiss it before
4145 // entering picture-in-picture (this will prompt the user to authenticate if the
4146 // device is currently locked).
4147 dismissKeyguard(token, new KeyguardDismissCallback() {
4148 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004149 public void onDismissSucceeded() {
4150 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004151 }
4152 }, null /* message */);
4153 } else {
4154 // Enter picture in picture immediately otherwise
4155 enterPipRunnable.run();
4156 }
4157 return true;
4158 }
4159 } finally {
4160 Binder.restoreCallingIdentity(origId);
4161 }
4162 }
4163
4164 @Override
4165 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4166 final long origId = Binder.clearCallingIdentity();
4167 try {
4168 synchronized (mGlobalLock) {
4169 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4170 "setPictureInPictureParams", token, params);
4171
4172 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004173 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004174 if (r.inPinnedWindowingMode()) {
4175 // If the activity is already in picture-in-picture, update the pinned stack now
4176 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4177 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004178 final ActivityStack stack = r.getRootTask();
Hongwei Wang85cf41f2020-01-15 15:14:47 -08004179 stack.setPictureInPictureAspectRatio(
4180 r.pictureInPictureArgs.getAspectRatio());
4181 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004182 }
4183 logPictureInPictureArgs(params);
4184 }
4185 } finally {
4186 Binder.restoreCallingIdentity(origId);
4187 }
4188 }
4189
4190 @Override
4191 public int getMaxNumPictureInPictureActions(IBinder token) {
4192 // Currently, this is a static constant, but later, we may change this to be dependent on
4193 // the context of the activity
4194 return 3;
4195 }
4196
4197 private void logPictureInPictureArgs(PictureInPictureParams params) {
4198 if (params.hasSetActions()) {
4199 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4200 params.getActions().size());
4201 }
4202 if (params.hasSetAspectRatio()) {
4203 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4204 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4205 MetricsLogger.action(lm);
4206 }
4207 }
4208
4209 /**
4210 * Checks the state of the system and the activity associated with the given {@param token} to
4211 * verify that picture-in-picture is supported for that activity.
4212 *
4213 * @return the activity record for the given {@param token} if all the checks pass.
4214 */
4215 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4216 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004217 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004218 throw new IllegalStateException(caller
4219 + ": Device doesn't support picture-in-picture mode.");
4220 }
4221
4222 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4223 if (r == null) {
4224 throw new IllegalStateException(caller
4225 + ": Can't find activity for token=" + token);
4226 }
4227
4228 if (!r.supportsPictureInPicture()) {
4229 throw new IllegalStateException(caller
4230 + ": Current activity does not support picture-in-picture.");
4231 }
4232
4233 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004234 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004235 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004236 final float minAspectRatio = mContext.getResources().getFloat(
4237 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4238 final float maxAspectRatio = mContext.getResources().getFloat(
4239 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4240 throw new IllegalArgumentException(String.format(caller
4241 + ": Aspect ratio is too extreme (must be between %f and %f).",
4242 minAspectRatio, maxAspectRatio));
4243 }
4244
4245 // Truncate the number of actions if necessary
4246 params.truncateActions(getMaxNumPictureInPictureActions(token));
4247
4248 return r;
4249 }
4250
4251 @Override
4252 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004253 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004254 synchronized (mGlobalLock) {
4255 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4256 if (r == null) {
4257 throw new IllegalArgumentException("Activity does not exist; token="
4258 + activityToken);
4259 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004260 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004261 }
4262 }
4263
Evan Rosky73a7fe92019-11-18 18:28:01 -08004264 // TODO(b/149338177): remove when CTS no-longer requires it
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004265 @Override
4266 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4267 Rect tempDockedTaskInsetBounds,
4268 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004269 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004270 long ident = Binder.clearCallingIdentity();
4271 try {
4272 synchronized (mGlobalLock) {
Evan Rosky73a7fe92019-11-18 18:28:01 -08004273 final DisplayContent dc = mRootWindowContainer.getDefaultDisplay();
4274 TaskTile primary = null;
4275 TaskTile secondary = null;
4276 for (int i = dc.getStackCount() - 1; i >= 0; --i) {
4277 final TaskTile t = dc.getStackAt(i).asTile();
4278 if (t == null) {
4279 continue;
4280 }
4281 if (t.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
4282 primary = t;
4283 } else if (t.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY) {
4284 secondary = t;
4285 }
4286 }
4287 if (primary == null || secondary == null) {
4288 return;
4289 }
4290 final WindowContainerTransaction wct = new WindowContainerTransaction();
4291 final Rect primaryRect =
4292 tempDockedTaskInsetBounds != null ? tempDockedTaskInsetBounds
4293 : (tempDockedTaskBounds != null ? tempDockedTaskBounds
4294 : dockedBounds);
4295 wct.setBounds(primary.mRemoteToken, primaryRect);
4296 Rect otherRect = tempOtherTaskInsetBounds != null ? tempOtherTaskInsetBounds
4297 : tempOtherTaskBounds;
4298 if (otherRect == null) {
4299 // Temporary estimation... again this is just for tests.
4300 otherRect = new Rect(secondary.getBounds());
4301 if (dc.getBounds().width() > dc.getBounds().height()) {
4302 otherRect.left = primaryRect.right + 6;
4303 } else {
4304 otherRect.top = primaryRect.bottom + 6;
4305 }
4306 }
4307 wct.setBounds(secondary.mRemoteToken, otherRect);
4308 mTaskOrganizerController.applyContainerTransaction(wct, null /* organizer */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004309 }
4310 } finally {
4311 Binder.restoreCallingIdentity(ident);
4312 }
4313 }
4314
4315 @Override
4316 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004317 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004318 final long ident = Binder.clearCallingIdentity();
4319 try {
4320 synchronized (mGlobalLock) {
4321 mStackSupervisor.setSplitScreenResizing(resizing);
4322 }
4323 } finally {
4324 Binder.restoreCallingIdentity(ident);
4325 }
4326 }
4327
Evan Rosky0037e5f2019-11-05 10:26:24 -08004328 @Override
4329 public ITaskOrganizerController getTaskOrganizerController() {
4330 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
4331 "getTaskOrganizerController()");
4332 return mTaskOrganizerController;
4333 }
4334
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004335 /**
4336 * Check that we have the features required for VR-related API calls, and throw an exception if
4337 * not.
4338 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004339 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004340 if (!mContext.getPackageManager().hasSystemFeature(
4341 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4342 throw new UnsupportedOperationException("VR mode not supported on this device!");
4343 }
4344 }
4345
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004346 @Override
4347 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004348 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004349
4350 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4351
4352 ActivityRecord r;
4353 synchronized (mGlobalLock) {
4354 r = ActivityRecord.isInStackLocked(token);
4355 }
4356
4357 if (r == null) {
4358 throw new IllegalArgumentException();
4359 }
4360
4361 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004362 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004363 VrManagerInternal.NO_ERROR) {
4364 return err;
4365 }
4366
4367 // Clear the binder calling uid since this path may call moveToTask().
4368 final long callingId = Binder.clearCallingIdentity();
4369 try {
4370 synchronized (mGlobalLock) {
4371 r.requestedVrComponent = (enabled) ? packageName : null;
4372
4373 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004374 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004375 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004376 }
4377 return 0;
4378 }
4379 } finally {
4380 Binder.restoreCallingIdentity(callingId);
4381 }
4382 }
4383
4384 @Override
4385 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4386 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4387 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004388 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004389 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4390 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4391 }
Louis Changcdec0802019-11-11 11:45:07 +08004392 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004393 || activity.voiceSession != null) {
4394 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4395 return;
4396 }
4397 if (activity.pendingVoiceInteractionStart) {
4398 Slog.w(TAG, "Pending start of voice interaction already.");
4399 return;
4400 }
4401 activity.pendingVoiceInteractionStart = true;
4402 }
4403 LocalServices.getService(VoiceInteractionManagerInternal.class)
4404 .startLocalVoiceInteraction(callingActivity, options);
4405 }
4406
4407 @Override
4408 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4409 LocalServices.getService(VoiceInteractionManagerInternal.class)
4410 .stopLocalVoiceInteraction(callingActivity);
4411 }
4412
4413 @Override
4414 public boolean supportsLocalVoiceInteraction() {
4415 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4416 .supportsLocalVoiceInteraction();
4417 }
4418
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004419 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004420 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004421 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004422
4423 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004424 if (mWindowManager == null) {
4425 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4426 return false;
4427 }
4428
4429 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004430 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004431 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004432 }
4433
Riddle Hsua0022cd2019-09-09 21:12:41 +08004434 mH.sendMessage(PooledLambda.obtainMessage(
4435 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4436 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004437
4438 final long origId = Binder.clearCallingIdentity();
4439 try {
4440 if (values != null) {
4441 Settings.System.clearConfiguration(values);
4442 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004443 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444 UserHandle.USER_NULL, false /* deferResume */,
4445 mTmpUpdateConfigurationResult);
4446 return mTmpUpdateConfigurationResult.changes != 0;
4447 } finally {
4448 Binder.restoreCallingIdentity(origId);
4449 }
4450 }
4451 }
4452
4453 @Override
4454 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4455 CharSequence message) {
4456 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004457 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004458 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4459 }
4460 final long callingId = Binder.clearCallingIdentity();
4461 try {
4462 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004463 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004464 }
4465 } finally {
4466 Binder.restoreCallingIdentity(callingId);
4467 }
4468 }
4469
4470 @Override
4471 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004472 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004473 "cancelTaskWindowTransition()");
4474 final long ident = Binder.clearCallingIdentity();
4475 try {
4476 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004477 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004478 MATCH_TASK_IN_STACKS_ONLY);
4479 if (task == null) {
4480 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4481 return;
4482 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004483 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004484 }
4485 } finally {
4486 Binder.restoreCallingIdentity(ident);
4487 }
4488 }
4489
4490 @Override
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004491 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004492 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004493 final long ident = Binder.clearCallingIdentity();
4494 try {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004495 return getTaskSnapshot(taskId, isLowResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004496 } finally {
4497 Binder.restoreCallingIdentity(ident);
4498 }
4499 }
4500
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004501 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004502 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004503 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004504 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004505 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004506 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4507 if (task == null) {
4508 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4509 return null;
4510 }
4511 }
4512 // Don't call this while holding the lock as this operation might hit the disk.
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004513 return task.getSnapshot(isLowResolution, restoreFromDisk);
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004514 }
4515
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004516 @Override
4517 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4518 synchronized (mGlobalLock) {
4519 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4520 if (r == null) {
4521 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4522 + token);
4523 return;
4524 }
4525 final long origId = Binder.clearCallingIdentity();
4526 try {
4527 r.setDisablePreviewScreenshots(disable);
4528 } finally {
4529 Binder.restoreCallingIdentity(origId);
4530 }
4531 }
4532 }
4533
Riddle Hsu440f88b2019-11-06 22:17:35 +08004534 @Override
4535 public void invalidateHomeTaskSnapshot(IBinder token) {
4536 synchronized (mGlobalLock) {
4537 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4538 if (r == null || !r.isActivityTypeHome()) {
4539 return;
4540 }
4541 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4542 }
4543 }
4544
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004545 /** Return the user id of the last resumed activity. */
4546 @Override
4547 public @UserIdInt
4548 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004549 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004550 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4551 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004552 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004553 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004554 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004555 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004556 }
4557 }
4558
4559 @Override
4560 public void updateLockTaskFeatures(int userId, int flags) {
4561 final int callingUid = Binder.getCallingUid();
4562 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004563 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004564 "updateLockTaskFeatures()");
4565 }
4566 synchronized (mGlobalLock) {
4567 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4568 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004569 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004570 }
4571 }
4572
4573 @Override
4574 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4575 synchronized (mGlobalLock) {
4576 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4577 if (r == null) {
4578 return;
4579 }
4580 final long origId = Binder.clearCallingIdentity();
4581 try {
4582 r.setShowWhenLocked(showWhenLocked);
4583 } finally {
4584 Binder.restoreCallingIdentity(origId);
4585 }
4586 }
4587 }
4588
4589 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004590 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4591 synchronized (mGlobalLock) {
4592 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4593 if (r == null) {
4594 return;
4595 }
4596 final long origId = Binder.clearCallingIdentity();
4597 try {
4598 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4599 } finally {
4600 Binder.restoreCallingIdentity(origId);
4601 }
4602 }
4603 }
4604
4605 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004606 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4607 synchronized (mGlobalLock) {
4608 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4609 if (r == null) {
4610 return;
4611 }
4612 final long origId = Binder.clearCallingIdentity();
4613 try {
4614 r.setTurnScreenOn(turnScreenOn);
4615 } finally {
4616 Binder.restoreCallingIdentity(origId);
4617 }
4618 }
4619 }
4620
4621 @Override
4622 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004623 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004624 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004625 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004626 synchronized (mGlobalLock) {
4627 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4628 if (r == null) {
4629 return;
4630 }
4631 final long origId = Binder.clearCallingIdentity();
4632 try {
4633 r.registerRemoteAnimations(definition);
4634 } finally {
4635 Binder.restoreCallingIdentity(origId);
4636 }
4637 }
4638 }
4639
4640 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004641 public void unregisterRemoteAnimations(IBinder token) {
4642 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4643 "unregisterRemoteAnimations");
4644 synchronized (mGlobalLock) {
4645 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4646 if (r == null) {
4647 return;
4648 }
4649 final long origId = Binder.clearCallingIdentity();
4650 try {
4651 r.unregisterRemoteAnimations();
4652 } finally {
4653 Binder.restoreCallingIdentity(origId);
4654 }
4655 }
4656 }
4657
4658 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004659 public void registerRemoteAnimationForNextActivityStart(String packageName,
4660 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004661 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004662 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004663 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004664 synchronized (mGlobalLock) {
4665 final long origId = Binder.clearCallingIdentity();
4666 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004667 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004668 packageName, adapter);
4669 } finally {
4670 Binder.restoreCallingIdentity(origId);
4671 }
4672 }
4673 }
4674
Evan Rosky966759f2019-01-15 10:33:58 -08004675 @Override
4676 public void registerRemoteAnimationsForDisplay(int displayId,
4677 RemoteAnimationDefinition definition) {
4678 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4679 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004680 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004681 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004682 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004683 if (display == null) {
4684 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4685 return;
4686 }
4687 final long origId = Binder.clearCallingIdentity();
4688 try {
4689 display.mDisplayContent.registerRemoteAnimations(definition);
4690 } finally {
4691 Binder.restoreCallingIdentity(origId);
4692 }
4693 }
4694 }
4695
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004696 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4697 @Override
4698 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4699 synchronized (mGlobalLock) {
4700 final long origId = Binder.clearCallingIdentity();
4701 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004702 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004703 } finally {
4704 Binder.restoreCallingIdentity(origId);
4705 }
4706 }
4707 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004708
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004709 @Override
4710 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004711 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004712 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004713 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004714 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004715 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004716 }
4717 }
4718
4719 @Override
4720 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004721 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004722 != PERMISSION_GRANTED) {
4723 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4724 + Binder.getCallingPid()
4725 + ", uid=" + Binder.getCallingUid()
4726 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4727 Slog.w(TAG, msg);
4728 throw new SecurityException(msg);
4729 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004730 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004731 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004732 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004733 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004734 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004735 }
4736 }
4737
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004738 @Override
4739 public void stopAppSwitches() {
4740 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4741 synchronized (mGlobalLock) {
4742 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004743 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004744 mDidAppSwitch = false;
4745 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4746 }
4747 }
4748
4749 @Override
4750 public void resumeAppSwitches() {
4751 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4752 synchronized (mGlobalLock) {
4753 // Note that we don't execute any pending app switches... we will
4754 // let those wait until either the timeout, or the next start
4755 // activity request.
4756 mAppSwitchesAllowedTime = 0;
4757 }
4758 }
4759
Ricky Wai906af482019-06-03 17:25:28 +01004760 long getLastStopAppSwitchesTime() {
4761 return mLastStopAppSwitchesTime;
4762 }
4763
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004764 void onStartActivitySetDidAppSwitch() {
4765 if (mDidAppSwitch) {
4766 // This is the second allowed switch since we stopped switches, so now just generally
4767 // allow switches. Use case:
4768 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4769 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4770 // anyone to switch again).
4771 mAppSwitchesAllowedTime = 0;
4772 } else {
4773 mDidAppSwitch = true;
4774 }
4775 }
4776
4777 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004778 boolean shouldDisableNonVrUiLocked() {
4779 return mVrController.shouldDisableNonVrUiLocked();
4780 }
4781
Wale Ogunwale53783742018-09-16 10:21:51 -07004782 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004783 // 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 +00004784 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004785 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004786 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4787 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004788 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004789 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004790 }
4791 mH.post(() -> {
4792 if (!mVrController.onVrModeChanged(r)) {
4793 return;
4794 }
4795 synchronized (mGlobalLock) {
4796 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4797 mWindowManager.disableNonVrUi(disableNonVrUi);
4798 if (disableNonVrUi) {
4799 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4800 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004801 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004802 }
4803 }
4804 });
4805 }
4806
Wale Ogunwale53783742018-09-16 10:21:51 -07004807 @Override
4808 public int getPackageScreenCompatMode(String packageName) {
4809 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4810 synchronized (mGlobalLock) {
4811 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4812 }
4813 }
4814
4815 @Override
4816 public void setPackageScreenCompatMode(String packageName, int mode) {
4817 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4818 "setPackageScreenCompatMode");
4819 synchronized (mGlobalLock) {
4820 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4821 }
4822 }
4823
4824 @Override
4825 public boolean getPackageAskScreenCompat(String packageName) {
4826 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4827 synchronized (mGlobalLock) {
4828 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4829 }
4830 }
4831
4832 @Override
4833 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4834 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4835 "setPackageAskScreenCompat");
4836 synchronized (mGlobalLock) {
4837 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4838 }
4839 }
4840
Wale Ogunwale64258362018-10-16 15:13:37 -07004841 public static String relaunchReasonToString(int relaunchReason) {
4842 switch (relaunchReason) {
4843 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4844 return "window_resize";
4845 case RELAUNCH_REASON_FREE_RESIZE:
4846 return "free_resize";
4847 default:
4848 return null;
4849 }
4850 }
4851
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004852 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004853 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004854 }
4855
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004856 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004857 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004858 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4859 }
4860
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004861 boolean isKeyguardLocked() {
4862 return mKeyguardController.isKeyguardLocked();
4863 }
4864
Garfield Tan01548632018-11-27 10:15:48 -08004865 /**
4866 * Clears launch params for the given package.
4867 * @param packageNames the names of the packages of which the launch params are to be cleared
4868 */
4869 @Override
4870 public void clearLaunchParamsForPackages(List<String> packageNames) {
4871 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4872 "clearLaunchParamsForPackages");
4873 synchronized (mGlobalLock) {
4874 for (int i = 0; i < packageNames.size(); ++i) {
4875 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4876 }
4877 }
4878 }
4879
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004880 /**
4881 * Makes the display with the given id a single task instance display. I.e the display can only
4882 * contain one task.
4883 */
4884 @Override
4885 public void setDisplayToSingleTaskInstance(int displayId) {
4886 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4887 "setDisplayToSingleTaskInstance");
4888 final long origId = Binder.clearCallingIdentity();
4889 try {
Louis Chang677921f2019-12-06 16:44:24 +08004890 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004891 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004892 if (display != null) {
4893 display.setDisplayToSingleTaskInstance();
4894 }
4895 } finally {
4896 Binder.restoreCallingIdentity(origId);
4897 }
4898 }
4899
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004900 /**
4901 * Requests that an activity should enter picture-in-picture mode if possible.
4902 */
4903 @Override
4904 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4905 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4906 "requestPictureInPictureMode");
4907 final long origId = Binder.clearCallingIdentity();
4908 try {
4909 synchronized (mGlobalLock) {
4910 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4911 if (activity == null) {
4912 return;
4913 }
4914
4915 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4916 "requestPictureInPictureMode", /* beforeStopping */ false);
4917 if (!canEnterPictureInPicture) {
4918 throw new IllegalStateException(
4919 "Requested PIP on an activity that doesn't support it");
4920 }
4921
4922 try {
4923 final ClientTransaction transaction = ClientTransaction.obtain(
4924 activity.app.getThread(),
4925 activity.token);
4926 transaction.addCallback(EnterPipRequestedItem.obtain());
4927 getLifecycleManager().scheduleTransaction(transaction);
4928 } catch (Exception e) {
4929 Slog.w(TAG, "Failed to send enter pip requested item: "
4930 + activity.intent.getComponent(), e);
4931 }
4932 }
4933 } finally {
4934 Binder.restoreCallingIdentity(origId);
4935 }
4936 }
4937
Wale Ogunwale31913b52018-10-13 08:29:31 -07004938 void dumpLastANRLocked(PrintWriter pw) {
4939 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4940 if (mLastANRState == null) {
4941 pw.println(" <no ANR has occurred since boot>");
4942 } else {
4943 pw.println(mLastANRState);
4944 }
4945 }
4946
4947 void dumpLastANRTracesLocked(PrintWriter pw) {
4948 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4949
4950 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4951 if (ArrayUtils.isEmpty(files)) {
4952 pw.println(" <no ANR has occurred since boot>");
4953 return;
4954 }
4955 // Find the latest file.
4956 File latest = null;
4957 for (File f : files) {
4958 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4959 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004960 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004961 }
4962 pw.print("File: ");
4963 pw.print(latest.getName());
4964 pw.println();
4965 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4966 String line;
4967 while ((line = in.readLine()) != null) {
4968 pw.println(line);
4969 }
4970 } catch (IOException e) {
4971 pw.print("Unable to read: ");
4972 pw.print(e);
4973 pw.println();
4974 }
4975 }
4976
4977 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4978 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4979 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4980 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4981 }
4982
4983 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4984 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4985 pw.println(header);
4986
Louis Chang149d5c82019-12-30 09:47:39 +08004987 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004988 dumpPackage);
4989 boolean needSep = printedAnything;
4990
4991 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08004992 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004993 " ResumedActivity: ");
4994 if (printed) {
4995 printedAnything = true;
4996 needSep = false;
4997 }
4998
4999 if (dumpPackage == null) {
5000 if (needSep) {
5001 pw.println();
5002 }
5003 printedAnything = true;
5004 mStackSupervisor.dump(pw, " ");
5005 }
5006
5007 if (!printedAnything) {
5008 pw.println(" (nothing)");
5009 }
5010 }
5011
5012 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005013 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005014 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005015 pw.println(" ");
5016 }
5017
5018 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5019 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5020 getActivityStartController().dump(pw, "", dumpPackage);
5021 }
5022
5023 /**
5024 * There are three things that cmd can be:
5025 * - a flattened component name that matches an existing activity
5026 * - the cmd arg isn't the flattened component name of an existing activity:
5027 * dump all activity whose component contains the cmd as a substring
5028 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005029 * <p>
5030 * The caller should not hold lock when calling this method because it will wait for the
5031 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005032 *
5033 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5034 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5035 */
5036 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5037 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5038 ArrayList<ActivityRecord> activities;
5039
5040 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005041 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005042 dumpFocusedStackOnly);
5043 }
5044
5045 if (activities.size() <= 0) {
5046 return false;
5047 }
5048
5049 String[] newArgs = new String[args.length - opti];
5050 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5051
Louis Changcdec0802019-11-11 11:45:07 +08005052 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005053 boolean needSep = false;
5054 for (int i = activities.size() - 1; i >= 0; i--) {
5055 ActivityRecord r = activities.get(i);
5056 if (needSep) {
5057 pw.println();
5058 }
5059 needSep = true;
5060 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005061 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005062 if (lastTask != task) {
5063 lastTask = task;
5064 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005065 pw.print(" id="); pw.print(lastTask.mTaskId);
5066 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005067 if (dumpAll) {
5068 lastTask.dump(pw, " ");
5069 }
5070 }
5071 }
5072 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5073 }
5074 return true;
5075 }
5076
5077 /**
5078 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5079 * there is a thread associated with the activity.
5080 */
5081 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5082 final ActivityRecord r, String[] args, boolean dumpAll) {
5083 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005084 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005085 synchronized (mGlobalLock) {
5086 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5087 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5088 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005089 if (r.hasProcess()) {
5090 pw.println(r.app.getPid());
5091 appThread = r.app.getThread();
5092 } else {
5093 pw.println("(not running)");
5094 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005095 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005096 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005097 }
5098 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005099 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005100 // flush anything that is already in the PrintWriter since the thread is going
5101 // to write to the file descriptor directly
5102 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005103 try (TransferPipe tp = new TransferPipe()) {
5104 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5105 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005106 } catch (IOException e) {
5107 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5108 } catch (RemoteException e) {
5109 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5110 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005111 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005112 }
5113
sanryhuang498e77e2018-12-06 14:57:01 +08005114 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5115 boolean testPssMode) {
5116 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5117 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5118 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005119 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005120 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5121 st.toString());
5122 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005123 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5124 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5125 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005126 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5127 testPssMode);
5128 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005129 }
5130
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005131 int getCurrentUserId() {
5132 return mAmInternal.getCurrentUserId();
5133 }
5134
5135 private void enforceNotIsolatedCaller(String caller) {
5136 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5137 throw new SecurityException("Isolated process not allowed to call " + caller);
5138 }
5139 }
5140
Wale Ogunwalef6733932018-06-27 05:14:34 -07005141 public Configuration getConfiguration() {
5142 Configuration ci;
5143 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005144 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005145 ci.userSetLocale = false;
5146 }
5147 return ci;
5148 }
5149
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005150 /**
5151 * Current global configuration information. Contains general settings for the entire system,
5152 * also corresponds to the merged configuration of the default display.
5153 */
5154 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005155 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005156 // while initializing process record for system, see {@link
5157 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005158 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005159 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005160 }
5161
5162 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5163 boolean initLocale) {
5164 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5165 }
5166
5167 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5168 boolean initLocale, boolean deferResume) {
5169 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5170 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5171 UserHandle.USER_NULL, deferResume);
5172 }
5173
Wale Ogunwale59507092018-10-29 09:00:30 -07005174 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005175 final long origId = Binder.clearCallingIdentity();
5176 try {
5177 synchronized (mGlobalLock) {
5178 updateConfigurationLocked(values, null, false, true, userId,
5179 false /* deferResume */);
5180 }
5181 } finally {
5182 Binder.restoreCallingIdentity(origId);
5183 }
5184 }
5185
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005186 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5187 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5188 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5189 deferResume, null /* result */);
5190 }
5191
5192 /**
5193 * Do either or both things: (1) change the current configuration, and (2)
5194 * make sure the given activity is running with the (now) current
5195 * configuration. Returns true if the activity has been left running, or
5196 * false if <var>starting</var> is being destroyed to match the new
5197 * configuration.
5198 *
5199 * @param userId is only used when persistent parameter is set to true to persist configuration
5200 * for that particular user
5201 */
5202 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5203 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5204 ActivityTaskManagerService.UpdateConfigurationResult result) {
5205 int changes = 0;
5206 boolean kept = true;
5207
Riddle Hsua0022cd2019-09-09 21:12:41 +08005208 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005209 try {
5210 if (values != null) {
5211 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5212 deferResume);
5213 }
5214
5215 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5216 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005217 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005218 }
5219
5220 if (result != null) {
5221 result.changes = changes;
5222 result.activityRelaunched = !kept;
5223 }
5224 return kept;
5225 }
5226
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005227 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005228 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005229 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005230
Louis Chang677921f2019-12-06 16:44:24 +08005231 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005232 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005233
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005234 mTempConfig.setTo(getGlobalConfiguration());
5235 final int changes = mTempConfig.updateFrom(values);
5236 if (changes == 0) {
5237 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5238 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5239 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5240 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005241 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005242 return 0;
5243 }
5244
5245 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5246 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005247 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005248 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005249 values.colorMode,
5250 values.densityDpi,
5251 values.fontScale,
5252 values.hardKeyboardHidden,
5253 values.keyboard,
5254 values.keyboardHidden,
5255 values.mcc,
5256 values.mnc,
5257 values.navigation,
5258 values.navigationHidden,
5259 values.orientation,
5260 values.screenHeightDp,
5261 values.screenLayout,
5262 values.screenWidthDp,
5263 values.smallestScreenWidthDp,
5264 values.touchscreen,
5265 values.uiMode);
5266
5267
5268 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5269 final LocaleList locales = values.getLocales();
5270 int bestLocaleIndex = 0;
5271 if (locales.size() > 1) {
5272 if (mSupportedSystemLocales == null) {
5273 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5274 }
5275 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5276 }
5277 SystemProperties.set("persist.sys.locale",
5278 locales.get(bestLocaleIndex).toLanguageTag());
5279 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005280
5281 final Message m = PooledLambda.obtainMessage(
5282 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5283 locales.get(bestLocaleIndex));
5284 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005285 }
5286
Yunfan Chen75157d72018-07-27 14:47:21 +09005287 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005288
5289 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005290 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005291
5292 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5293 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005294 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005295
5296 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005297 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005298
5299 AttributeCache ac = AttributeCache.instance();
5300 if (ac != null) {
5301 ac.updateConfiguration(mTempConfig);
5302 }
5303
5304 // Make sure all resources in our process are updated right now, so that anyone who is going
5305 // to retrieve resource values after we return will be sure to get the new ones. This is
5306 // especially important during boot, where the first config change needs to guarantee all
5307 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005308 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005309
5310 // We need another copy of global config because we're scheduling some calls instead of
5311 // running them in place. We need to be sure that object we send will be handled unchanged.
5312 final Configuration configCopy = new Configuration(mTempConfig);
5313 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005314 final Message msg = PooledLambda.obtainMessage(
5315 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5316 this, userId, configCopy);
5317 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005318 }
5319
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005320 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5321 for (int i = pidMap.size() - 1; i >= 0; i--) {
5322 final int pid = pidMap.keyAt(i);
5323 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005324 if (DEBUG_CONFIGURATION) {
5325 Slog.v(TAG_CONFIGURATION, "Update process config of "
5326 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005327 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005328 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005329 }
5330
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005331 final Message msg = PooledLambda.obtainMessage(
5332 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5333 mAmInternal, changes, initLocale);
5334 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005335
5336 // Override configuration of the default display duplicates global config, so we need to
5337 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005338 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005339 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005340
5341 return changes;
5342 }
5343
Riddle Hsua0022cd2019-09-09 21:12:41 +08005344 /** @see WindowSurfacePlacer#deferLayout */
5345 void deferWindowLayout() {
5346 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5347 // Reset the reasons at the first entrance because we only care about the changes in the
5348 // deferred scope.
5349 mLayoutReasons = 0;
5350 }
5351
5352 mWindowManager.mWindowPlacerLocked.deferLayout();
5353 }
5354
5355 /** @see WindowSurfacePlacer#continueLayout */
5356 void continueWindowLayout() {
5357 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5358 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5359 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5360 }
5361 }
5362
5363 /**
5364 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5365 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5366 * defer count is gone.
5367 */
5368 void addWindowLayoutReasons(@LayoutReason int reasons) {
5369 mLayoutReasons |= reasons;
5370 }
5371
Wale Ogunwalef6733932018-06-27 05:14:34 -07005372 private void updateEventDispatchingLocked(boolean booted) {
5373 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5374 }
5375
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005376 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5377 final ContentResolver resolver = mContext.getContentResolver();
5378 Settings.System.putConfigurationForUser(resolver, config, userId);
5379 }
5380
5381 private void sendLocaleToMountDaemonMsg(Locale l) {
5382 try {
5383 IBinder service = ServiceManager.getService("mount");
5384 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5385 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5386 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5387 } catch (RemoteException e) {
5388 Log.e(TAG, "Error storing locale for decryption UI", e);
5389 }
5390 }
5391
Alison Cichowlas3e340502018-08-07 17:15:01 -04005392 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5393 mStartActivitySources.remove(permissionToken);
5394 mExpiredStartAsCallerTokens.add(permissionToken);
5395 }
5396
5397 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5398 mExpiredStartAsCallerTokens.remove(permissionToken);
5399 }
5400
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005401 boolean isActivityStartsLoggingEnabled() {
5402 return mAmInternal.isActivityStartsLoggingEnabled();
5403 }
5404
Michal Karpinski8596ded2018-11-14 14:43:48 +00005405 boolean isBackgroundActivityStartsEnabled() {
5406 return mAmInternal.isBackgroundActivityStartsEnabled();
5407 }
5408
Wale Ogunwalef6733932018-06-27 05:14:34 -07005409 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005410 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005411 mWindowManager.enableScreenAfterBoot();
5412
5413 synchronized (mGlobalLock) {
5414 updateEventDispatchingLocked(booted);
5415 }
5416 }
5417
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005418 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5419 if (r == null || !r.hasProcess()) {
5420 return KEY_DISPATCHING_TIMEOUT_MS;
5421 }
5422 return getInputDispatchingTimeoutLocked(r.app);
5423 }
5424
5425 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005426 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005427 }
5428
Wale Ogunwalef6733932018-06-27 05:14:34 -07005429 /**
5430 * Decide based on the configuration whether we should show the ANR,
5431 * crash, etc dialogs. The idea is that if there is no affordance to
5432 * press the on-screen buttons, or the user experience would be more
5433 * greatly impacted than the crash itself, we shouldn't show the dialog.
5434 *
5435 * A thought: SystemUI might also want to get told about this, the Power
5436 * dialog / global actions also might want different behaviors.
5437 */
5438 private void updateShouldShowDialogsLocked(Configuration config) {
5439 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5440 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5441 && config.navigation == Configuration.NAVIGATION_NONAV);
5442 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5443 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5444 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5445 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5446 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5447 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5448 HIDE_ERROR_DIALOGS, 0) != 0;
5449 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5450 }
5451
5452 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5453 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5454 FONT_SCALE, 1.0f, userId);
5455
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005456 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005457 if (getGlobalConfiguration().fontScale == scaleFactor) {
5458 return;
5459 }
5460
5461 final Configuration configuration
5462 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5463 configuration.fontScale = scaleFactor;
5464 updatePersistentConfiguration(configuration, userId);
5465 }
5466 }
5467
5468 // Actually is sleeping or shutting down or whatever else in the future
5469 // is an inactive state.
5470 boolean isSleepingOrShuttingDownLocked() {
5471 return isSleepingLocked() || mShuttingDown;
5472 }
5473
5474 boolean isSleepingLocked() {
5475 return mSleeping;
5476 }
5477
Riddle Hsu16567132018-08-16 21:37:47 +08005478 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005479 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005480 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005481 if (task.isActivityTypeStandard()) {
5482 if (mCurAppTimeTracker != r.appTimeTracker) {
5483 // We are switching app tracking. Complete the current one.
5484 if (mCurAppTimeTracker != null) {
5485 mCurAppTimeTracker.stop();
5486 mH.obtainMessage(
5487 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005488 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005489 mCurAppTimeTracker = null;
5490 }
5491 if (r.appTimeTracker != null) {
5492 mCurAppTimeTracker = r.appTimeTracker;
5493 startTimeTrackingFocusedActivityLocked();
5494 }
5495 } else {
5496 startTimeTrackingFocusedActivityLocked();
5497 }
5498 } else {
5499 r.appTimeTracker = null;
5500 }
5501 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5502 // TODO: Probably not, because we don't want to resume voice on switching
5503 // back to this activity
5504 if (task.voiceInteractor != null) {
5505 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5506 } else {
5507 finishRunningVoiceLocked();
5508
5509 if (mLastResumedActivity != null) {
5510 final IVoiceInteractionSession session;
5511
Louis Changcdec0802019-11-11 11:45:07 +08005512 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005513 if (lastResumedActivityTask != null
5514 && lastResumedActivityTask.voiceSession != null) {
5515 session = lastResumedActivityTask.voiceSession;
5516 } else {
5517 session = mLastResumedActivity.voiceSession;
5518 }
5519
5520 if (session != null) {
5521 // We had been in a voice interaction session, but now focused has
5522 // move to something different. Just finish the session, we can't
5523 // return to it and retain the proper state and synchronization with
5524 // the voice interaction service.
5525 finishVoiceTask(session);
5526 }
5527 }
5528 }
5529
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005530 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5531 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005532 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005533 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5534
Wale Ogunwalef6733932018-06-27 05:14:34 -07005535 updateResumedAppTrace(r);
5536 mLastResumedActivity = r;
5537
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005538 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005539
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005540 if (prevTask == null || task != prevTask) {
5541 if (prevTask != null) {
5542 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5543 }
5544 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5545 }
5546
Wale Ogunwalef6733932018-06-27 05:14:34 -07005547 applyUpdateLockStateLocked(r);
5548 applyUpdateVrModeLocked(r);
5549
Jeff Changd136e772019-11-05 20:33:52 +08005550 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005551 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005552 r == null ? "NULL" : r.shortComponentName,
5553 reason);
5554 }
5555
5556 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5557 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005558 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005559 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005560 updateSleepIfNeededLocked();
5561 return token;
5562 }
5563 }
5564
5565 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005566 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005567 final boolean wasSleeping = mSleeping;
5568 boolean updateOomAdj = false;
5569
5570 if (!shouldSleep) {
5571 // If wasSleeping is true, we need to wake up activity manager state from when
5572 // we started sleeping. In either case, we need to apply the sleep tokens, which
5573 // will wake up stacks or put them to sleep as appropriate.
5574 if (wasSleeping) {
5575 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005576 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5577 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005578 startTimeTrackingFocusedActivityLocked();
5579 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005580 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005581 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5582 }
Louis Chang149d5c82019-12-30 09:47:39 +08005583 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005584 if (wasSleeping) {
5585 updateOomAdj = true;
5586 }
5587 } else if (!mSleeping && shouldSleep) {
5588 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005589 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5590 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005591 if (mCurAppTimeTracker != null) {
5592 mCurAppTimeTracker.stop();
5593 }
5594 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005595 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005596 mStackSupervisor.goingToSleepLocked();
5597 updateResumedAppTrace(null /* resumed */);
5598 updateOomAdj = true;
5599 }
5600 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005601 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005602 }
5603 }
5604
5605 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005606 mH.removeCallbacks(mUpdateOomAdjRunnable);
5607 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005608 }
5609
Wale Ogunwale53783742018-09-16 10:21:51 -07005610 void updateCpuStats() {
5611 mH.post(mAmInternal::updateCpuStats);
5612 }
5613
Hui Yu03d12402018-12-06 18:00:37 -08005614 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5615 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005616 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5617 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005618 mH.sendMessage(m);
5619 }
5620
Hui Yu03d12402018-12-06 18:00:37 -08005621 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005622 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005623 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005624 if (task != null) {
5625 final ActivityRecord rootActivity = task.getRootActivity();
5626 if (rootActivity != null) {
5627 taskRoot = rootActivity.mActivityComponent;
5628 }
5629 }
5630
Hui Yu03d12402018-12-06 18:00:37 -08005631 final Message m = PooledLambda.obtainMessage(
5632 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005633 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005634 mH.sendMessage(m);
5635 }
5636
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005637 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5638 String hostingType) {
5639 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005640 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5641 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005642 + activity.processName);
5643 }
5644 // Post message to start process to avoid possible deadlock of calling into AMS with the
5645 // ATMS lock held.
5646 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5647 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5648 isTop, hostingType, activity.intent.getComponent());
5649 mH.sendMessage(m);
5650 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005651 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005652 }
5653 }
5654
Wale Ogunwale53783742018-09-16 10:21:51 -07005655 void setBooting(boolean booting) {
5656 mAmInternal.setBooting(booting);
5657 }
5658
5659 boolean isBooting() {
5660 return mAmInternal.isBooting();
5661 }
5662
5663 void setBooted(boolean booted) {
5664 mAmInternal.setBooted(booted);
5665 }
5666
5667 boolean isBooted() {
5668 return mAmInternal.isBooted();
5669 }
5670
5671 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5672 mH.post(() -> {
5673 if (finishBooting) {
5674 mAmInternal.finishBooting();
5675 }
5676 if (enableScreen) {
5677 mInternal.enableScreenAfterBoot(isBooted());
5678 }
5679 });
5680 }
5681
5682 void setHeavyWeightProcess(ActivityRecord root) {
5683 mHeavyWeightProcess = root.app;
5684 final Message m = PooledLambda.obtainMessage(
5685 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005686 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005687 mH.sendMessage(m);
5688 }
5689
5690 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5691 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5692 return;
5693 }
5694
5695 mHeavyWeightProcess = null;
5696 final Message m = PooledLambda.obtainMessage(
5697 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5698 proc.mUserId);
5699 mH.sendMessage(m);
5700 }
5701
5702 private void cancelHeavyWeightProcessNotification(int userId) {
5703 final INotificationManager inm = NotificationManager.getService();
5704 if (inm == null) {
5705 return;
5706 }
5707 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005708 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005709 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5710 } catch (RuntimeException e) {
5711 Slog.w(TAG, "Error canceling notification for service", e);
5712 } catch (RemoteException e) {
5713 }
5714
5715 }
5716
5717 private void postHeavyWeightProcessNotification(
5718 WindowProcessController proc, Intent intent, int userId) {
5719 if (proc == null) {
5720 return;
5721 }
5722
5723 final INotificationManager inm = NotificationManager.getService();
5724 if (inm == null) {
5725 return;
5726 }
5727
5728 try {
5729 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5730 String text = mContext.getString(R.string.heavy_weight_notification,
5731 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5732 Notification notification =
5733 new Notification.Builder(context,
5734 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5735 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5736 .setWhen(0)
5737 .setOngoing(true)
5738 .setTicker(text)
5739 .setColor(mContext.getColor(
5740 com.android.internal.R.color.system_notification_accent_color))
5741 .setContentTitle(text)
5742 .setContentText(
5743 mContext.getText(R.string.heavy_weight_notification_detail))
5744 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5745 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5746 new UserHandle(userId)))
5747 .build();
5748 try {
5749 inm.enqueueNotificationWithTag("android", "android", null,
5750 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5751 } catch (RuntimeException e) {
5752 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5753 } catch (RemoteException e) {
5754 }
5755 } catch (PackageManager.NameNotFoundException e) {
5756 Slog.w(TAG, "Unable to create context for heavy notification", e);
5757 }
5758
5759 }
5760
Philip P. Moltmannee295092020-02-10 08:46:26 -08005761 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5762 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5763 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005764
5765 ActivityRecord activity = null;
5766 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5767 activity = ActivityRecord.isInStackLocked(token);
5768 if (activity == null) {
5769 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5770 return null;
5771 }
5772 if (activity.finishing) {
5773 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5774 return null;
5775 }
5776 }
5777
5778 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005779 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5780 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005781 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5782 if (noCreate) {
5783 return rec;
5784 }
5785 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5786 if (activity.pendingResults == null) {
5787 activity.pendingResults = new HashSet<>();
5788 }
5789 activity.pendingResults.add(rec.ref);
5790 }
5791 return rec;
5792 }
5793
Andrii Kulian52d255c2018-07-13 11:32:19 -07005794 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005795 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005796 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005797 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5798 mCurAppTimeTracker.start(resumedActivity.packageName);
5799 }
5800 }
5801
5802 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5803 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005804 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005805 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5806 }
5807 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005808 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005809 constructResumedTraceName(resumed.packageName), 0);
5810 }
5811 mTracedResumedActivity = resumed;
5812 }
5813
5814 private String constructResumedTraceName(String packageName) {
5815 return "focused app: " + packageName;
5816 }
5817
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005818 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005819 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005820 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005821 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005822 // mainStack is null during startup.
5823 if (mainStack != null) {
5824 if (changes != 0 && starting == null) {
5825 // If the configuration changed, and the caller is not already
5826 // in the process of starting an activity, then find the top
5827 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005828 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005829 }
5830
5831 if (starting != null) {
5832 kept = starting.ensureActivityConfiguration(changes,
5833 false /* preserveWindow */);
5834 // And we need to make sure at this point that all other activities
5835 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005836 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005837 !PRESERVE_WINDOWS);
5838 }
5839 }
5840
5841 return kept;
5842 }
5843
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005844 void scheduleAppGcsLocked() {
5845 mH.post(() -> mAmInternal.scheduleAppGcs());
5846 }
5847
Wale Ogunwale53783742018-09-16 10:21:51 -07005848 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5849 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5850 }
5851
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005852 /**
5853 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5854 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5855 * on demand.
5856 */
5857 IPackageManager getPackageManager() {
5858 return AppGlobals.getPackageManager();
5859 }
5860
5861 PackageManagerInternal getPackageManagerInternalLocked() {
5862 if (mPmInternal == null) {
5863 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5864 }
5865 return mPmInternal;
5866 }
5867
Hai Zhangf4da9be2019-05-01 13:46:06 +08005868 PermissionPolicyInternal getPermissionPolicyInternal() {
5869 if (mPermissionPolicyInternal == null) {
5870 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5871 }
5872 return mPermissionPolicyInternal;
5873 }
5874
Wale Ogunwale008163e2018-07-23 23:11:08 -07005875 AppWarnings getAppWarningsLocked() {
5876 return mAppWarnings;
5877 }
5878
Wale Ogunwale214f3482018-10-04 11:00:47 -07005879 Intent getHomeIntent() {
5880 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5881 intent.setComponent(mTopComponent);
5882 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5883 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5884 intent.addCategory(Intent.CATEGORY_HOME);
5885 }
5886 return intent;
5887 }
5888
Chilun2ef71f72018-11-16 17:57:15 +08005889 /**
5890 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5891 * activities.
5892 *
Chilun939b05c2020-02-19 14:50:59 +08005893 * @param preferredPackage Specify a preferred package name, otherwise use the package name
5894 * defined in config_secondaryHomePackage.
Chilun2ef71f72018-11-16 17:57:15 +08005895 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5896 */
5897 Intent getSecondaryHomeIntent(String preferredPackage) {
5898 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005899 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5900 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5901 if (preferredPackage == null || useSystemProvidedLauncher) {
Chilun939b05c2020-02-19 14:50:59 +08005902 // Using the package name stored in config if no preferred package name or forced.
5903 final String secondaryHomePackage = mContext.getResources().getString(
5904 com.android.internal.R.string.config_secondaryHomePackage);
5905 intent.setPackage(secondaryHomePackage);
Chilun2ef71f72018-11-16 17:57:15 +08005906 } else {
5907 intent.setPackage(preferredPackage);
5908 }
5909 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5910 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5911 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5912 }
5913 return intent;
5914 }
5915
Wale Ogunwale214f3482018-10-04 11:00:47 -07005916 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5917 if (info == null) return null;
5918 ApplicationInfo newInfo = new ApplicationInfo(info);
5919 newInfo.initForUser(userId);
5920 return newInfo;
5921 }
5922
Wale Ogunwale9c103022018-10-18 07:44:54 -07005923 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005924 if (uid == SYSTEM_UID) {
5925 // The system gets to run in any process. If there are multiple processes with the same
5926 // uid, just pick the first (this should never happen).
5927 final SparseArray<WindowProcessController> procs =
5928 mProcessNames.getMap().get(processName);
5929 if (procs == null) return null;
5930 final int procCount = procs.size();
5931 for (int i = 0; i < procCount; i++) {
5932 final int procUid = procs.keyAt(i);
5933 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5934 // Don't use an app process or different user process for system component.
5935 continue;
5936 }
5937 return procs.valueAt(i);
5938 }
5939 }
5940
5941 return mProcessNames.get(processName, uid);
5942 }
5943
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005944 WindowProcessController getProcessController(IApplicationThread thread) {
5945 if (thread == null) {
5946 return null;
5947 }
5948
5949 final IBinder threadBinder = thread.asBinder();
5950 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5951 for (int i = pmap.size()-1; i >= 0; i--) {
5952 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5953 for (int j = procs.size() - 1; j >= 0; j--) {
5954 final WindowProcessController proc = procs.valueAt(j);
5955 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5956 return proc;
5957 }
5958 }
5959 }
5960
5961 return null;
5962 }
5963
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005964 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005965 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005966 if (proc == null) return null;
5967 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5968 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005969 }
5970 return null;
5971 }
5972
Riddle Hsua0536432019-02-16 00:38:59 +08005973 int getUidState(int uid) {
5974 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005975 }
5976
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005977 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005978 // A uid is considered to be foreground if it has a visible non-toast window.
5979 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005980 }
5981
Ricky Wai96f5c352019-04-10 18:40:17 +01005982 boolean isDeviceOwner(int uid) {
5983 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005984 }
5985
Ricky Wai96f5c352019-04-10 18:40:17 +01005986 void setDeviceOwnerUid(int uid) {
5987 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005988 }
5989
Wale Ogunwale9de19442018-10-18 19:05:03 -07005990 /**
5991 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5992 * the whitelist
5993 */
5994 String getPendingTempWhitelistTagForUidLocked(int uid) {
5995 return mPendingTempWhitelist.get(uid);
5996 }
5997
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005998 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5999 if (true || Build.IS_USER) {
6000 return;
6001 }
6002
6003 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6004 StrictMode.allowThreadDiskWrites();
6005 try {
6006 File tracesDir = new File("/data/anr");
6007 File tracesFile = null;
6008 try {
6009 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6010
6011 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006012 String timeString =
6013 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6014 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006015 sb.append(": ");
6016 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6017 sb.append(" since ");
6018 sb.append(msg);
6019 FileOutputStream fos = new FileOutputStream(tracesFile);
6020 fos.write(sb.toString().getBytes());
6021 if (app == null) {
6022 fos.write("\n*** No application process!".getBytes());
6023 }
6024 fos.close();
6025 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6026 } catch (IOException e) {
6027 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6028 return;
6029 }
6030
6031 if (app != null && app.getPid() > 0) {
6032 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6033 firstPids.add(app.getPid());
6034 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6035 }
6036
6037 File lastTracesFile = null;
6038 File curTracesFile = null;
6039 for (int i=9; i>=0; i--) {
6040 String name = String.format(Locale.US, "slow%02d.txt", i);
6041 curTracesFile = new File(tracesDir, name);
6042 if (curTracesFile.exists()) {
6043 if (lastTracesFile != null) {
6044 curTracesFile.renameTo(lastTracesFile);
6045 } else {
6046 curTracesFile.delete();
6047 }
6048 }
6049 lastTracesFile = curTracesFile;
6050 }
6051 tracesFile.renameTo(curTracesFile);
6052 } finally {
6053 StrictMode.setThreadPolicy(oldPolicy);
6054 }
6055 }
6056
Michal Karpinskida34cd42019-04-02 19:46:52 +01006057 boolean isAssociatedCompanionApp(int userId, int uid) {
6058 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6059 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006060 return false;
6061 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006062 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006063 }
6064
Issei Suzuki734bc942019-06-05 13:59:52 +02006065 void notifySingleTaskDisplayEmpty(int displayId) {
6066 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6067 }
6068
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006069 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006070 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006071
6072
Wale Ogunwale98875612018-10-12 07:53:02 -07006073 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6074 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006075
Riddle Hsud93a6c42018-11-29 21:50:06 +08006076 H(Looper looper) {
6077 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006078 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006079
6080 @Override
6081 public void handleMessage(Message msg) {
6082 switch (msg.what) {
6083 case REPORT_TIME_TRACKER_MSG: {
6084 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6085 tracker.deliverResult(mContext);
6086 } break;
6087 }
6088 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006089 }
6090
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006091 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006092 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006093
6094 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006095 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006096 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006097
6098 @Override
6099 public void handleMessage(Message msg) {
6100 switch (msg.what) {
6101 case DISMISS_DIALOG_UI_MSG: {
6102 final Dialog d = (Dialog) msg.obj;
6103 d.dismiss();
6104 break;
6105 }
6106 }
6107 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006108 }
6109
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006110 final class LocalService extends ActivityTaskManagerInternal {
6111 @Override
6112 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006113 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006114 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006115 }
6116
6117 @Override
6118 public ComponentName getHomeActivityForUser(int userId) {
6119 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006120 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006121 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006122 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006123 }
6124 }
6125
6126 @Override
6127 public void onLocalVoiceInteractionStarted(IBinder activity,
6128 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6129 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006130 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006131 }
6132 }
6133
6134 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006135 public void notifySingleTaskDisplayDrawn(int displayId) {
6136 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6137 }
6138
6139 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006140 public void notifyAppTransitionFinished() {
6141 synchronized (mGlobalLock) {
6142 mStackSupervisor.notifyAppTransitionDone();
6143 }
6144 }
6145
6146 @Override
6147 public void notifyAppTransitionCancelled() {
6148 synchronized (mGlobalLock) {
6149 mStackSupervisor.notifyAppTransitionDone();
6150 }
6151 }
6152
6153 @Override
6154 public List<IBinder> getTopVisibleActivities() {
6155 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006156 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006157 }
6158 }
6159
6160 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006161 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6162 int userId, Intent[] intents, Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006163 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006164 final String[] resolvedTypes = new String[intents.length];
6165
6166 // UID of the package on user userId.
6167 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6168 // packageUid may not be initialized.
6169 int packageUid = 0;
6170 final long ident = Binder.clearCallingIdentity();
6171
6172 try {
6173 for (int i = 0; i < intents.length; i++) {
6174 resolvedTypes[i] =
6175 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6176 }
6177
6178 packageUid = AppGlobals.getPackageManager().getPackageUid(
6179 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6180 } catch (RemoteException e) {
6181 // Shouldn't happen.
6182 } finally {
6183 Binder.restoreCallingIdentity(ident);
6184 }
6185
Riddle Hsu591bf612019-02-14 17:55:31 +08006186 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006187 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006188 intents, resolvedTypes, null /* resultTo */,
6189 SafeActivityOptions.fromBundle(bOptions), userId,
6190 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6191 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006192 }
6193
6194 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006195 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006196 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6197 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6198 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006199 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006200 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006201 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006202 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006203 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6204 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006205 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006206 }
6207 }
6208
6209 @Override
6210 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006211 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6212 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6213 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6214 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006215 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006216 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006217 synchronized (mGlobalLock) {
6218 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006219 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6220 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6221 reason, validateIncomingUser, originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006222 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006223 }
6224 }
6225
6226 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006227 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006228 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6229 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006230 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006231 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006232 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006233 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006234 false /*validateIncomingUser*/);
6235 }
6236
6237 @Override
lumark588a3e82018-07-20 18:53:54 +08006238 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006239 synchronized (mGlobalLock) {
6240
6241 // We might change the visibilities here, so prepare an empty app transition which
6242 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006243 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006244 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006245 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006246 return;
6247 }
Louis Chang677921f2019-12-06 16:44:24 +08006248 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006249 final boolean wasTransitionSet =
6250 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006251 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006252 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006253 }
Louis Chang149d5c82019-12-30 09:47:39 +08006254 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006255
6256 // If there was a transition set already we don't want to interfere with it as we
6257 // might be starting it too early.
6258 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006259 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006260 }
6261 }
6262 if (callback != null) {
6263 callback.run();
6264 }
6265 }
6266
6267 @Override
6268 public void notifyKeyguardTrustedChanged() {
6269 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006270 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006271 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006272 }
6273 }
6274 }
6275
6276 /**
6277 * Called after virtual display Id is updated by
6278 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6279 * {@param vrVr2dDisplayId}.
6280 */
6281 @Override
6282 public void setVr2dDisplayId(int vr2dDisplayId) {
6283 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6284 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006285 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006286 }
6287 }
6288
6289 @Override
6290 public void setFocusedActivity(IBinder token) {
6291 synchronized (mGlobalLock) {
6292 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6293 if (r == null) {
6294 throw new IllegalArgumentException(
6295 "setFocusedActivity: No activity record matching token=" + token);
6296 }
Louis Chang19443452018-10-09 12:10:21 +08006297 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006298 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006299 }
6300 }
6301 }
6302
6303 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006304 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006305 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006306 }
6307
6308 @Override
6309 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006310 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006311 }
6312
6313 @Override
6314 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006315 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006316 }
6317
6318 @Override
6319 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6320 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6321 }
6322
6323 @Override
6324 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006325 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006326 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006327
6328 @Override
6329 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6330 synchronized (mGlobalLock) {
6331 mActiveVoiceInteractionServiceComponent = component;
6332 }
6333 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006334
6335 @Override
6336 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6337 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6338 return;
6339 }
6340 synchronized (mGlobalLock) {
6341 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6342 if (types == null) {
6343 if (uid < 0) {
6344 return;
6345 }
6346 types = new ArrayMap<>();
6347 mAllowAppSwitchUids.put(userId, types);
6348 }
6349 if (uid < 0) {
6350 types.remove(type);
6351 } else {
6352 types.put(type, uid);
6353 }
6354 }
6355 }
6356
6357 @Override
6358 public void onUserStopped(int userId) {
6359 synchronized (mGlobalLock) {
6360 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6361 mAllowAppSwitchUids.remove(userId);
6362 }
6363 }
6364
6365 @Override
6366 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6367 synchronized (mGlobalLock) {
6368 return ActivityTaskManagerService.this.isGetTasksAllowed(
6369 caller, callingPid, callingUid);
6370 }
6371 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006372
Riddle Hsua0536432019-02-16 00:38:59 +08006373 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006374 @Override
6375 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006376 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006377 mProcessNames.put(proc.mName, proc.mUid, proc);
6378 }
6379 }
6380
Riddle Hsua0536432019-02-16 00:38:59 +08006381 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006382 @Override
6383 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006384 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006385 mProcessNames.remove(name, uid);
6386 }
6387 }
6388
Riddle Hsua0536432019-02-16 00:38:59 +08006389 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006390 @Override
6391 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006392 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006393 if (proc == mHomeProcess) {
6394 mHomeProcess = null;
6395 }
6396 if (proc == mPreviousProcess) {
6397 mPreviousProcess = null;
6398 }
6399 }
6400 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006401
Riddle Hsua0536432019-02-16 00:38:59 +08006402 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006403 @Override
6404 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006405 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006406 return mTopProcessState;
6407 }
6408 }
6409
Riddle Hsua0536432019-02-16 00:38:59 +08006410 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006411 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006412 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006413 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006414 return proc == mHeavyWeightProcess;
6415 }
6416 }
6417
Riddle Hsua0536432019-02-16 00:38:59 +08006418 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006419 @Override
6420 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006421 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006422 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6423 }
6424 }
6425
6426 @Override
6427 public void finishHeavyWeightApp() {
6428 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006429 if (mHeavyWeightProcess != null) {
6430 mHeavyWeightProcess.finishActivities();
6431 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006432 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6433 mHeavyWeightProcess);
6434 }
6435 }
6436
Riddle Hsua0536432019-02-16 00:38:59 +08006437 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006438 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006439 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006440 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006441 return isSleepingLocked();
6442 }
6443 }
6444
6445 @Override
6446 public boolean isShuttingDown() {
6447 synchronized (mGlobalLock) {
6448 return mShuttingDown;
6449 }
6450 }
6451
6452 @Override
6453 public boolean shuttingDown(boolean booted, int timeout) {
6454 synchronized (mGlobalLock) {
6455 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006456 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006457 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006458 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006459 return mStackSupervisor.shutdownLocked(timeout);
6460 }
6461 }
6462
6463 @Override
6464 public void enableScreenAfterBoot(boolean booted) {
6465 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006466 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006467 mWindowManager.enableScreenAfterBoot();
6468 updateEventDispatchingLocked(booted);
6469 }
6470 }
6471
6472 @Override
6473 public boolean showStrictModeViolationDialog() {
6474 synchronized (mGlobalLock) {
6475 return mShowDialogs && !mSleeping && !mShuttingDown;
6476 }
6477 }
6478
6479 @Override
6480 public void showSystemReadyErrorDialogsIfNeeded() {
6481 synchronized (mGlobalLock) {
6482 try {
6483 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6484 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6485 + " data partition or your device will be unstable.");
6486 mUiHandler.post(() -> {
6487 if (mShowDialogs) {
6488 AlertDialog d = new BaseErrorDialog(mUiContext);
6489 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6490 d.setCancelable(false);
6491 d.setTitle(mUiContext.getText(R.string.android_system_label));
6492 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6493 d.setButton(DialogInterface.BUTTON_POSITIVE,
6494 mUiContext.getText(R.string.ok),
6495 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6496 d.show();
6497 }
6498 });
6499 }
6500 } catch (RemoteException e) {
6501 }
6502
6503 if (!Build.isBuildConsistent()) {
6504 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6505 mUiHandler.post(() -> {
6506 if (mShowDialogs) {
6507 AlertDialog d = new BaseErrorDialog(mUiContext);
6508 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6509 d.setCancelable(false);
6510 d.setTitle(mUiContext.getText(R.string.android_system_label));
6511 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6512 d.setButton(DialogInterface.BUTTON_POSITIVE,
6513 mUiContext.getText(R.string.ok),
6514 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6515 d.show();
6516 }
6517 });
6518 }
6519 }
6520 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006521
6522 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006523 public void onProcessMapped(int pid, WindowProcessController proc) {
6524 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006525 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006526 }
6527 }
6528
6529 @Override
6530 public void onProcessUnMapped(int pid) {
6531 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006532 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006533 }
6534 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006535
6536 @Override
6537 public void onPackageDataCleared(String name) {
6538 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006539 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006540 mAppWarnings.onPackageDataCleared(name);
6541 }
6542 }
6543
6544 @Override
6545 public void onPackageUninstalled(String name) {
6546 synchronized (mGlobalLock) {
6547 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006548 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006549 }
6550 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006551
6552 @Override
6553 public void onPackageAdded(String name, boolean replacing) {
6554 synchronized (mGlobalLock) {
6555 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6556 }
6557 }
6558
6559 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006560 public void onPackageReplaced(ApplicationInfo aInfo) {
6561 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006562 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006563 }
6564 }
6565
6566 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006567 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6568 synchronized (mGlobalLock) {
6569 return compatibilityInfoForPackageLocked(ai);
6570 }
6571 }
6572
Yunfan Chen75157d72018-07-27 14:47:21 +09006573 /**
6574 * Set the corresponding display information for the process global configuration. To be
6575 * called when we need to show IME on a different display.
6576 *
6577 * @param pid The process id associated with the IME window.
6578 * @param displayId The ID of the display showing the IME.
6579 */
6580 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006581 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006582 // Don't update process-level configuration for Multi-Client IME process since other
6583 // IMEs on other displays will also receive this configuration change due to IME
6584 // services use the same application config/context.
6585 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006586
Yunfan Chen75157d72018-07-27 14:47:21 +09006587 if (pid == MY_PID || pid < 0) {
6588 if (DEBUG_CONFIGURATION) {
6589 Slog.w(TAG,
6590 "Trying to update display configuration for system/invalid process.");
6591 }
6592 return;
6593 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006594 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006595 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006596 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006597 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006598 // Call might come when display is not yet added or has been removed.
6599 if (DEBUG_CONFIGURATION) {
6600 Slog.w(TAG, "Trying to update display configuration for non-existing "
6601 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006602 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006603 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006604 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006605 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006606 if (process == null) {
6607 if (DEBUG_CONFIGURATION) {
6608 Slog.w(TAG, "Trying to update display configuration for invalid "
6609 + "process, pid=" + pid);
6610 }
6611 return;
6612 }
lumarkddc77fb2019-06-27 22:22:23 +08006613 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006614 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006615 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006616 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006617
6618 @Override
6619 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006620 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006621 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006622 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006623 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006624 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006625 }
6626 }
6627 }
6628
6629 @Override
6630 public void clearPendingResultForActivity(IBinder activityToken,
6631 WeakReference<PendingIntentRecord> pir) {
6632 synchronized (mGlobalLock) {
6633 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6634 if (r != null && r.pendingResults != null) {
6635 r.pendingResults.remove(pir);
6636 }
6637 }
6638 }
6639
6640 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006641 public ActivityTokens getTopActivityForTask(int taskId) {
6642 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006643 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006644 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006645 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6646 + " Requested task not found");
6647 return null;
6648 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006649 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006650 if (activity == null) {
6651 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6652 + " Requested activity not found");
6653 return null;
6654 }
6655 if (!activity.attachedToProcess()) {
6656 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6657 + activity);
6658 return null;
6659 }
6660 return new ActivityTokens(activity.appToken, activity.assistToken,
6661 activity.app.getThread());
6662 }
6663 }
6664
6665 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006666 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006667 @Nullable String featureId, int callingUid, int userId, IBinder token,
6668 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6669 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006670 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006671 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6672 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006673 }
6674 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006675
6676 @Override
6677 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6678 synchronized (mGlobalLock) {
6679 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6680 if (r == null) {
6681 return null;
6682 }
6683 if (r.mServiceConnectionsHolder == null) {
6684 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6685 ActivityTaskManagerService.this, r);
6686 }
6687
6688 return r.mServiceConnectionsHolder;
6689 }
6690 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006691
6692 @Override
6693 public Intent getHomeIntent() {
6694 synchronized (mGlobalLock) {
6695 return ActivityTaskManagerService.this.getHomeIntent();
6696 }
6697 }
6698
6699 @Override
6700 public boolean startHomeActivity(int userId, String reason) {
6701 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006702 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006703 }
6704 }
6705
6706 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006707 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006708 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006709 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006710 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006711 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006712 }
Chilun8b1f1be2019-03-13 17:14:36 +08006713 }
6714
6715 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006716 public boolean startHomeOnAllDisplays(int userId, String reason) {
6717 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006718 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006719 }
6720 }
6721
Riddle Hsua0536432019-02-16 00:38:59 +08006722 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006723 @Override
6724 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006725 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006726 if (mFactoryTest == FACTORY_TEST_OFF) {
6727 return false;
6728 }
6729 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6730 && wpc.mName.equals(mTopComponent.getPackageName())) {
6731 return true;
6732 }
6733 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6734 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6735 }
6736 }
6737
6738 @Override
6739 public void updateTopComponentForFactoryTest() {
6740 synchronized (mGlobalLock) {
6741 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6742 return;
6743 }
6744 final ResolveInfo ri = mContext.getPackageManager()
6745 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6746 final CharSequence errorMsg;
6747 if (ri != null) {
6748 final ActivityInfo ai = ri.activityInfo;
6749 final ApplicationInfo app = ai.applicationInfo;
6750 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6751 mTopAction = Intent.ACTION_FACTORY_TEST;
6752 mTopData = null;
6753 mTopComponent = new ComponentName(app.packageName, ai.name);
6754 errorMsg = null;
6755 } else {
6756 errorMsg = mContext.getResources().getText(
6757 com.android.internal.R.string.factorytest_not_system);
6758 }
6759 } else {
6760 errorMsg = mContext.getResources().getText(
6761 com.android.internal.R.string.factorytest_no_action);
6762 }
6763 if (errorMsg == null) {
6764 return;
6765 }
6766
6767 mTopAction = null;
6768 mTopData = null;
6769 mTopComponent = null;
6770 mUiHandler.post(() -> {
6771 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6772 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006773 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006774 });
6775 }
6776 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006777
Riddle Hsua0536432019-02-16 00:38:59 +08006778 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006779 @Override
6780 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6781 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006782 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006783 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006784 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006785
6786 wpc.clearRecentTasks();
6787 wpc.clearActivities();
6788
6789 if (wpc.isInstrumenting()) {
6790 finishInstrumentationCallback.run();
6791 }
6792
Jorim Jaggid0752812018-10-16 16:07:20 +02006793 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006794 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006795 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006796 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006797 // If there was nothing to resume, and we are not already restarting
6798 // this process, but there is a visible activity that is hosted by the
6799 // process...then make sure all visible activities are running, taking
6800 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006801 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006802 !PRESERVE_WINDOWS);
6803 }
6804 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006805 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006807 }
6808 }
6809 }
6810
6811 @Override
6812 public void closeSystemDialogs(String reason) {
6813 enforceNotIsolatedCaller("closeSystemDialogs");
6814
6815 final int pid = Binder.getCallingPid();
6816 final int uid = Binder.getCallingUid();
6817 final long origId = Binder.clearCallingIdentity();
6818 try {
6819 synchronized (mGlobalLock) {
6820 // Only allow this from foreground processes, so that background
6821 // applications can't abuse it to prevent system UI from being shown.
6822 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006823 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006824 if (!proc.isPerceptible()) {
6825 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6826 + " from background process " + proc);
6827 return;
6828 }
6829 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006830 mWindowManager.closeSystemDialogs(reason);
6831
Louis Chang149d5c82019-12-30 09:47:39 +08006832 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006833 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006834 // Call into AM outside the synchronized block.
6835 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006836 } finally {
6837 Binder.restoreCallingIdentity(origId);
6838 }
6839 }
6840
6841 @Override
6842 public void cleanupDisabledPackageComponents(
6843 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6844 synchronized (mGlobalLock) {
6845 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006846 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006847 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006848 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006849 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006850 }
6851
6852 // Clean-up disabled tasks
6853 getRecentTasks().cleanupDisabledPackageTasksLocked(
6854 packageName, disabledClasses, userId);
6855 }
6856 }
6857
6858 @Override
6859 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6860 int userId) {
6861 synchronized (mGlobalLock) {
6862
6863 boolean didSomething =
6864 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006865 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006866 null, doit, evenPersistent, userId);
6867 return didSomething;
6868 }
6869 }
6870
6871 @Override
6872 public void resumeTopActivities(boolean scheduleIdle) {
6873 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006874 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006875 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006876 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006877 }
6878 }
6879 }
6880
Riddle Hsua0536432019-02-16 00:38:59 +08006881 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006882 @Override
6883 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006884 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006885 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6886 }
6887 }
6888
Riddle Hsua0536432019-02-16 00:38:59 +08006889 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006890 @Override
6891 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006892 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006893 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6894 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6895 }
6896 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006897 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006898 } finally {
6899 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6900 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006901 }
6902 }
6903
6904 @Override
6905 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6906 try {
6907 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6908 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6909 }
6910 } catch (RemoteException ex) {
6911 throw new SecurityException("Fail to check is caller a privileged app", ex);
6912 }
6913
6914 synchronized (mGlobalLock) {
6915 final long ident = Binder.clearCallingIdentity();
6916 try {
6917 if (mAmInternal.shouldConfirmCredentials(userId)) {
6918 if (mKeyguardController.isKeyguardLocked()) {
6919 // Showing launcher to avoid user entering credential twice.
6920 startHomeActivity(currentUserId, "notifyLockedProfile");
6921 }
Louis Chang149d5c82019-12-30 09:47:39 +08006922 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006923 }
6924 } finally {
6925 Binder.restoreCallingIdentity(ident);
6926 }
6927 }
6928 }
6929
6930 @Override
6931 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6932 mAmInternal.enforceCallingPermission(
6933 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6934
6935 synchronized (mGlobalLock) {
6936 final long ident = Binder.clearCallingIdentity();
6937 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006938 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6939 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006940 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006941 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6942 UserHandle.CURRENT);
6943 } finally {
6944 Binder.restoreCallingIdentity(ident);
6945 }
6946 }
6947 }
6948
6949 @Override
6950 public void writeActivitiesToProto(ProtoOutputStream proto) {
6951 synchronized (mGlobalLock) {
6952 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006953 mRootWindowContainer.dumpDebug(
6954 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006955 }
6956 }
6957
6958 @Override
6959 public void saveANRState(String reason) {
6960 synchronized (mGlobalLock) {
6961 final StringWriter sw = new StringWriter();
6962 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6963 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6964 if (reason != null) {
6965 pw.println(" Reason: " + reason);
6966 }
6967 pw.println();
6968 getActivityStartController().dump(pw, " ", null);
6969 pw.println();
6970 pw.println("-------------------------------------------------------------------------------");
6971 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6972 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6973 "" /* header */);
6974 pw.println();
6975 pw.close();
6976
6977 mLastANRState = sw.toString();
6978 }
6979 }
6980
6981 @Override
6982 public void clearSavedANRState() {
6983 synchronized (mGlobalLock) {
6984 mLastANRState = null;
6985 }
6986 }
6987
6988 @Override
6989 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6990 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6991 synchronized (mGlobalLock) {
6992 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6993 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6994 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6995 dumpLastANRLocked(pw);
6996 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6997 dumpLastANRTracesLocked(pw);
6998 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6999 dumpActivityStarterLocked(pw, dumpPackage);
7000 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7001 dumpActivityContainersLocked(pw);
7002 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7003 if (getRecentTasks() != null) {
7004 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7005 }
7006 }
7007 }
7008 }
7009
7010 @Override
7011 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7012 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7013 int wakefulness) {
7014 synchronized (mGlobalLock) {
7015 if (mHomeProcess != null && (dumpPackage == null
7016 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7017 if (needSep) {
7018 pw.println();
7019 needSep = false;
7020 }
7021 pw.println(" mHomeProcess: " + mHomeProcess);
7022 }
7023 if (mPreviousProcess != null && (dumpPackage == null
7024 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7025 if (needSep) {
7026 pw.println();
7027 needSep = false;
7028 }
7029 pw.println(" mPreviousProcess: " + mPreviousProcess);
7030 }
7031 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7032 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7033 StringBuilder sb = new StringBuilder(128);
7034 sb.append(" mPreviousProcessVisibleTime: ");
7035 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7036 pw.println(sb);
7037 }
7038 if (mHeavyWeightProcess != null && (dumpPackage == null
7039 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7040 if (needSep) {
7041 pw.println();
7042 needSep = false;
7043 }
7044 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7045 }
7046 if (dumpPackage == null) {
7047 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007048 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007049 }
7050 if (dumpAll) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007051 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7052 if (dumpPackage == null && topFocusedStack != null) {
7053 pw.println(" mConfigWillChange: " + topFocusedStack.mConfigWillChange);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007054 }
7055 if (mCompatModePackages.getPackages().size() > 0) {
7056 boolean printed = false;
7057 for (Map.Entry<String, Integer> entry
7058 : mCompatModePackages.getPackages().entrySet()) {
7059 String pkg = entry.getKey();
7060 int mode = entry.getValue();
7061 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7062 continue;
7063 }
7064 if (!printed) {
7065 pw.println(" mScreenCompatPackages:");
7066 printed = true;
7067 }
7068 pw.println(" " + pkg + ": " + mode);
7069 }
7070 }
7071 }
7072
7073 if (dumpPackage == null) {
7074 pw.println(" mWakefulness="
7075 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007076 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007077 if (mRunningVoice != null) {
7078 pw.println(" mRunningVoice=" + mRunningVoice);
7079 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7080 }
7081 pw.println(" mSleeping=" + mSleeping);
7082 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7083 pw.println(" mVrController=" + mVrController);
7084 }
7085 if (mCurAppTimeTracker != null) {
7086 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7087 }
7088 if (mAllowAppSwitchUids.size() > 0) {
7089 boolean printed = false;
7090 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7091 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7092 for (int j = 0; j < types.size(); j++) {
7093 if (dumpPackage == null ||
7094 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7095 if (needSep) {
7096 pw.println();
7097 needSep = false;
7098 }
7099 if (!printed) {
7100 pw.println(" mAllowAppSwitchUids:");
7101 printed = true;
7102 }
7103 pw.print(" User ");
7104 pw.print(mAllowAppSwitchUids.keyAt(i));
7105 pw.print(": Type ");
7106 pw.print(types.keyAt(j));
7107 pw.print(" = ");
7108 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7109 pw.println();
7110 }
7111 }
7112 }
7113 }
7114 if (dumpPackage == null) {
7115 if (mController != null) {
7116 pw.println(" mController=" + mController
7117 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7118 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007119 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7120 pw.println(" mLaunchingActivityWakeLock="
7121 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007122 }
7123
7124 return needSep;
7125 }
7126 }
7127
7128 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007129 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7130 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007131 synchronized (mGlobalLock) {
7132 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007133 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08007134 final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
7135 if (topFocusedStack != null) {
7136 proto.write(CONFIG_WILL_CHANGE, topFocusedStack.mConfigWillChange);
7137 }
sanryhuang498e77e2018-12-06 14:57:01 +08007138 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7139 if (mRunningVoice != null) {
7140 final long vrToken = proto.start(
7141 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7142 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7143 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007144 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007145 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7146 proto.end(vrToken);
7147 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007148 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007149 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007150 if (mController != null) {
7151 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007152 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7153 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007154 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7155 proto.end(token);
7156 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007157 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7158 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007159 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007160 }
7161
7162 if (mHomeProcess != null && (dumpPackage == null
7163 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007164 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007165 }
7166
7167 if (mPreviousProcess != null && (dumpPackage == null
7168 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007169 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007170 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7171 }
7172
7173 if (mHeavyWeightProcess != null && (dumpPackage == null
7174 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007175 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007176 }
7177
7178 for (Map.Entry<String, Integer> entry
7179 : mCompatModePackages.getPackages().entrySet()) {
7180 String pkg = entry.getKey();
7181 int mode = entry.getValue();
7182 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7183 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7184 proto.write(PACKAGE, pkg);
7185 proto.write(MODE, mode);
7186 proto.end(compatToken);
7187 }
7188 }
7189
7190 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007191 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007192 }
7193
7194 }
7195 }
7196
7197 @Override
7198 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7199 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7200 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007201 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7202 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007203 }
7204
7205 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007206 public void dumpForOom(PrintWriter pw) {
7207 synchronized (mGlobalLock) {
7208 pw.println(" mHomeProcess: " + mHomeProcess);
7209 pw.println(" mPreviousProcess: " + mPreviousProcess);
7210 if (mHeavyWeightProcess != null) {
7211 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7212 }
7213 }
7214 }
7215
7216 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007217 public boolean canGcNow() {
7218 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007219 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007220 }
7221 }
7222
Riddle Hsua0536432019-02-16 00:38:59 +08007223 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007224 @Override
7225 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007226 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007227 if (mRootWindowContainer == null) {
7228 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007229 // oomadj after AMS created.
7230 return null;
7231 }
Louis Chang149d5c82019-12-30 09:47:39 +08007232 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007233 return top != null ? top.app : null;
7234 }
7235 }
7236
Riddle Hsua0536432019-02-16 00:38:59 +08007237 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007238 @Override
7239 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007240 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007241 if (mRootWindowContainer != null) {
7242 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007243 }
7244 }
7245 }
7246
7247 @Override
7248 public void scheduleDestroyAllActivities(String reason) {
7249 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007250 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007251 }
7252 }
7253
7254 @Override
7255 public void removeUser(int userId) {
7256 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007257 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007258 }
7259 }
7260
7261 @Override
7262 public boolean switchUser(int userId, UserState userState) {
7263 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007264 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007265 }
7266 }
7267
7268 @Override
7269 public void onHandleAppCrash(WindowProcessController wpc) {
7270 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007271 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007272 }
7273 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007274
7275 @Override
7276 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7277 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007278 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007279 }
7280 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007281
Riddle Hsua0536432019-02-16 00:38:59 +08007282 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007283 @Override
7284 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007285 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007286 }
7287
Riddle Hsua0536432019-02-16 00:38:59 +08007288 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007289 @Override
7290 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007291 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007292 }
7293
Riddle Hsua0536432019-02-16 00:38:59 +08007294 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007295 @Override
7296 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007297 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007298 }
7299
Riddle Hsua0536432019-02-16 00:38:59 +08007300 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007301 @Override
7302 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007303 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007304 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007305
7306 @Override
7307 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007308 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007309 mPendingTempWhitelist.put(uid, tag);
7310 }
7311 }
7312
7313 @Override
7314 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007315 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007316 mPendingTempWhitelist.remove(uid);
7317 }
7318 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007319
7320 @Override
7321 public boolean handleAppCrashInActivityController(String processName, int pid,
7322 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7323 Runnable killCrashingAppCallback) {
7324 synchronized (mGlobalLock) {
7325 if (mController == null) {
7326 return false;
7327 }
7328
7329 try {
7330 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7331 stackTrace)) {
7332 killCrashingAppCallback.run();
7333 return true;
7334 }
7335 } catch (RemoteException e) {
7336 mController = null;
7337 Watchdog.getInstance().setActivityController(null);
7338 }
7339 return false;
7340 }
7341 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007342
7343 @Override
7344 public void removeRecentTasksByPackageName(String packageName, int userId) {
7345 synchronized (mGlobalLock) {
7346 mRecentTasks.removeTasksByPackageName(packageName, userId);
7347 }
7348 }
7349
7350 @Override
7351 public void cleanupRecentTasksForUser(int userId) {
7352 synchronized (mGlobalLock) {
7353 mRecentTasks.cleanupLocked(userId);
7354 }
7355 }
7356
7357 @Override
7358 public void loadRecentTasksForUser(int userId) {
7359 synchronized (mGlobalLock) {
7360 mRecentTasks.loadUserRecentsLocked(userId);
7361 }
7362 }
7363
7364 @Override
7365 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7366 synchronized (mGlobalLock) {
7367 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7368 }
7369 }
7370
7371 @Override
7372 public void flushRecentTasks() {
7373 mRecentTasks.flush();
7374 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007375
7376 @Override
7377 public WindowProcessController getHomeProcess() {
7378 synchronized (mGlobalLock) {
7379 return mHomeProcess;
7380 }
7381 }
7382
7383 @Override
7384 public WindowProcessController getPreviousProcess() {
7385 synchronized (mGlobalLock) {
7386 return mPreviousProcess;
7387 }
7388 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007389
7390 @Override
7391 public void clearLockedTasks(String reason) {
7392 synchronized (mGlobalLock) {
7393 getLockTaskController().clearLockedTasks(reason);
7394 }
7395 }
7396
7397 @Override
7398 public void updateUserConfiguration() {
7399 synchronized (mGlobalLock) {
7400 final Configuration configuration = new Configuration(getGlobalConfiguration());
7401 final int currentUserId = mAmInternal.getCurrentUserId();
7402 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7403 configuration, currentUserId, Settings.System.canWrite(mContext));
7404 updateConfigurationLocked(configuration, null /* starting */,
7405 false /* initLocale */, false /* persistent */, currentUserId,
7406 false /* deferResume */);
7407 }
7408 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007409
7410 @Override
7411 public boolean canShowErrorDialogs() {
7412 synchronized (mGlobalLock) {
7413 return mShowDialogs && !mSleeping && !mShuttingDown
7414 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7415 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7416 mAmInternal.getCurrentUserId())
7417 && !(UserManager.isDeviceInDemoMode(mContext)
7418 && mAmInternal.getCurrentUser().isDemo());
7419 }
7420 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007421
7422 @Override
7423 public void setProfileApp(String profileApp) {
7424 synchronized (mGlobalLock) {
7425 mProfileApp = profileApp;
7426 }
7427 }
7428
7429 @Override
7430 public void setProfileProc(WindowProcessController wpc) {
7431 synchronized (mGlobalLock) {
7432 mProfileProc = wpc;
7433 }
7434 }
7435
7436 @Override
7437 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7438 synchronized (mGlobalLock) {
7439 mProfilerInfo = profilerInfo;
7440 }
7441 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007442
7443 @Override
7444 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7445 synchronized (mGlobalLock) {
7446 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7447 }
7448 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007449
7450 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007451 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
Peter Kalauskas4dc04602020-02-12 18:49:03 -08007452 boolean isLowResolution) {
7453 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007454 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007455 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007456
7457 @Override
7458 public boolean isUidForeground(int uid) {
7459 synchronized (mGlobalLock) {
7460 return ActivityTaskManagerService.this.isUidForeground(uid);
7461 }
7462 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007463
7464 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007465 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007466 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007467 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007468 }
7469 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007470
7471 @Override
7472 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007473 // Translate package names into UIDs
7474 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007475 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007476 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7477 if (uid >= 0) {
7478 result.add(uid);
7479 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007480 }
7481 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007482 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007483 }
7484 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007485 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007486}