blob: ea7a62a618c22b2bb51a9efb45da329646ced66d [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;
Evan Rosky4505b352018-09-06 11:20:40 -070031import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080055import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070067
Yunfan Chen79b96062018-10-17 12:45:23 -070068import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
69import static com.android.server.am.ActivityManagerService.MY_PID;
70import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
71import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Jeff Changd136e772019-11-05 20:33:52 +080086import static com.android.server.am.EventLogTags.writeBootProgressEnableScreen;
87import static com.android.server.am.EventLogTags.writeConfigurationChanged;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070088import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
89import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Louis Chang149d5c82019-12-30 09:47:39 +0800120import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
Louis Changcdec0802019-11-11 11:45:07 +0800122import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800127import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700128import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.annotation.Nullable;
130import android.annotation.UserIdInt;
131import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700132import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700133import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.ActivityOptions;
135import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700136import android.app.ActivityThread;
137import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700138import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100139import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700140import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700141import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700142import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.IApplicationThread;
144import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400146import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700148import android.app.Notification;
149import android.app.NotificationManager;
150import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700151import android.app.PictureInPictureParams;
152import android.app.ProfilerInfo;
153import android.app.RemoteAction;
154import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700155import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.app.admin.DevicePolicyCache;
157import android.app.assist.AssistContent;
158import android.app.assist.AssistStructure;
jorgegil@google.com06bc3232019-10-31 14:51:22 -0700159import android.app.servertransaction.ClientTransaction;
160import android.app.servertransaction.EnterPipRequestedItem;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700161import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.ActivityNotFoundException;
163import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700164import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700165import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700166import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700167import android.content.IIntentSender;
168import android.content.Intent;
169import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700170import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900171import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700172import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700174import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.content.pm.ParceledListSlice;
176import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700177import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700179import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700180import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700181import android.graphics.Bitmap;
182import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700183import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700184import android.metrics.LogMaker;
185import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700186import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700187import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700188import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700189import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700190import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700194import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800195import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700196import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700197import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700198import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700199import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100200import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700201import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700203import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.SystemClock;
205import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700207import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700209import android.os.UserManager;
210import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700211import android.os.storage.IStorageManager;
212import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700213import android.provider.Settings;
214import android.service.voice.IVoiceInteractionSession;
215import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900216import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700217import android.telecom.TelecomManager;
218import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100219import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700221import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700223import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700224import android.util.SparseArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700225import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700226import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700227import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700228import android.view.IRecentsAnimationRunner;
Robert Carr8a2f9132019-11-11 15:03:15 -0800229import android.view.ITaskOrganizer;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700230import android.view.RemoteAnimationAdapter;
231import android.view.RemoteAnimationDefinition;
Evan Roskyddedfd42019-10-04 13:38:38 -0700232import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700233import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700234
Evan Rosky4505b352018-09-06 11:20:40 -0700235import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700236import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700238import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import 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;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800251import com.android.internal.util.function.pooled.PooledConsumer;
252import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700253import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700254import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700255import com.android.server.LocalServices;
256import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700257import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800258import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700259import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700260import com.android.server.am.ActivityManagerService;
261import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
262import 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;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900268import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700269import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700270import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700271import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800272import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700273import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700275
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700277import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700279import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700280import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700281import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700282import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700283import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800284import java.lang.annotation.ElementType;
285import java.lang.annotation.Retention;
286import java.lang.annotation.RetentionPolicy;
287import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700288import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700291import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700292import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400293import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700294import java.util.HashSet;
Evan Roskyddedfd42019-10-04 13:38:38 -0700295import java.util.Iterator;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700296import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700297import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700298import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000299import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700300import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301
302/**
303 * System service for managing activities and their containers (task, stacks, displays,... ).
304 *
305 * {@hide}
306 */
307public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700308 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700309 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000310 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700311 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
312 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
313 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
314 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700315 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700316
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700318 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700319 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700320 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100321 // How long we permit background activity starts after an activity in the process
322 // started or finished.
323 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700324
Wale Ogunwale98875612018-10-12 07:53:02 -0700325 /** Used to indicate that an app transition should be animated. */
326 static final boolean ANIMATE = true;
327
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700328 /** Hardware-reported OpenGLES version. */
329 final int GL_ES_VERSION;
330
Wale Ogunwale31913b52018-10-13 08:29:31 -0700331 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
332 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
333 public static final String DUMP_LASTANR_CMD = "lastanr" ;
334 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
335 public static final String DUMP_STARTER_CMD = "starter" ;
336 public static final String DUMP_CONTAINERS_CMD = "containers" ;
337 public static final String DUMP_RECENTS_CMD = "recents" ;
338 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
339
Wale Ogunwale64258362018-10-16 15:13:37 -0700340 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
341 public static final int RELAUNCH_REASON_NONE = 0;
342 /** This activity is being relaunched due to windowing mode change. */
343 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
344 /** This activity is being relaunched due to a free-resize operation. */
345 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
346
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700347 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700348
Wale Ogunwalef6733932018-06-27 05:14:34 -0700349 /**
350 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
351 * change at runtime. Use mContext for non-UI purposes.
352 */
353 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700354 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700355 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700356 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700357 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700358 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700359 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800360 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800361 @VisibleForTesting
362 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700363 PowerManagerInternal mPowerManagerInternal;
364 private UsageStatsManagerInternal mUsageStatsInternal;
365
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700366 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700367 IntentFirewall mIntentFirewall;
368
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700369 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800370 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800371 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700372 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800373 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
374 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
375 *
376 * @see WindowManagerThreadPriorityBooster
377 */
378 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700379 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800380 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700381 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700382 private UserManagerService mUserManager;
383 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700384 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800385 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700386 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700387 /** All processes currently running that might have a window organized by name. */
388 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100389 /** All processes we currently have running mapped by pid and uid */
390 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700391 /** This is the process holding what we currently consider to be the "home" activity. */
392 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700393 /** The currently running heavy-weight process, if any. */
394 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700395 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700396 /**
397 * This is the process holding the activity the user last visited that is in a different process
398 * from the one they are currently in.
399 */
400 WindowProcessController mPreviousProcess;
401 /** The time at which the previous process was last visible. */
402 long mPreviousProcessVisibleTime;
403
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700404 /** List of intents that were used to start the most recent tasks. */
405 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700406 /** State of external calls telling us if the device is awake or asleep. */
407 private boolean mKeyguardShown = false;
408
409 // Wrapper around VoiceInteractionServiceManager
410 private AssistUtils mAssistUtils;
411
412 // VoiceInteraction session ID that changes for each new request except when
413 // being called for multi-window assist in a single session.
414 private int mViSessionId = 1000;
415
416 // How long to wait in getAssistContextExtras for the activity and foreground services
417 // to respond with the result.
418 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
419
420 // How long top wait when going through the modern assist (which doesn't need to block
421 // on getting this result before starting to launch its UI).
422 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
423
424 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
425 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
426
Alison Cichowlas3e340502018-08-07 17:15:01 -0400427 // Permission tokens are used to temporarily granted a trusted app the ability to call
428 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
429 // showing any appropriate error messages to the user.
430 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
431 10 * MINUTE_IN_MILLIS;
432
433 // How long before the service actually expires a token. This is slightly longer than
434 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
435 // expiration exception.
436 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
437 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
438
439 // How long the service will remember expired tokens, for the purpose of providing error
440 // messaging when a client uses an expired token.
441 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
442 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
443
444 // Activity tokens of system activities that are delegating their call to
445 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
446 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
447
448 // Permission tokens that have expired, but we remember for error reporting.
449 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
450
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700451 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
452
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700453 // Keeps track of the active voice interaction service component, notified from
454 // VoiceInteractionManagerService
455 ComponentName mActiveVoiceInteractionServiceComponent;
456
Michal Karpinskida34cd42019-04-02 19:46:52 +0100457 // A map userId and all its companion app uids
458 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000459
Wale Ogunwalee2172292018-10-25 10:11:10 -0700460 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700461 KeyguardController mKeyguardController;
462 private final ClientLifecycleManager mLifecycleManager;
463 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700464 /** The controller for all operations related to locktask. */
465 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700466 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700467
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700468 boolean mSuppressResizeConfigChanges;
469
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700470 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700471 new UpdateConfigurationResult();
472
473 static final class UpdateConfigurationResult {
474 // Configuration changes that were updated.
475 int changes;
476 // If the activity was relaunched to match the new configuration.
477 boolean activityRelaunched;
478
479 void reset() {
480 changes = 0;
481 activityRelaunched = false;
482 }
483 }
484
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700485 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700486 private int mConfigurationSeq;
487 // To cache the list of supported system locales
488 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700489
490 /**
491 * Temp object used when global and/or display override configuration is updated. It is also
492 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
493 * anyone...
494 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700495 private Configuration mTempConfig = new Configuration();
496
Wale Ogunwalef6733932018-06-27 05:14:34 -0700497 /** Temporary to avoid allocations. */
498 final StringBuilder mStringBuilder = new StringBuilder(256);
499
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700500 // Amount of time after a call to stopAppSwitches() during which we will
501 // prevent further untrusted switches from happening.
502 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
503
504 /**
505 * The time at which we will allow normal application switches again,
506 * after a call to {@link #stopAppSwitches()}.
507 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700508 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700509 /**
510 * This is set to true after the first switch after mAppSwitchesAllowedTime
511 * is set; any switches after that will clear the time.
512 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700513 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700514
Ricky Wai906af482019-06-03 17:25:28 +0100515 /**
516 * Last stop app switches time, apps finished before this time cannot start background activity
517 * even if they are in grace period.
518 */
519 private long mLastStopAppSwitchesTime;
520
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700521 IActivityController mController = null;
522 boolean mControllerIsAMonkey = false;
523
Wale Ogunwale214f3482018-10-04 11:00:47 -0700524 final int mFactoryTest;
525
526 /** Used to control how we initialize the service. */
527 ComponentName mTopComponent;
528 String mTopAction = Intent.ACTION_MAIN;
529 String mTopData;
530
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800531 /** Profiling app information. */
532 String mProfileApp = null;
533 WindowProcessController mProfileProc = null;
534 ProfilerInfo mProfilerInfo = null;
535
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700536 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700537 * Dump of the activity state at the time of the last ANR. Cleared after
538 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
539 */
540 String mLastANRState;
541
542 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700543 * Used to retain an update lock when the foreground activity is in
544 * immersive mode.
545 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700546 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700547
548 /**
549 * Packages that are being allowed to perform unrestricted app switches. Mapping is
550 * User -> Type -> uid.
551 */
552 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
553
554 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700555 private int mThumbnailWidth;
556 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700557
558 /**
559 * Flag that indicates if multi-window is enabled.
560 *
561 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
562 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
563 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
564 * At least one of the forms of multi-window must be enabled in order for this flag to be
565 * initialized to 'true'.
566 *
567 * @see #mSupportsSplitScreenMultiWindow
568 * @see #mSupportsFreeformWindowManagement
569 * @see #mSupportsPictureInPicture
570 * @see #mSupportsMultiDisplay
571 */
572 boolean mSupportsMultiWindow;
573 boolean mSupportsSplitScreenMultiWindow;
574 boolean mSupportsFreeformWindowManagement;
575 boolean mSupportsPictureInPicture;
576 boolean mSupportsMultiDisplay;
577 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700578 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700579
580 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
581
582 // VR Vr2d Display Id.
583 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700584
Wale Ogunwalef6733932018-06-27 05:14:34 -0700585 /**
586 * Set while we are wanting to sleep, to prevent any
587 * activities from being started/resumed.
588 *
589 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
590 *
591 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
592 * while in the sleep state until there is a pending transition out of sleep, in which case
593 * mSleeping is set to false, and remains false while awake.
594 *
595 * Whether mSleeping can quickly toggled between true/false without the device actually
596 * display changing states is undefined.
597 */
598 private boolean mSleeping = false;
599
600 /**
601 * The process state used for processes that are running the top activities.
602 * This changes between TOP and TOP_SLEEPING to following mSleeping.
603 */
604 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
605
Riddle Hsua0022cd2019-09-09 21:12:41 +0800606 @Retention(RetentionPolicy.SOURCE)
607 @IntDef({
608 LAYOUT_REASON_CONFIG_CHANGED,
609 LAYOUT_REASON_VISIBILITY_CHANGED,
610 })
611 @interface LayoutReason {}
612 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
613 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
614
615 /** The reasons to perform surface placement. */
616 @LayoutReason
617 private int mLayoutReasons;
618
Wale Ogunwalef6733932018-06-27 05:14:34 -0700619 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
620 // automatically. Important for devices without direct input devices.
621 private boolean mShowDialogs = true;
622
623 /** Set if we are shutting down the system, similar to sleeping. */
624 boolean mShuttingDown = false;
625
626 /**
627 * We want to hold a wake lock while running a voice interaction session, since
628 * this may happen with the screen off and we need to keep the CPU running to
629 * be able to continue to interact with the user.
630 */
631 PowerManager.WakeLock mVoiceWakeLock;
632
633 /**
634 * Set while we are running a voice interaction. This overrides sleeping while it is active.
635 */
636 IVoiceInteractionSession mRunningVoice;
637
638 /**
639 * The last resumed activity. This is identical to the current resumed activity most
640 * of the time but could be different when we're pausing one activity before we resume
641 * another activity.
642 */
643 ActivityRecord mLastResumedActivity;
644
645 /**
646 * The activity that is currently being traced as the active resumed activity.
647 *
648 * @see #updateResumedAppTrace
649 */
650 private @Nullable ActivityRecord mTracedResumedActivity;
651
652 /** If non-null, we are tracking the time the user spends in the currently focused app. */
653 AppTimeTracker mCurAppTimeTracker;
654
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700655 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700656
Wale Ogunwale53783742018-09-16 10:21:51 -0700657 /**
658 * Packages that the user has asked to have run in screen size
659 * compatibility mode instead of filling the screen.
660 */
661 CompatModePackages mCompatModePackages;
662
Wale Ogunwalef6733932018-06-27 05:14:34 -0700663 private FontScaleSettingObserver mFontScaleSettingObserver;
664
Robert Carr8a2f9132019-11-11 15:03:15 -0800665 /**
666 * Stores the registration and state of TaskOrganizers in use.
667 */
668 TaskOrganizerController mTaskOrganizerController =
669 new TaskOrganizerController(this, mGlobalLock);
670
Ricky Wai96f5c352019-04-10 18:40:17 +0100671 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000672
Wale Ogunwalef6733932018-06-27 05:14:34 -0700673 private final class FontScaleSettingObserver extends ContentObserver {
674 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
675 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
676
677 public FontScaleSettingObserver() {
678 super(mH);
679 final ContentResolver resolver = mContext.getContentResolver();
680 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
681 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
682 UserHandle.USER_ALL);
683 }
684
685 @Override
686 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
687 if (mFontScaleUri.equals(uri)) {
688 updateFontScaleIfNeeded(userId);
689 } else if (mHideErrorDialogsUri.equals(uri)) {
690 synchronized (mGlobalLock) {
691 updateShouldShowDialogsLocked(getGlobalConfiguration());
692 }
693 }
694 }
695 }
696
Riddle Hsua0536432019-02-16 00:38:59 +0800697 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
698 @Target(ElementType.METHOD)
699 @Retention(RetentionPolicy.SOURCE)
700 @interface HotPath {
701 int NONE = 0;
702 int OOM_ADJUSTMENT = 1;
703 int LRU_UPDATE = 2;
704 int PROCESS_CHANGE = 3;
705 int caller() default NONE;
706 }
707
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800708 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
709 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900710 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800711 mAmInternal.updateOomAdj();
712 }
713 };
714
Charles Chen8d98dd22018-12-26 17:36:54 +0800715 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
716 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700717 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700718 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700719 mSystemThread = ActivityThread.currentActivityThread();
720 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700721 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800722 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700723 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700724 }
725
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700726 public void onSystemReady() {
727 synchronized (mGlobalLock) {
728 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
729 PackageManager.FEATURE_CANT_SAVE_STATE);
730 mAssistUtils = new AssistUtils(mContext);
731 mVrController.onSystemReady();
732 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700733 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700734 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700735 }
736
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700737 public void onInitPowerManagement() {
738 synchronized (mGlobalLock) {
739 mStackSupervisor.initPowerManagement();
740 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
741 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
742 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
743 mVoiceWakeLock.setReferenceCounted(false);
744 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700745 }
746
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700747 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700748 mFontScaleSettingObserver = new FontScaleSettingObserver();
749 }
750
Wale Ogunwale59507092018-10-29 09:00:30 -0700751 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700752 final boolean freeformWindowManagement =
753 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
754 || Settings.Global.getInt(
755 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
756
757 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
758 final boolean supportsPictureInPicture = supportsMultiWindow &&
759 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
760 final boolean supportsSplitScreenMultiWindow =
761 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
762 final boolean supportsMultiDisplay = mContext.getPackageManager()
763 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700764 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
765 final boolean forceResizable = Settings.Global.getInt(
766 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700767 final boolean sizeCompatFreeform = Settings.Global.getInt(
768 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700769
770 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900771 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700772
773 final Configuration configuration = new Configuration();
774 Settings.System.getConfiguration(resolver, configuration);
775 if (forceRtl) {
776 // This will take care of setting the correct layout direction flags
777 configuration.setLayoutDirection(configuration.locale);
778 }
779
780 synchronized (mGlobalLock) {
781 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700782 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700783 final boolean multiWindowFormEnabled = freeformWindowManagement
784 || supportsSplitScreenMultiWindow
785 || supportsPictureInPicture
786 || supportsMultiDisplay;
787 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
788 mSupportsMultiWindow = true;
789 mSupportsFreeformWindowManagement = freeformWindowManagement;
790 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
791 mSupportsPictureInPicture = supportsPictureInPicture;
792 mSupportsMultiDisplay = supportsMultiDisplay;
793 } else {
794 mSupportsMultiWindow = false;
795 mSupportsFreeformWindowManagement = false;
796 mSupportsSplitScreenMultiWindow = false;
797 mSupportsPictureInPicture = false;
798 mSupportsMultiDisplay = false;
799 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700800 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700801 // This happens before any activities are started, so we can change global configuration
802 // in-place.
803 updateConfigurationLocked(configuration, null, true);
804 final Configuration globalConfig = getGlobalConfiguration();
805 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
806
807 // Load resources only after the current configuration has been set.
808 final Resources res = mContext.getResources();
809 mThumbnailWidth = res.getDimensionPixelSize(
810 com.android.internal.R.dimen.thumbnail_width);
811 mThumbnailHeight = res.getDimensionPixelSize(
812 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700813 }
814 }
815
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800816 public WindowManagerGlobalLock getGlobalLock() {
817 return mGlobalLock;
818 }
819
Yunfan Chen585f2932019-01-29 16:04:45 +0900820 /** For test purpose only. */
821 @VisibleForTesting
822 public ActivityTaskManagerInternal getAtmInternal() {
823 return mInternal;
824 }
825
Riddle Hsud93a6c42018-11-29 21:50:06 +0800826 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
827 Looper looper) {
828 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700829 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700830 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700831 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800832 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700833 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700834 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700835 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700836
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700837 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700838 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700839 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700840 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700841 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700842 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700843 mKeyguardController = mStackSupervisor.getKeyguardController();
844 }
845
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700846 public void onActivityManagerInternalAdded() {
847 synchronized (mGlobalLock) {
848 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
849 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
850 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700851 }
852
Yunfan Chen75157d72018-07-27 14:47:21 +0900853 int increaseConfigurationSeqLocked() {
854 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
855 return mConfigurationSeq;
856 }
857
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700858 protected ActivityStackSupervisor createStackSupervisor() {
859 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
860 supervisor.initialize();
861 return supervisor;
862 }
863
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800864 protected AppWarnings createAppWarnings(
865 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
866 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
867 }
868
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700869 public void setWindowManager(WindowManagerService wm) {
870 synchronized (mGlobalLock) {
871 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800872 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800873 mTempConfig.setToDefaults();
874 mTempConfig.setLocales(LocaleList.getDefault());
875 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800876 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700877 mLockTaskController.setWindowManager(wm);
878 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800879 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700880 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700881 }
882
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700883 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
884 synchronized (mGlobalLock) {
885 mUsageStatsInternal = usageStatsManager;
886 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700887 }
888
Wale Ogunwalef6733932018-06-27 05:14:34 -0700889 UserManagerService getUserManager() {
890 if (mUserManager == null) {
891 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
892 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
893 }
894 return mUserManager;
895 }
896
897 AppOpsService getAppOpsService() {
898 if (mAppOpsService == null) {
899 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
900 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
901 }
902 return mAppOpsService;
903 }
904
905 boolean hasUserRestriction(String restriction, int userId) {
906 return getUserManager().hasUserRestriction(restriction, userId);
907 }
908
Michal Karpinski15486842019-04-25 17:33:42 +0100909 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
910 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmannda554e42019-12-20 11:21:02 -0800911 callingUid, callingPackage, /* featureId */ null, false, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100912 if (mode == AppOpsManager.MODE_DEFAULT) {
913 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
914 == PERMISSION_GRANTED;
915 }
916 return mode == AppOpsManager.MODE_ALLOWED;
917 }
918
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700919 @VisibleForTesting
920 protected void setRecentTasks(RecentTasks recentTasks) {
921 mRecentTasks = recentTasks;
922 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700923 }
924
925 RecentTasks getRecentTasks() {
926 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700927 }
928
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700929 ClientLifecycleManager getLifecycleManager() {
930 return mLifecycleManager;
931 }
932
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700933 ActivityStartController getActivityStartController() {
934 return mActivityStartController;
935 }
936
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700937 TaskChangeNotificationController getTaskChangeNotificationController() {
938 return mTaskChangeNotificationController;
939 }
940
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700941 LockTaskController getLockTaskController() {
942 return mLockTaskController;
943 }
944
Yunfan Chen75157d72018-07-27 14:47:21 +0900945 /**
946 * Return the global configuration used by the process corresponding to the input pid. This is
947 * usually the global configuration with some overrides specific to that process.
948 */
949 Configuration getGlobalConfigurationForCallingPid() {
950 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800951 return getGlobalConfigurationForPid(pid);
952 }
953
954 /**
955 * Return the global configuration used by the process corresponding to the given pid.
956 */
957 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900958 if (pid == MY_PID || pid < 0) {
959 return getGlobalConfiguration();
960 }
961 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100962 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900963 return app != null ? app.getConfiguration() : getGlobalConfiguration();
964 }
965 }
966
967 /**
968 * Return the device configuration info used by the process corresponding to the input pid.
969 * The value is consistent with the global configuration for the process.
970 */
971 @Override
972 public ConfigurationInfo getDeviceConfigurationInfo() {
973 ConfigurationInfo config = new ConfigurationInfo();
974 synchronized (mGlobalLock) {
975 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
976 config.reqTouchScreen = globalConfig.touchscreen;
977 config.reqKeyboardType = globalConfig.keyboard;
978 config.reqNavigation = globalConfig.navigation;
979 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
980 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
981 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
982 }
983 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
984 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
985 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
986 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700987 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900988 }
989 return config;
990 }
991
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700992 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700993 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700994 }
995
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700996 public static final class Lifecycle extends SystemService {
997 private final ActivityTaskManagerService mService;
998
999 public Lifecycle(Context context) {
1000 super(context);
1001 mService = new ActivityTaskManagerService(context);
1002 }
1003
1004 @Override
1005 public void onStart() {
1006 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001007 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001008 }
1009
Garfield Tan891146c2018-10-09 12:14:00 -07001010 @Override
1011 public void onUnlockUser(int userId) {
1012 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001013 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001014 }
1015 }
1016
1017 @Override
1018 public void onCleanupUser(int userId) {
1019 synchronized (mService.getGlobalLock()) {
1020 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1021 }
1022 }
1023
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001024 public ActivityTaskManagerService getService() {
1025 return mService;
1026 }
1027 }
1028
1029 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001030 public final int startActivity(IApplicationThread caller, String callingPackage,
1031 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1032 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1033 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1034 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1035 UserHandle.getCallingUserId());
1036 }
1037
1038 @Override
1039 public final int startActivities(IApplicationThread caller, String callingPackage,
1040 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1041 int userId) {
1042 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001043 enforceNotIsolatedCaller(reason);
1044 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001045 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001046 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1047 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1048 reason, null /* originatingPendingIntent */,
1049 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001050 }
1051
1052 @Override
1053 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1054 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1055 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1056 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1057 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1058 true /*validateIncomingUser*/);
1059 }
1060
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001061 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001062 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1063 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1064 boolean validateIncomingUser) {
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)
1074 .setResolvedType(resolvedType)
1075 .setResultTo(resultTo)
1076 .setResultWho(resultWho)
1077 .setRequestCode(requestCode)
1078 .setStartFlags(startFlags)
1079 .setProfilerInfo(profilerInfo)
1080 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001081 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001082 .execute();
1083
1084 }
1085
1086 @Override
1087 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1088 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001089 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1090 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001091 // Refuse possible leaked file descriptors
1092 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1093 throw new IllegalArgumentException("File descriptors passed in Intent");
1094 }
1095
1096 if (!(target instanceof PendingIntentRecord)) {
1097 throw new IllegalArgumentException("Bad PendingIntent object");
1098 }
1099
1100 PendingIntentRecord pir = (PendingIntentRecord)target;
1101
1102 synchronized (mGlobalLock) {
1103 // If this is coming from the currently resumed activity, it is
1104 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001105 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001106 if (stack.mResumedActivity != null &&
1107 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001108 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001109 }
1110 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001111 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001112 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001113 }
1114
1115 @Override
1116 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1117 Bundle bOptions) {
1118 // Refuse possible leaked file descriptors
1119 if (intent != null && intent.hasFileDescriptors()) {
1120 throw new IllegalArgumentException("File descriptors passed in Intent");
1121 }
1122 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1123
1124 synchronized (mGlobalLock) {
1125 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1126 if (r == null) {
1127 SafeActivityOptions.abort(options);
1128 return false;
1129 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001130 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001131 // The caller is not running... d'oh!
1132 SafeActivityOptions.abort(options);
1133 return false;
1134 }
1135 intent = new Intent(intent);
1136 // The caller is not allowed to change the data.
1137 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1138 // And we are resetting to find the next component...
1139 intent.setComponent(null);
1140
1141 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1142
1143 ActivityInfo aInfo = null;
1144 try {
1145 List<ResolveInfo> resolves =
1146 AppGlobals.getPackageManager().queryIntentActivities(
1147 intent, r.resolvedType,
1148 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1149 UserHandle.getCallingUserId()).getList();
1150
1151 // Look for the original activity in the list...
1152 final int N = resolves != null ? resolves.size() : 0;
1153 for (int i=0; i<N; i++) {
1154 ResolveInfo rInfo = resolves.get(i);
1155 if (rInfo.activityInfo.packageName.equals(r.packageName)
1156 && rInfo.activityInfo.name.equals(r.info.name)) {
1157 // We found the current one... the next matching is
1158 // after it.
1159 i++;
1160 if (i<N) {
1161 aInfo = resolves.get(i).activityInfo;
1162 }
1163 if (debug) {
1164 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1165 + "/" + r.info.name);
1166 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1167 ? "null" : aInfo.packageName + "/" + aInfo.name));
1168 }
1169 break;
1170 }
1171 }
1172 } catch (RemoteException e) {
1173 }
1174
1175 if (aInfo == null) {
1176 // Nobody who is next!
1177 SafeActivityOptions.abort(options);
1178 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1179 return false;
1180 }
1181
1182 intent.setComponent(new ComponentName(
1183 aInfo.applicationInfo.packageName, aInfo.name));
1184 intent.setFlags(intent.getFlags()&~(
1185 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1186 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1187 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1188 FLAG_ACTIVITY_NEW_TASK));
1189
1190 // Okay now we need to start the new activity, replacing the currently running activity.
1191 // This is a little tricky because we want to start the new one as if the current one is
1192 // finished, but not finish the current one first so that there is no flicker.
1193 // And thus...
1194 final boolean wasFinishing = r.finishing;
1195 r.finishing = true;
1196
1197 // Propagate reply information over to the new activity.
1198 final ActivityRecord resultTo = r.resultTo;
1199 final String resultWho = r.resultWho;
1200 final int requestCode = r.requestCode;
1201 r.resultTo = null;
1202 if (resultTo != null) {
1203 resultTo.removeResultsLocked(r, resultWho, requestCode);
1204 }
1205
1206 final long origId = Binder.clearCallingIdentity();
1207 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001208 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001209 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001210 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001211 .setResolvedType(r.resolvedType)
1212 .setActivityInfo(aInfo)
1213 .setResultTo(resultTo != null ? resultTo.appToken : null)
1214 .setResultWho(resultWho)
1215 .setRequestCode(requestCode)
1216 .setCallingPid(-1)
1217 .setCallingUid(r.launchedFromUid)
1218 .setCallingPackage(r.launchedFromPackage)
1219 .setRealCallingPid(-1)
1220 .setRealCallingUid(r.launchedFromUid)
1221 .setActivityOptions(options)
1222 .execute();
1223 Binder.restoreCallingIdentity(origId);
1224
1225 r.finishing = wasFinishing;
1226 if (res != ActivityManager.START_SUCCESS) {
1227 return false;
1228 }
1229 return true;
1230 }
1231 }
1232
1233 @Override
1234 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1235 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1236 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1237 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001238 enforceNotIsolatedCaller("startActivityAndWait");
1239 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1240 userId, "startActivityAndWait");
1241 // TODO: Switch to user app stacks here.
1242 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1243 .setCaller(caller)
1244 .setCallingPackage(callingPackage)
1245 .setResolvedType(resolvedType)
1246 .setResultTo(resultTo)
1247 .setResultWho(resultWho)
1248 .setRequestCode(requestCode)
1249 .setStartFlags(startFlags)
1250 .setActivityOptions(bOptions)
1251 .setUserId(userId)
1252 .setProfilerInfo(profilerInfo)
1253 .setWaitResult(res)
1254 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001255 return res;
1256 }
1257
1258 @Override
1259 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1260 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1261 int startFlags, Configuration config, Bundle bOptions, int userId) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001262 enforceNotIsolatedCaller("startActivityWithConfig");
1263 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1264 "startActivityWithConfig");
1265 // TODO: Switch to user app stacks here.
1266 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1267 .setCaller(caller)
1268 .setCallingPackage(callingPackage)
1269 .setResolvedType(resolvedType)
1270 .setResultTo(resultTo)
1271 .setResultWho(resultWho)
1272 .setRequestCode(requestCode)
1273 .setStartFlags(startFlags)
1274 .setGlobalConfiguration(config)
1275 .setActivityOptions(bOptions)
1276 .setUserId(userId)
1277 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001278 }
1279
Robert Carr8a2f9132019-11-11 15:03:15 -08001280 @Override
1281 public final void registerTaskOrganizer(ITaskOrganizer organizer, int windowingMode) {
1282 enforceCallerIsRecentsOrHasPermission(
1283 MANAGE_ACTIVITY_STACKS, "registerTaskOrganizer()");
1284 synchronized (mGlobalLock) {
1285 mTaskOrganizerController.registerTaskOrganizer(organizer, windowingMode);
1286 }
1287 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001288
1289 @Override
1290 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1291 int callingUid = Binder.getCallingUid();
1292 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1293 throw new SecurityException("Only the system process can request a permission token, "
1294 + "received request from uid: " + callingUid);
1295 }
1296 IBinder permissionToken = new Binder();
1297 synchronized (mGlobalLock) {
1298 mStartActivitySources.put(permissionToken, delegatorToken);
1299 }
1300
1301 Message expireMsg = PooledLambda.obtainMessage(
1302 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1303 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1304
1305 Message forgetMsg = PooledLambda.obtainMessage(
1306 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1307 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1308
1309 return permissionToken;
1310 }
1311
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001312 @Override
1313 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1314 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001315 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1316 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001317 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001318 // permission grants) as any app that may launch one of your own activities. So we only
1319 // allow this in two cases:
1320 // 1) The caller is an activity that is part of the core framework, and then only when it
1321 // is running as the system.
1322 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1323 // can only be requested by a system activity, which may then delegate this call to
1324 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001325 final ActivityRecord sourceRecord;
1326 final int targetUid;
1327 final String targetPackage;
1328 final boolean isResolver;
1329 synchronized (mGlobalLock) {
1330 if (resultTo == null) {
1331 throw new SecurityException("Must be called from an activity");
1332 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001333 final IBinder sourceToken;
1334 if (permissionToken != null) {
1335 // To even attempt to use a permissionToken, an app must also have this signature
1336 // permission.
1337 mAmInternal.enforceCallingPermission(
1338 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1339 "startActivityAsCaller");
1340 // If called with a permissionToken, we want the sourceRecord from the delegator
1341 // activity that requested this token.
1342 sourceToken = mStartActivitySources.remove(permissionToken);
1343 if (sourceToken == null) {
1344 // Invalid permissionToken, check if it recently expired.
1345 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1346 throw new SecurityException("Called with expired permission token: "
1347 + permissionToken);
1348 } else {
1349 throw new SecurityException("Called with invalid permission token: "
1350 + permissionToken);
1351 }
1352 }
1353 } else {
1354 // This method was called directly by the source.
1355 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001356 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001357
Louis Chang149d5c82019-12-30 09:47:39 +08001358 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001359 if (sourceRecord == null) {
1360 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001361 }
1362 if (sourceRecord.app == null) {
1363 throw new SecurityException("Called without a process attached to activity");
1364 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001365
1366 // Whether called directly or from a delegate, the source activity must be from the
1367 // android package.
1368 if (!sourceRecord.info.packageName.equals("android")) {
1369 throw new SecurityException("Must be called from an activity that is "
1370 + "declared in the android package");
1371 }
1372
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001373 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001374 // This is still okay, as long as this activity is running under the
1375 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001376 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001378 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001379 + " must be system uid or original calling uid "
1380 + sourceRecord.launchedFromUid);
1381 }
1382 }
1383 if (ignoreTargetSecurity) {
1384 if (intent.getComponent() == null) {
1385 throw new SecurityException(
1386 "Component must be specified with ignoreTargetSecurity");
1387 }
1388 if (intent.getSelector() != null) {
1389 throw new SecurityException(
1390 "Selector not allowed with ignoreTargetSecurity");
1391 }
1392 }
1393 targetUid = sourceRecord.launchedFromUid;
1394 targetPackage = sourceRecord.launchedFromPackage;
1395 isResolver = sourceRecord.isResolverOrChildActivity();
1396 }
1397
1398 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001399 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001400 }
1401
1402 // TODO: Switch to user app stacks here.
1403 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001404 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001405 .setCallingUid(targetUid)
1406 .setCallingPackage(targetPackage)
1407 .setResolvedType(resolvedType)
1408 .setResultTo(resultTo)
1409 .setResultWho(resultWho)
1410 .setRequestCode(requestCode)
1411 .setStartFlags(startFlags)
1412 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001413 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001414 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1415 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001416 // The target may well be in the background, which would normally prevent it
1417 // from starting an activity. Here we definitely want the start to succeed.
1418 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001419 .execute();
1420 } catch (SecurityException e) {
1421 // XXX need to figure out how to propagate to original app.
1422 // A SecurityException here is generally actually a fault of the original
1423 // calling activity (such as a fairly granting permissions), so propagate it
1424 // back to them.
1425 /*
1426 StringBuilder msg = new StringBuilder();
1427 msg.append("While launching");
1428 msg.append(intent.toString());
1429 msg.append(": ");
1430 msg.append(e.getMessage());
1431 */
1432 throw e;
1433 }
1434 }
1435
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001436 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1437 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1438 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1439 }
1440
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001441 @Override
1442 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1443 Intent intent, String resolvedType, IVoiceInteractionSession session,
1444 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1445 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001446 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001447 if (session == null || interactor == null) {
1448 throw new NullPointerException("null session or interactor");
1449 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001450 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001451 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001452 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 .setCallingUid(callingUid)
1454 .setCallingPackage(callingPackage)
1455 .setResolvedType(resolvedType)
1456 .setVoiceSession(session)
1457 .setVoiceInteractor(interactor)
1458 .setStartFlags(startFlags)
1459 .setProfilerInfo(profilerInfo)
1460 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001461 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001462 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001463 .execute();
1464 }
1465
1466 @Override
1467 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1468 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001469 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1470 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001471
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001472 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 .setCallingUid(callingUid)
1474 .setCallingPackage(callingPackage)
1475 .setResolvedType(resolvedType)
1476 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001477 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001478 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001479 .execute();
1480 }
1481
Riddle Hsu609a8e22019-06-27 16:46:29 -06001482 /**
1483 * Start the recents activity to perform the recents animation.
1484 *
1485 * @param intent The intent to start the recents activity.
1486 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1487 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001488 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001489 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1490 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001491 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001492 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001493 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001494 final long origId = Binder.clearCallingIdentity();
1495 try {
1496 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001497 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1498 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001499 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001500
1501 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001502 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001503 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001504 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001505 if (recentsAnimationRunner == null) {
1506 anim.preloadRecentsActivity();
1507 } else {
1508 anim.startRecentsActivity(recentsAnimationRunner);
1509 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001510 }
1511 } finally {
1512 Binder.restoreCallingIdentity(origId);
1513 }
1514 }
1515
1516 @Override
1517 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001518 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001519 "startActivityFromRecents()");
1520
1521 final int callingPid = Binder.getCallingPid();
1522 final int callingUid = Binder.getCallingUid();
1523 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1524 final long origId = Binder.clearCallingIdentity();
1525 try {
1526 synchronized (mGlobalLock) {
1527 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1528 safeOptions);
1529 }
1530 } finally {
1531 Binder.restoreCallingIdentity(origId);
1532 }
1533 }
1534
1535 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001536 * Public API to check if the client is allowed to start an activity on specified display.
1537 *
1538 * If the target display is private or virtual, some restrictions will apply.
1539 *
1540 * @param displayId Target display id.
1541 * @param intent Intent used to launch the activity.
1542 * @param resolvedType The MIME type of the intent.
1543 * @param userId The id of the user for whom the call is made.
1544 * @return {@code true} if a call to start an activity on the target display should succeed and
1545 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1546 */
1547 @Override
1548 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1549 String resolvedType, int userId) {
1550 final int callingUid = Binder.getCallingUid();
1551 final int callingPid = Binder.getCallingPid();
1552 final long origId = Binder.clearCallingIdentity();
1553
1554 try {
1555 // Collect information about the target of the Intent.
1556 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1557 0 /* startFlags */, null /* profilerInfo */, userId,
1558 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1559 UserHandle.USER_NULL));
1560 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1561
1562 synchronized (mGlobalLock) {
1563 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1564 aInfo);
1565 }
1566 } finally {
1567 Binder.restoreCallingIdentity(origId);
1568 }
1569 }
1570
1571 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001572 * This is the internal entry point for handling Activity.finish().
1573 *
1574 * @param token The Binder token referencing the Activity we want to finish.
1575 * @param resultCode Result code, if any, from this Activity.
1576 * @param resultData Result data (Intent), if any, from this Activity.
1577 * @param finishTask Whether to finish the task associated with this Activity.
1578 *
1579 * @return Returns true if the activity successfully finished, or false if it is still running.
1580 */
1581 @Override
1582 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1583 int finishTask) {
1584 // Refuse possible leaked file descriptors
1585 if (resultData != null && resultData.hasFileDescriptors()) {
1586 throw new IllegalArgumentException("File descriptors passed in Intent");
1587 }
1588
1589 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001590 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001591 if (r == null) {
1592 return true;
1593 }
1594 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001595 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001596 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 if (rootR == null) {
1598 Slog.w(TAG, "Finishing task with all activities already finished");
1599 }
1600 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1601 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001602 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001603 return false;
1604 }
1605
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001606 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1607 // We should consolidate.
1608 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001609 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001610 final ActivityRecord next =
1611 r.getActivityStack().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001612 if (next != null) {
1613 // ask watcher if this is allowed
1614 boolean resumeOK = true;
1615 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001616 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001617 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001618 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001619 Watchdog.getInstance().setActivityController(null);
1620 }
1621
1622 if (!resumeOK) {
1623 Slog.i(TAG, "Not finishing activity because controller resumed");
1624 return false;
1625 }
1626 }
1627 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001628
1629 // note down that the process has finished an activity and is in background activity
1630 // starts grace period
1631 if (r.app != null) {
1632 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1633 }
1634
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001635 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001636 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001637 try {
1638 boolean res;
1639 final boolean finishWithRootActivity =
1640 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1641 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1642 || (finishWithRootActivity && r == rootR)) {
1643 // If requested, remove the task that is associated to this activity only if it
1644 // was the root activity in the task. The result code and data is ignored
1645 // because we don't support returning them across task boundaries. Also, to
1646 // keep backwards compatibility we remove the task from recents when finishing
1647 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001648 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001649 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001650 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001651 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001652 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001653 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001654 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001655 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001656 if (!res) {
1657 Slog.i(TAG, "Failed to finish by app-request");
1658 }
1659 }
1660 return res;
1661 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001662 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001663 Binder.restoreCallingIdentity(origId);
1664 }
1665 }
1666 }
1667
1668 @Override
1669 public boolean finishActivityAffinity(IBinder token) {
1670 synchronized (mGlobalLock) {
1671 final long origId = Binder.clearCallingIdentity();
1672 try {
1673 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1674 if (r == null) {
1675 return false;
1676 }
1677
1678 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1679 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001680 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001681 return false;
1682 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001683
1684 final PooledFunction p = PooledLambda.obtainFunction(
1685 ActivityRecord::finishIfSameAffinity, r,
1686 PooledLambda.__(ActivityRecord.class));
1687 r.getTask().forAllActivities(
1688 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1689 p.recycle();
1690
Andrii Kuliande93eff2019-07-12 12:21:27 -07001691 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001692 } finally {
1693 Binder.restoreCallingIdentity(origId);
1694 }
1695 }
1696 }
1697
1698 @Override
1699 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1700 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001701 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001702 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001703 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001704 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1705 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001706 return;
1707 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001708 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1709 false /* processPausingActivities */, config);
1710 if (stopProfiling && r.hasProcess()) {
1711 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001712 }
1713 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001714 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001715 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001716 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001717 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001718 }
1719
1720 @Override
1721 public final void activityResumed(IBinder token) {
1722 final long origId = Binder.clearCallingIdentity();
1723 synchronized (mGlobalLock) {
1724 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001725 }
1726 Binder.restoreCallingIdentity(origId);
1727 }
1728
1729 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001730 public final void activityTopResumedStateLost() {
1731 final long origId = Binder.clearCallingIdentity();
1732 synchronized (mGlobalLock) {
1733 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1734 }
1735 Binder.restoreCallingIdentity(origId);
1736 }
1737
1738 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001739 public final void activityPaused(IBinder token) {
1740 final long origId = Binder.clearCallingIdentity();
1741 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001742 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001743 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1744 if (r != null) {
1745 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001746 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001747 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001748 }
1749 Binder.restoreCallingIdentity(origId);
1750 }
1751
1752 @Override
1753 public final void activityStopped(IBinder token, Bundle icicle,
1754 PersistableBundle persistentState, CharSequence description) {
1755 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1756
1757 // Refuse possible leaked file descriptors
1758 if (icicle != null && icicle.hasFileDescriptors()) {
1759 throw new IllegalArgumentException("File descriptors passed in Bundle");
1760 }
1761
1762 final long origId = Binder.clearCallingIdentity();
1763
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001764 String restartingName = null;
1765 int restartingUid = 0;
1766 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001767 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001768 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001769 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001770 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001771 if (r.attachedToProcess()
1772 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1773 // The activity was requested to restart from
1774 // {@link #restartActivityProcessIfVisible}.
1775 restartingName = r.app.mName;
1776 restartingUid = r.app.mUid;
1777 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001778 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001779 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001780 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001781 }
1782
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001783 if (restartingName != null) {
1784 // In order to let the foreground activity can be restarted with its saved state from
1785 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1786 // until the activity reports stopped with the state. And the activity record will be
1787 // kept because the record state is restarting, then the activity will be restarted
1788 // immediately if it is still the top one.
1789 mStackSupervisor.removeRestartTimeouts(r);
1790 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1791 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001792 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001793
1794 Binder.restoreCallingIdentity(origId);
1795 }
1796
1797 @Override
1798 public final void activityDestroyed(IBinder token) {
1799 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1800 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001801 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001802 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001803 try {
1804 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1805 if (activity != null) {
1806 activity.destroyed("activityDestroyed");
1807 }
1808 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001809 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001810 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001811 }
1812 }
1813 }
1814
1815 @Override
1816 public final void activityRelaunched(IBinder token) {
1817 final long origId = Binder.clearCallingIdentity();
1818 synchronized (mGlobalLock) {
1819 mStackSupervisor.activityRelaunchedLocked(token);
1820 }
1821 Binder.restoreCallingIdentity(origId);
1822 }
1823
1824 public final void activitySlept(IBinder token) {
1825 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1826
1827 final long origId = Binder.clearCallingIdentity();
1828
1829 synchronized (mGlobalLock) {
1830 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1831 if (r != null) {
1832 mStackSupervisor.activitySleptLocked(r);
1833 }
1834 }
1835
1836 Binder.restoreCallingIdentity(origId);
1837 }
1838
1839 @Override
1840 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1841 synchronized (mGlobalLock) {
1842 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1843 if (r == null) {
1844 return;
1845 }
1846 final long origId = Binder.clearCallingIdentity();
1847 try {
1848 r.setRequestedOrientation(requestedOrientation);
1849 } finally {
1850 Binder.restoreCallingIdentity(origId);
1851 }
1852 }
1853 }
1854
1855 @Override
1856 public int getRequestedOrientation(IBinder token) {
1857 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001858 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1859 return (r != null)
1860 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001861 }
1862 }
1863
1864 @Override
1865 public void setImmersive(IBinder token, boolean immersive) {
1866 synchronized (mGlobalLock) {
1867 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1868 if (r == null) {
1869 throw new IllegalArgumentException();
1870 }
1871 r.immersive = immersive;
1872
1873 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001874 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001875 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001876 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001877 }
1878 }
1879 }
1880
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001881 void applyUpdateLockStateLocked(ActivityRecord r) {
1882 // Modifications to the UpdateLock state are done on our handler, outside
1883 // the activity manager's locks. The new state is determined based on the
1884 // state *now* of the relevant activity record. The object is passed to
1885 // the handler solely for logging detail, not to be consulted/modified.
1886 final boolean nextState = r != null && r.immersive;
1887 mH.post(() -> {
1888 if (mUpdateLock.isHeld() != nextState) {
1889 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1890 "Applying new update lock state '" + nextState + "' for " + r);
1891 if (nextState) {
1892 mUpdateLock.acquire();
1893 } else {
1894 mUpdateLock.release();
1895 }
1896 }
1897 });
1898 }
1899
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001900 @Override
1901 public boolean isImmersive(IBinder token) {
1902 synchronized (mGlobalLock) {
1903 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1904 if (r == null) {
1905 throw new IllegalArgumentException();
1906 }
1907 return r.immersive;
1908 }
1909 }
1910
1911 @Override
1912 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001913 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001914 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001915 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001916 return (r != null) ? r.immersive : false;
1917 }
1918 }
1919
1920 @Override
1921 public void overridePendingTransition(IBinder token, String packageName,
1922 int enterAnim, int exitAnim) {
1923 synchronized (mGlobalLock) {
1924 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1925 if (self == null) {
1926 return;
1927 }
1928
1929 final long origId = Binder.clearCallingIdentity();
1930
1931 if (self.isState(
1932 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001933 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001934 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 }
1936
1937 Binder.restoreCallingIdentity(origId);
1938 }
1939 }
1940
1941 @Override
1942 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001943 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001944 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001945 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001946 if (r == null) {
1947 return ActivityManager.COMPAT_MODE_UNKNOWN;
1948 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001949 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001950 }
1951 }
1952
1953 @Override
1954 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001955 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001956 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001957 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001958 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001959 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001960 if (r == null) {
1961 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1962 return;
1963 }
1964 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001965 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001966 }
1967 }
1968
1969 @Override
1970 public int getLaunchedFromUid(IBinder activityToken) {
1971 ActivityRecord srec;
1972 synchronized (mGlobalLock) {
1973 srec = ActivityRecord.forTokenLocked(activityToken);
1974 }
1975 if (srec == null) {
1976 return -1;
1977 }
1978 return srec.launchedFromUid;
1979 }
1980
1981 @Override
1982 public String getLaunchedFromPackage(IBinder activityToken) {
1983 ActivityRecord srec;
1984 synchronized (mGlobalLock) {
1985 srec = ActivityRecord.forTokenLocked(activityToken);
1986 }
1987 if (srec == null) {
1988 return null;
1989 }
1990 return srec.launchedFromPackage;
1991 }
1992
1993 @Override
1994 public boolean convertFromTranslucent(IBinder token) {
1995 final long origId = Binder.clearCallingIdentity();
1996 try {
1997 synchronized (mGlobalLock) {
1998 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1999 if (r == null) {
2000 return false;
2001 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002002 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002003 }
2004 } finally {
2005 Binder.restoreCallingIdentity(origId);
2006 }
2007 }
2008
2009 @Override
2010 public boolean convertToTranslucent(IBinder token, Bundle options) {
2011 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2012 final long origId = Binder.clearCallingIdentity();
2013 try {
2014 synchronized (mGlobalLock) {
2015 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2016 if (r == null) {
2017 return false;
2018 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002019 final ActivityRecord under = r.getTask().getActivityBelow(r);
2020 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002021 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2022 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002023 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002024 }
2025 } finally {
2026 Binder.restoreCallingIdentity(origId);
2027 }
2028 }
2029
2030 @Override
2031 public void notifyActivityDrawn(IBinder token) {
2032 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2033 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002034 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002035 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002036 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002037 }
2038 }
2039 }
2040
2041 @Override
2042 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2043 synchronized (mGlobalLock) {
2044 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2045 if (r == null) {
2046 return;
2047 }
2048 r.reportFullyDrawnLocked(restoredFromBundle);
2049 }
2050 }
2051
2052 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002053 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002054 synchronized (mGlobalLock) {
2055 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale0b3d2922019-12-30 08:55:07 -08002056 if (stack != null && stack.getDisplayId() != INVALID_DISPLAY) {
2057 return stack.getDisplayId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002058 }
2059 return DEFAULT_DISPLAY;
2060 }
2061 }
2062
2063 @Override
2064 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002065 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002066 long ident = Binder.clearCallingIdentity();
2067 try {
2068 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002069 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002070 if (focusedStack != null) {
Louis Chang149d5c82019-12-30 09:47:39 +08002071 return mRootWindowContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002072 }
2073 return null;
2074 }
2075 } finally {
2076 Binder.restoreCallingIdentity(ident);
2077 }
2078 }
2079
2080 @Override
2081 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002082 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002083 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2084 final long callingId = Binder.clearCallingIdentity();
2085 try {
2086 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002087 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002088 if (stack == null) {
2089 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2090 return;
2091 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002092 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002093 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002094 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002095 }
2096 }
2097 } finally {
2098 Binder.restoreCallingIdentity(callingId);
2099 }
2100 }
2101
2102 @Override
2103 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002104 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002105 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2106 final long callingId = Binder.clearCallingIdentity();
2107 try {
2108 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002109 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002110 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002111 if (task == null) {
2112 return;
2113 }
2114 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002115 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002116 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002117 }
2118 }
2119 } finally {
2120 Binder.restoreCallingIdentity(callingId);
2121 }
2122 }
2123
2124 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002125 public void restartActivityProcessIfVisible(IBinder activityToken) {
2126 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2127 final long callingId = Binder.clearCallingIdentity();
2128 try {
2129 synchronized (mGlobalLock) {
2130 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2131 if (r == null) {
2132 return;
2133 }
2134 r.restartProcessIfVisible();
2135 }
2136 } finally {
2137 Binder.restoreCallingIdentity(callingId);
2138 }
2139 }
2140
2141 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002142 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002143 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002144 synchronized (mGlobalLock) {
2145 final long ident = Binder.clearCallingIdentity();
2146 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002147 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002148 "remove-task");
2149 } finally {
2150 Binder.restoreCallingIdentity(ident);
2151 }
2152 }
2153 }
2154
2155 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002156 public void removeAllVisibleRecentTasks() {
2157 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2158 synchronized (mGlobalLock) {
2159 final long ident = Binder.clearCallingIdentity();
2160 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002161 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002162 } finally {
2163 Binder.restoreCallingIdentity(ident);
2164 }
2165 }
2166 }
2167
2168 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002169 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2170 synchronized (mGlobalLock) {
2171 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2172 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002173 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002174 }
2175 }
2176 return false;
2177 }
2178
2179 @Override
2180 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2181 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002182
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002183 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002184 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2185 if (r != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002186 return r.getActivityStack().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002187 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002188 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002189 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002190 }
2191 }
2192
2193 /**
2194 * Attempts to move a task backwards in z-order (the order of activities within the task is
2195 * unchanged).
2196 *
2197 * There are several possible results of this call:
2198 * - if the task is locked, then we will show the lock toast
2199 * - if there is a task behind the provided task, then that task is made visible and resumed as
2200 * this task is moved to the back
2201 * - otherwise, if there are no other tasks in the stack:
2202 * - if this task is in the pinned stack, then we remove the stack completely, which will
2203 * have the effect of moving the task to the top or bottom of the fullscreen stack
2204 * (depending on whether it is visible)
2205 * - otherwise, we simply return home and hide this task
2206 *
2207 * @param token A reference to the activity we wish to move
2208 * @param nonRoot If false then this only works if the activity is the root
2209 * of a task; if true it will work for any activity in a task.
2210 * @return Returns true if the move completed, false if not.
2211 */
2212 @Override
2213 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002214 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002215 synchronized (mGlobalLock) {
2216 final long origId = Binder.clearCallingIdentity();
2217 try {
2218 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002219 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002220 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002221 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002222 }
2223 } finally {
2224 Binder.restoreCallingIdentity(origId);
2225 }
2226 }
2227 return false;
2228 }
2229
2230 @Override
2231 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002232 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002233 long ident = Binder.clearCallingIdentity();
2234 Rect rect = new Rect();
2235 try {
2236 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002237 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002238 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2239 if (task == null) {
2240 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2241 return rect;
2242 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002243 if (task.getParent() != null) {
2244 rect.set(task.getBounds());
2245 } else if (task.mLastNonFullscreenBounds != null) {
2246 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002247 }
2248 }
2249 } finally {
2250 Binder.restoreCallingIdentity(ident);
2251 }
2252 return rect;
2253 }
2254
2255 @Override
2256 public ActivityManager.TaskDescription getTaskDescription(int id) {
2257 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002258 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002259 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002260 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002261 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2262 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002263 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002264 }
2265 }
2266 return null;
2267 }
2268
2269 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002270 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2271 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2272 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2273 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2274 return;
2275 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002276 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002277 synchronized (mGlobalLock) {
2278 final long ident = Binder.clearCallingIdentity();
2279 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002280 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002281 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002282 if (task == null) {
2283 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2284 return;
2285 }
2286
2287 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2288 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2289
2290 if (!task.isActivityTypeStandardOrUndefined()) {
2291 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2292 + " non-standard task " + taskId + " to windowing mode="
2293 + windowingMode);
2294 }
2295
2296 final ActivityStack stack = task.getStack();
2297 if (toTop) {
2298 stack.moveToFront("setTaskWindowingMode", task);
2299 }
2300 stack.setWindowingMode(windowingMode);
2301 } finally {
2302 Binder.restoreCallingIdentity(ident);
2303 }
2304 }
2305 }
2306
2307 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002308 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002309 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002310 ActivityRecord r = getCallingRecordLocked(token);
2311 return r != null ? r.info.packageName : null;
2312 }
2313 }
2314
2315 @Override
2316 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002317 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002318 ActivityRecord r = getCallingRecordLocked(token);
2319 return r != null ? r.intent.getComponent() : null;
2320 }
2321 }
2322
2323 private ActivityRecord getCallingRecordLocked(IBinder token) {
2324 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2325 if (r == null) {
2326 return null;
2327 }
2328 return r.resultTo;
2329 }
2330
2331 @Override
2332 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002333 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002334
2335 synchronized (mGlobalLock) {
2336 final long origId = Binder.clearCallingIdentity();
2337 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002338 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002339 } finally {
2340 Binder.restoreCallingIdentity(origId);
2341 }
2342 }
2343 }
2344
Mark Renouf446251d2019-04-26 10:22:41 -04002345 @Override
2346 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2347 synchronized (mGlobalLock) {
2348 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2349 if (r == null) {
2350 return;
2351 }
2352 ActivityStack stack = r.getActivityStack();
2353 if (stack != null && stack.isSingleTaskInstance()) {
2354 // Single-task stacks are used for activities which are presented in floating
2355 // windows above full screen activities. Instead of directly finishing the
2356 // task, a task change listener is used to notify SystemUI so the action can be
2357 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002358 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002359 mTaskChangeNotificationController
2360 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2361 } else {
2362 try {
2363 callback.requestFinish();
2364 } catch (RemoteException e) {
2365 Slog.e(TAG, "Failed to invoke request finish callback", e);
2366 }
2367 }
2368 }
2369 }
2370
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002371 /**
2372 * TODO: Add mController hook
2373 */
2374 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002375 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2376 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002377 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002378
2379 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2380 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002381 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2382 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002383 }
2384 }
2385
Ricky Waiaca8a772019-04-04 16:01:06 +01002386 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2387 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002388 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002389
Ricky Waiaca8a772019-04-04 16:01:06 +01002390 final int callingPid = Binder.getCallingPid();
2391 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002392 if (!isSameApp(callingUid, callingPackage)) {
2393 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2394 + Binder.getCallingPid() + " as package " + callingPackage;
2395 Slog.w(TAG, msg);
2396 throw new SecurityException(msg);
2397 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002398 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002399 SafeActivityOptions.abort(options);
2400 return;
2401 }
2402 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002403 WindowProcessController callerApp = null;
2404 if (appThread != null) {
2405 callerApp = getProcessController(appThread);
2406 }
2407 final ActivityStarter starter = getActivityStartController().obtainStarter(
2408 null /* intent */, "moveTaskToFront");
2409 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2410 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002411 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002412 return;
2413 }
2414 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002415 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002416 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002417 if (task == null) {
2418 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002419 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002420 return;
2421 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002422 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002423 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002424 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002425 return;
2426 }
2427 ActivityOptions realOptions = options != null
2428 ? options.getOptions(mStackSupervisor)
2429 : null;
2430 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2431 false /* forceNonResizable */);
2432
Wale Ogunwale21e06482019-11-18 05:14:15 -08002433 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002434 if (topActivity != null) {
2435
2436 // We are reshowing a task, use a starting window to hide the initial draw delay
2437 // so the transition can start earlier.
2438 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2439 true /* taskSwitch */, fromRecents);
2440 }
2441 } finally {
2442 Binder.restoreCallingIdentity(origId);
2443 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002444 }
2445
Ricky Waiaca8a772019-04-04 16:01:06 +01002446 /**
2447 * Return true if callingUid is system, or packageName belongs to that callingUid.
2448 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002449 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002450 try {
2451 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2452 if (packageName == null) {
2453 return false;
2454 }
2455 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2456 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2457 UserHandle.getUserId(callingUid));
2458 return UserHandle.isSameApp(callingUid, uid);
2459 }
2460 } catch (RemoteException e) {
2461 // Should not happen
2462 }
2463 return true;
2464 }
2465
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002466 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2467 int callingPid, int callingUid, String name) {
2468 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2469 return true;
2470 }
2471
2472 if (getRecentTasks().isCallerRecents(sourceUid)) {
2473 return true;
2474 }
2475
2476 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2477 if (perm == PackageManager.PERMISSION_GRANTED) {
2478 return true;
2479 }
2480 if (checkAllowAppSwitchUid(sourceUid)) {
2481 return true;
2482 }
2483
2484 // If the actual IPC caller is different from the logical source, then
2485 // also see if they are allowed to control app switches.
2486 if (callingUid != -1 && callingUid != sourceUid) {
2487 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2488 if (perm == PackageManager.PERMISSION_GRANTED) {
2489 return true;
2490 }
2491 if (checkAllowAppSwitchUid(callingUid)) {
2492 return true;
2493 }
2494 }
2495
2496 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2497 return false;
2498 }
2499
2500 private boolean checkAllowAppSwitchUid(int uid) {
2501 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2502 if (types != null) {
2503 for (int i = types.size() - 1; i >= 0; i--) {
2504 if (types.valueAt(i).intValue() == uid) {
2505 return true;
2506 }
2507 }
2508 }
2509 return false;
2510 }
2511
2512 @Override
2513 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2514 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2515 "setActivityController()");
2516 synchronized (mGlobalLock) {
2517 mController = controller;
2518 mControllerIsAMonkey = imAMonkey;
2519 Watchdog.getInstance().setActivityController(controller);
2520 }
2521 }
2522
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002523 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002524 synchronized (mGlobalLock) {
2525 return mController != null && mControllerIsAMonkey;
2526 }
2527 }
2528
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002529 @Override
2530 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2531 synchronized (mGlobalLock) {
2532 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2533 }
2534 }
2535
2536 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002537 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2538 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2539 }
2540
2541 @Override
2542 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2543 @WindowConfiguration.ActivityType int ignoreActivityType,
2544 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2545 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002546 final int callingPid = Binder.getCallingPid();
2547 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002548 final int[] profileIds = getUserManager().getProfileIds(
2549 UserHandle.getUserId(callingUid), true);
2550 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2551 for (int i = 0; i < profileIds.length; i++) {
2552 callingProfileIds.add(profileIds[i]);
2553 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002554 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2555
2556 synchronized (mGlobalLock) {
2557 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2558
Nicholas Sauer0259e532019-08-30 08:24:55 -07002559 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002560 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002561 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002562 }
2563
2564 return list;
2565 }
2566
2567 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002568 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2569 synchronized (mGlobalLock) {
2570 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002571 try {
2572 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2573 if (r == null) return;
2574
2575 final PooledConsumer c = PooledLambda.obtainConsumer(
2576 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2577 r, resultWho, requestCode);
2578 // TODO: This should probably only loop over the task since you need to be in the
2579 // same task to return results.
2580 r.getActivityStack().forAllActivities(c);
2581 c.recycle();
2582
2583 updateOomAdj();
2584 } finally {
2585 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002586 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002587 }
2588 }
2589
2590 @Override
2591 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002592 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002593 ActivityStack stack = ActivityRecord.getStackLocked(token);
2594 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002595 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002596 }
2597 return false;
2598 }
2599 }
2600
2601 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002602 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002603 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002604 synchronized (mGlobalLock) {
2605 final long ident = Binder.clearCallingIdentity();
2606 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002607 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002608 if (task == null) {
2609 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2610 return;
2611 }
2612
2613 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2614 + " to stackId=" + stackId + " toTop=" + toTop);
2615
Louis Chang149d5c82019-12-30 09:47:39 +08002616 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002617 if (stack == null) {
2618 throw new IllegalStateException(
2619 "moveTaskToStack: No stack for stackId=" + stackId);
2620 }
2621 if (!stack.isActivityTypeStandardOrUndefined()) {
2622 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2623 + taskId + " to stack " + stackId);
2624 }
2625 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002626 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002627 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2628 }
2629 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2630 "moveTaskToStack");
2631 } finally {
2632 Binder.restoreCallingIdentity(ident);
2633 }
2634 }
2635 }
2636
2637 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002638 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2639 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002640
2641 final long ident = Binder.clearCallingIdentity();
2642 try {
2643 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002644 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Evan Roskydbe2ce52019-07-18 11:13:17 -07002645 if (stack == null) {
2646 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2647 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002648 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002649 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2650 throw new IllegalArgumentException("Stack: " + stackId
2651 + " doesn't support animated resize.");
2652 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002653 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002654 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002655 }
2656 } finally {
2657 Binder.restoreCallingIdentity(ident);
2658 }
2659 }
2660
wilsonshih5c4cf522019-01-25 09:03:47 +08002661 @Override
2662 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2663 int animationDuration) {
2664 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2665
2666 final long ident = Binder.clearCallingIdentity();
2667 try {
2668 synchronized (mGlobalLock) {
2669 if (xOffset == 0 && yOffset == 0) {
2670 return;
2671 }
Louis Chang149d5c82019-12-30 09:47:39 +08002672 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
wilsonshih5c4cf522019-01-25 09:03:47 +08002673 if (stack == null) {
2674 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2675 return;
2676 }
2677 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2678 throw new IllegalArgumentException("Stack: " + stackId
2679 + " doesn't support animated resize.");
2680 }
2681 final Rect destBounds = new Rect();
2682 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002683 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002684 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2685 return;
2686 }
2687 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002688 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002689 animationDuration, false /* fromFullscreen */);
2690 }
2691 } finally {
2692 Binder.restoreCallingIdentity(ident);
2693 }
2694 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002695 /**
2696 * Moves the specified task to the primary-split-screen stack.
2697 *
2698 * @param taskId Id of task to move.
2699 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2700 * exist already. See
2701 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2702 * and
2703 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2704 * @param toTop If the task and stack should be moved to the top.
2705 * @param animate Whether we should play an animation for the moving the task.
2706 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2707 * stack. Pass {@code null} to use default bounds.
2708 * @param showRecents If the recents activity should be shown on the other side of the task
2709 * going into split-screen mode.
2710 */
2711 @Override
2712 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2713 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002714 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002715 "setTaskWindowingModeSplitScreenPrimary()");
2716 synchronized (mGlobalLock) {
2717 final long ident = Binder.clearCallingIdentity();
2718 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002719 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002720 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002721 if (task == null) {
2722 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2723 return false;
2724 }
2725 if (DEBUG_STACK) Slog.d(TAG_STACK,
2726 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2727 + " to createMode=" + createMode + " toTop=" + toTop);
2728 if (!task.isActivityTypeStandardOrUndefined()) {
2729 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2730 + " non-standard task " + taskId + " to split-screen windowing mode");
2731 }
2732
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002733 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002734 final int windowingMode = task.getWindowingMode();
2735 final ActivityStack stack = task.getStack();
2736 if (toTop) {
2737 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2738 }
2739 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002740 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2741 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002742 return windowingMode != task.getWindowingMode();
2743 } finally {
2744 Binder.restoreCallingIdentity(ident);
2745 }
2746 }
2747 }
2748
2749 /**
2750 * Removes stacks in the input windowing modes from the system if they are of activity type
2751 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2752 */
2753 @Override
2754 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002755 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002756 "removeStacksInWindowingModes()");
2757
2758 synchronized (mGlobalLock) {
2759 final long ident = Binder.clearCallingIdentity();
2760 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002761 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002762 } finally {
2763 Binder.restoreCallingIdentity(ident);
2764 }
2765 }
2766 }
2767
2768 @Override
2769 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002770 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002771 "removeStacksWithActivityTypes()");
2772
2773 synchronized (mGlobalLock) {
2774 final long ident = Binder.clearCallingIdentity();
2775 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002776 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002777 } finally {
2778 Binder.restoreCallingIdentity(ident);
2779 }
2780 }
2781 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002782
2783 @Override
2784 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2785 int userId) {
2786 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002787 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2788 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002789 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002790 final boolean detailed = checkGetTasksPermission(
2791 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2792 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002793 == PackageManager.PERMISSION_GRANTED;
2794
2795 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002796 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002797 callingUid);
2798 }
2799 }
2800
2801 @Override
2802 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002803 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002804 long ident = Binder.clearCallingIdentity();
2805 try {
2806 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002807 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002808 }
2809 } finally {
2810 Binder.restoreCallingIdentity(ident);
2811 }
2812 }
2813
2814 @Override
2815 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002816 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002817 long ident = Binder.clearCallingIdentity();
2818 try {
2819 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002820 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002821 }
2822 } finally {
2823 Binder.restoreCallingIdentity(ident);
2824 }
2825 }
2826
2827 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002828 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2829 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2830 long ident = Binder.clearCallingIdentity();
2831 try {
2832 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002833 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002834 }
2835 } finally {
2836 Binder.restoreCallingIdentity(ident);
2837 }
2838 }
2839
2840 @Override
2841 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2842 int displayId) {
2843 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2844 long ident = Binder.clearCallingIdentity();
2845 try {
2846 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002847 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002848 }
2849 } finally {
2850 Binder.restoreCallingIdentity(ident);
2851 }
2852 }
2853
2854 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002855 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002856 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002857 final long callingUid = Binder.getCallingUid();
2858 final long origId = Binder.clearCallingIdentity();
2859 try {
2860 synchronized (mGlobalLock) {
2861 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002862 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002863 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2864 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2865 }
2866 } finally {
2867 Binder.restoreCallingIdentity(origId);
2868 }
2869 }
2870
2871 @Override
2872 public void startLockTaskModeByToken(IBinder token) {
2873 synchronized (mGlobalLock) {
2874 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2875 if (r == null) {
2876 return;
2877 }
Louis Changcdec0802019-11-11 11:45:07 +08002878 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002879 }
2880 }
2881
2882 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002883 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002884 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002885 // This makes inner call to look as if it was initiated by system.
2886 long ident = Binder.clearCallingIdentity();
2887 try {
2888 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002889 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002890 MATCH_TASK_IN_STACKS_ONLY);
2891 if (task == null) {
2892 return;
2893 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002894
2895 // When starting lock task mode the stack must be in front and focused
2896 task.getStack().moveToFront("startSystemLockTaskMode");
2897 startLockTaskModeLocked(task, true /* isSystemCaller */);
2898 }
2899 } finally {
2900 Binder.restoreCallingIdentity(ident);
2901 }
2902 }
2903
2904 @Override
2905 public void stopLockTaskModeByToken(IBinder token) {
2906 synchronized (mGlobalLock) {
2907 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2908 if (r == null) {
2909 return;
2910 }
Louis Changcdec0802019-11-11 11:45:07 +08002911 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002912 }
2913 }
2914
2915 /**
2916 * This API should be called by SystemUI only when user perform certain action to dismiss
2917 * lock task mode. We should only dismiss pinned lock task mode in this case.
2918 */
2919 @Override
2920 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002921 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002922 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2923 }
2924
Louis Changcdec0802019-11-11 11:45:07 +08002925 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002926 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2927 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2928 return;
2929 }
2930
Louis Chang149d5c82019-12-30 09:47:39 +08002931 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002932 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002933 throw new IllegalArgumentException("Invalid task, not in foreground");
2934 }
2935
2936 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2937 // system or a specific app.
2938 // * System-initiated requests will only start the pinned mode (screen pinning)
2939 // * App-initiated requests
2940 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2941 // - will start the pinned mode, otherwise
2942 final int callingUid = Binder.getCallingUid();
2943 long ident = Binder.clearCallingIdentity();
2944 try {
2945 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002946 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002947
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002948 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002949 } finally {
2950 Binder.restoreCallingIdentity(ident);
2951 }
2952 }
2953
Louis Changcdec0802019-11-11 11:45:07 +08002954 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002955 final int callingUid = Binder.getCallingUid();
2956 long ident = Binder.clearCallingIdentity();
2957 try {
2958 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002959 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002960 }
2961 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2962 // task and jumping straight into a call in the case of emergency call back.
2963 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2964 if (tm != null) {
2965 tm.showInCallScreen(false);
2966 }
2967 } finally {
2968 Binder.restoreCallingIdentity(ident);
2969 }
2970 }
2971
2972 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002973 public void updateLockTaskPackages(int userId, String[] packages) {
2974 final int callingUid = Binder.getCallingUid();
2975 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2976 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2977 "updateLockTaskPackages()");
2978 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002979 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002980 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2981 + Arrays.toString(packages));
2982 getLockTaskController().updateLockTaskPackages(userId, packages);
2983 }
2984 }
2985
2986 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002987 public boolean isInLockTaskMode() {
2988 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2989 }
2990
2991 @Override
2992 public int getLockTaskModeState() {
2993 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002994 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002995 }
2996 }
2997
2998 @Override
2999 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3000 synchronized (mGlobalLock) {
3001 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3002 if (r != null) {
3003 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003004 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003005 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003006 }
3007 }
3008 }
3009
3010 @Override
3011 public Bundle getActivityOptions(IBinder token) {
3012 final long origId = Binder.clearCallingIdentity();
3013 try {
3014 synchronized (mGlobalLock) {
3015 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3016 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003017 final ActivityOptions activityOptions = r.takeOptionsLocked(
3018 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003019 return activityOptions == null ? null : activityOptions.toBundle();
3020 }
3021 return null;
3022 }
3023 } finally {
3024 Binder.restoreCallingIdentity(origId);
3025 }
3026 }
3027
3028 @Override
3029 public List<IBinder> getAppTasks(String callingPackage) {
3030 int callingUid = Binder.getCallingUid();
3031 long ident = Binder.clearCallingIdentity();
3032 try {
3033 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003034 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003035 }
3036 } finally {
3037 Binder.restoreCallingIdentity(ident);
3038 }
3039 }
3040
3041 @Override
3042 public void finishVoiceTask(IVoiceInteractionSession session) {
3043 synchronized (mGlobalLock) {
3044 final long origId = Binder.clearCallingIdentity();
3045 try {
3046 // TODO: VI Consider treating local voice interactions and voice tasks
3047 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003048 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003049 } finally {
3050 Binder.restoreCallingIdentity(origId);
3051 }
3052 }
3053
3054 }
3055
3056 @Override
3057 public boolean isTopOfTask(IBinder token) {
3058 synchronized (mGlobalLock) {
3059 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003060 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003061 }
3062 }
3063
3064 @Override
3065 public void notifyLaunchTaskBehindComplete(IBinder token) {
3066 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3067 }
3068
3069 @Override
3070 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003071 mH.post(() -> {
3072 synchronized (mGlobalLock) {
3073 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003074 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003075 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003076 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003077 } catch (RemoteException e) {
3078 }
3079 }
3080 }
3081
3082 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003083 }
3084
3085 /** Called from an app when assist data is ready. */
3086 @Override
3087 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3088 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003089 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003090 synchronized (pae) {
3091 pae.result = extras;
3092 pae.structure = structure;
3093 pae.content = content;
3094 if (referrer != null) {
3095 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3096 }
3097 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003098 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003099 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003100 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003101 structure.setHomeActivity(pae.isHome);
3102 }
3103 pae.haveResult = true;
3104 pae.notifyAll();
3105 if (pae.intent == null && pae.receiver == null) {
3106 // Caller is just waiting for the result.
3107 return;
3108 }
3109 }
3110 // We are now ready to launch the assist activity.
3111 IAssistDataReceiver sendReceiver = null;
3112 Bundle sendBundle = null;
3113 synchronized (mGlobalLock) {
3114 buildAssistBundleLocked(pae, extras);
3115 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003116 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003117 if (!exists) {
3118 // Timed out.
3119 return;
3120 }
3121
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003122 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003123 // Caller wants result sent back to them.
3124 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003125 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003126 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003127 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3128 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003129 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3130 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3131 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3132 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3133 }
3134 }
3135 if (sendReceiver != null) {
3136 try {
3137 sendReceiver.onHandleAssistData(sendBundle);
3138 } catch (RemoteException e) {
3139 }
3140 return;
3141 }
3142
3143 final long ident = Binder.clearCallingIdentity();
3144 try {
3145 if (TextUtils.equals(pae.intent.getAction(),
3146 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003147 // Start voice interaction through VoiceInteractionManagerService.
3148 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3149 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003150 } else {
3151 pae.intent.replaceExtras(pae.extras);
3152 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3153 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3154 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003155 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003156
3157 try {
3158 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3159 } catch (ActivityNotFoundException e) {
3160 Slog.w(TAG, "No activity to handle assist action.", e);
3161 }
3162 }
3163 } finally {
3164 Binder.restoreCallingIdentity(ident);
3165 }
3166 }
3167
3168 @Override
3169 public int addAppTask(IBinder activityToken, Intent intent,
3170 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3171 final int callingUid = Binder.getCallingUid();
3172 final long callingIdent = Binder.clearCallingIdentity();
3173
3174 try {
3175 synchronized (mGlobalLock) {
3176 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3177 if (r == null) {
3178 throw new IllegalArgumentException("Activity does not exist; token="
3179 + activityToken);
3180 }
3181 ComponentName comp = intent.getComponent();
3182 if (comp == null) {
3183 throw new IllegalArgumentException("Intent " + intent
3184 + " must specify explicit component");
3185 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003186 if (thumbnail.getWidth() != mThumbnailWidth
3187 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003188 throw new IllegalArgumentException("Bad thumbnail size: got "
3189 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003190 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003191 }
3192 if (intent.getSelector() != null) {
3193 intent.setSelector(null);
3194 }
3195 if (intent.getSourceBounds() != null) {
3196 intent.setSourceBounds(null);
3197 }
3198 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3199 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3200 // The caller has added this as an auto-remove task... that makes no
3201 // sense, so turn off auto-remove.
3202 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3203 }
3204 }
3205 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3206 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3207 if (ainfo.applicationInfo.uid != callingUid) {
3208 throw new SecurityException(
3209 "Can't add task for another application: target uid="
3210 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3211 }
3212
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003213 final ActivityStack stack = r.getActivityStack();
Louis Changcdec0802019-11-11 11:45:07 +08003214 final Task task = stack.createTask(
Wale Ogunwale0b3d2922019-12-30 08:55:07 -08003215 mStackSupervisor.getNextTaskIdForUser(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003216 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003217 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003218 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003219 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003220 return INVALID_TASK_ID;
3221 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003222 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003223
3224 // TODO: Send the thumbnail to WM to store it.
3225
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003226 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003227 }
3228 } finally {
3229 Binder.restoreCallingIdentity(callingIdent);
3230 }
3231 }
3232
3233 @Override
3234 public Point getAppTaskThumbnailSize() {
3235 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003236 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003237 }
3238 }
3239
3240 @Override
3241 public void setTaskResizeable(int taskId, int resizeableMode) {
3242 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003243 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003244 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3245 if (task == null) {
3246 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3247 return;
3248 }
3249 task.setResizeMode(resizeableMode);
3250 }
3251 }
3252
3253 @Override
3254 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003255 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003256 long ident = Binder.clearCallingIdentity();
3257 try {
3258 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003259 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003260 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003261 if (task == null) {
3262 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3263 return;
3264 }
3265 // Place the task in the right stack if it isn't there already based on
3266 // the requested bounds.
3267 // The stack transition logic is:
3268 // - a null bounds on a freeform task moves that task to fullscreen
3269 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3270 // that task to freeform
3271 // - otherwise the task is not moved
3272 ActivityStack stack = task.getStack();
3273 if (!task.getWindowConfiguration().canResizeTask()) {
3274 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3275 }
3276 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3277 stack = stack.getDisplay().getOrCreateStack(
3278 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3279 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3280 stack = stack.getDisplay().getOrCreateStack(
3281 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3282 }
3283
3284 // Reparent the task to the right stack if necessary
3285 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3286 if (stack != task.getStack()) {
3287 // Defer resume until the task is resized below
3288 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3289 DEFER_RESUME, "resizeTask");
3290 preserveWindow = false;
3291 }
3292
3293 // After reparenting (which only resizes the task to the stack bounds), resize the
3294 // task to the actual bounds provided
3295 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3296 }
3297 } finally {
3298 Binder.restoreCallingIdentity(ident);
3299 }
3300 }
3301
Evan Roskyddedfd42019-10-04 13:38:38 -07003302 private void sanitizeAndApplyConfigChange(ConfigurationContainer container,
3303 WindowContainerTransaction.Change change) {
Evan Rosky282ee672019-11-13 15:50:46 -08003304 if (!(container instanceof Task || container instanceof ActivityStack)) {
Evan Roskyddedfd42019-10-04 13:38:38 -07003305 throw new RuntimeException("Invalid token in task transaction");
3306 }
3307 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3308 // masks here.
3309 int configMask = change.getConfigSetMask();
3310 int windowMask = change.getWindowSetMask();
3311 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3312 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3313 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
3314 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3315 c.setTo(change.getConfiguration(), configMask, windowMask);
3316 container.onRequestedOverrideConfigurationChanged(c);
Hongwei Wangebf18082019-09-26 14:25:11 -07003317 // TODO(b/145675353): remove the following once we could apply new bounds to the
3318 // pinned stack together with its children.
3319 resizePinnedStackIfNeeded(container, configMask, windowMask, c);
3320 }
3321
3322 private void resizePinnedStackIfNeeded(ConfigurationContainer container, int configMask,
3323 int windowMask, Configuration config) {
3324 if ((container instanceof ActivityStack)
3325 && ((configMask & ActivityInfo.CONFIG_WINDOW_CONFIGURATION) != 0)
3326 && ((windowMask & WindowConfiguration.WINDOW_CONFIG_BOUNDS) != 0)) {
3327 final ActivityStack stack = (ActivityStack) container;
3328 if (stack.inPinnedWindowingMode()) {
3329 stack.resize(config.windowConfiguration.getBounds(),
3330 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
3331 PRESERVE_WINDOWS, true /* deferResume */);
3332 }
3333 }
Evan Roskyddedfd42019-10-04 13:38:38 -07003334 }
3335
Robert Carr8a2f9132019-11-11 15:03:15 -08003336 private void applyWindowContainerChange(ConfigurationContainer cc,
3337 WindowContainerTransaction.Change c) {
3338 sanitizeAndApplyConfigChange(cc, c);
3339
3340 Rect enterPipBounds = c.getEnterPipBounds();
3341 if (enterPipBounds != null) {
3342 Task tr = (Task) cc;
3343 mStackSupervisor.updatePictureInPictureMode(tr,
3344 enterPipBounds, true);
3345 }
3346 }
3347
Evan Roskyddedfd42019-10-04 13:38:38 -07003348 @Override
3349 public void applyContainerTransaction(WindowContainerTransaction t) {
3350 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
3351 long ident = Binder.clearCallingIdentity();
3352 try {
3353 if (t == null) {
3354 return;
3355 }
3356 synchronized (mGlobalLock) {
3357 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3358 t.getChanges().entrySet().iterator();
3359 while (entries.hasNext()) {
3360 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3361 entries.next();
3362 final ConfigurationContainer cc = ConfigurationContainer.RemoteToken.fromBinder(
3363 entry.getKey()).getContainer();
Robert Carr8a2f9132019-11-11 15:03:15 -08003364 applyWindowContainerChange(cc, entry.getValue());
Evan Roskyddedfd42019-10-04 13:38:38 -07003365 }
3366 }
3367 } finally {
3368 Binder.restoreCallingIdentity(ident);
3369 }
3370 }
3371
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003372 @Override
3373 public boolean releaseActivityInstance(IBinder token) {
3374 synchronized (mGlobalLock) {
3375 final long origId = Binder.clearCallingIdentity();
3376 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003377 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3378 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003379 return false;
3380 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003381 r.destroyImmediately(true /* removeFromApp */, "app-req");
3382 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383 } finally {
3384 Binder.restoreCallingIdentity(origId);
3385 }
3386 }
3387 }
3388
3389 @Override
3390 public void releaseSomeActivities(IApplicationThread appInt) {
3391 synchronized (mGlobalLock) {
3392 final long origId = Binder.clearCallingIdentity();
3393 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003394 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003395 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003396 } finally {
3397 Binder.restoreCallingIdentity(origId);
3398 }
3399 }
3400 }
3401
3402 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003403 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003404 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003405 != PackageManager.PERMISSION_GRANTED) {
3406 throw new SecurityException("Requires permission "
3407 + android.Manifest.permission.DEVICE_POWER);
3408 }
3409
3410 synchronized (mGlobalLock) {
3411 long ident = Binder.clearCallingIdentity();
3412 if (mKeyguardShown != keyguardShowing) {
3413 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003414 final Message msg = PooledLambda.obtainMessage(
3415 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3416 keyguardShowing);
3417 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003418 }
3419 try {
wilsonshih177261f2019-02-22 12:02:18 +08003420 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003421 } finally {
3422 Binder.restoreCallingIdentity(ident);
3423 }
3424 }
3425
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003426 mH.post(() -> {
3427 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3428 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3429 }
3430 });
3431 }
3432
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003433 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003434 mH.post(() -> {
3435 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3436 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3437 }
3438 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003439 }
3440
3441 @Override
3442 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003443 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3444 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003445
3446 final File passedIconFile = new File(filePath);
3447 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3448 passedIconFile.getName());
3449 if (!legitIconFile.getPath().equals(filePath)
3450 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3451 throw new IllegalArgumentException("Bad file path: " + filePath
3452 + " passed for userId " + userId);
3453 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003454 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003455 }
3456
3457 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003458 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003459 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003460 synchronized (mGlobalLock) {
3461 final long ident = Binder.clearCallingIdentity();
3462 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003463 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003464 if (stack == null) {
3465 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3466 return;
3467 }
3468 if (!stack.isActivityTypeStandardOrUndefined()) {
3469 throw new IllegalArgumentException(
3470 "Removing non-standard stack is not allowed.");
3471 }
3472 mStackSupervisor.removeStack(stack);
3473 } finally {
3474 Binder.restoreCallingIdentity(ident);
3475 }
3476 }
3477 }
3478
3479 @Override
3480 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003481 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003482
3483 synchronized (mGlobalLock) {
3484 final long ident = Binder.clearCallingIdentity();
3485 try {
3486 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3487 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003488 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003489 } finally {
3490 Binder.restoreCallingIdentity(ident);
3491 }
3492 }
3493 }
3494
3495 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003496 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003497 synchronized (mGlobalLock) {
3498 long ident = Binder.clearCallingIdentity();
3499 try {
3500 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3501 if (r == null) {
3502 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003503 "toggleFreeformWindowingMode: No activity record matching token="
3504 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003505 }
3506
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003507 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003508 if (stack == null) {
3509 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3510 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003511 }
3512
Yunfan Chend967af82019-01-17 18:30:18 +09003513 if (!stack.inFreeformWindowingMode()
3514 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3515 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3516 + "toggle between fullscreen and freeform.");
3517 }
3518
3519 if (stack.inFreeformWindowingMode()) {
3520 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003521 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003522 throw new IllegalStateException("Size-compat windows are currently not"
3523 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003524 } else if (stack.getParent().inFreeformWindowingMode()) {
3525 // If the window is on a freeform display, set it to undefined. It will be
3526 // resolved to freeform and it can adjust windowing mode when the display mode
3527 // changes in runtime.
3528 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003529 } else {
3530 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3531 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003532 } finally {
3533 Binder.restoreCallingIdentity(ident);
3534 }
3535 }
3536 }
3537
3538 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3539 @Override
3540 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003541 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003542 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003543 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003544 }
3545
3546 /** Unregister a task stack listener so that it stops receiving callbacks. */
3547 @Override
3548 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003549 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003550 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003551 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003552 }
3553
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003554 @Override
3555 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3556 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3557 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3558 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3559 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3560 }
3561
3562 @Override
3563 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3564 IBinder activityToken, int flags) {
3565 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3566 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3567 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3568 }
3569
3570 @Override
3571 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3572 Bundle args) {
3573 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3574 true /* focused */, true /* newSessionId */, userHandle, args,
3575 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3576 }
3577
3578 @Override
3579 public Bundle getAssistContextExtras(int requestType) {
3580 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3581 null, null, true /* focused */, true /* newSessionId */,
3582 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3583 if (pae == null) {
3584 return null;
3585 }
3586 synchronized (pae) {
3587 while (!pae.haveResult) {
3588 try {
3589 pae.wait();
3590 } catch (InterruptedException e) {
3591 }
3592 }
3593 }
3594 synchronized (mGlobalLock) {
3595 buildAssistBundleLocked(pae, pae.result);
3596 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003597 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003598 }
3599 return pae.extras;
3600 }
3601
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003602 /**
3603 * Binder IPC calls go through the public entry point.
3604 * This can be called with or without the global lock held.
3605 */
3606 private static int checkCallingPermission(String permission) {
3607 return checkPermission(
3608 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3609 }
3610
3611 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003612 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003613 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3614 mAmInternal.enforceCallingPermission(permission, func);
3615 }
3616 }
3617
3618 @VisibleForTesting
3619 int checkGetTasksPermission(String permission, int pid, int uid) {
3620 return checkPermission(permission, pid, uid);
3621 }
3622
3623 static int checkPermission(String permission, int pid, int uid) {
3624 if (permission == null) {
3625 return PackageManager.PERMISSION_DENIED;
3626 }
3627 return checkComponentPermission(permission, pid, uid, -1, true);
3628 }
3629
Wale Ogunwale214f3482018-10-04 11:00:47 -07003630 public static int checkComponentPermission(String permission, int pid, int uid,
3631 int owningUid, boolean exported) {
3632 return ActivityManagerService.checkComponentPermission(
3633 permission, pid, uid, owningUid, exported);
3634 }
3635
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003636 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3637 if (getRecentTasks().isCallerRecents(callingUid)) {
3638 // Always allow the recents component to get tasks
3639 return true;
3640 }
3641
3642 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3643 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3644 if (!allowed) {
3645 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3646 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3647 // Temporary compatibility: some existing apps on the system image may
3648 // still be requesting the old permission and not switched to the new
3649 // one; if so, we'll still allow them full access. This means we need
3650 // to see if they are holding the old permission and are a system app.
3651 try {
3652 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3653 allowed = true;
3654 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3655 + " is using old GET_TASKS but privileged; allowing");
3656 }
3657 } catch (RemoteException e) {
3658 }
3659 }
3660 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3661 + " does not hold REAL_GET_TASKS; limiting output");
3662 }
3663 return allowed;
3664 }
3665
Nicholas Sauer0259e532019-08-30 08:24:55 -07003666 boolean isCrossUserAllowed(int pid, int uid) {
3667 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3668 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3669 }
3670
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003671 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3672 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3673 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3674 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003675 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003676 "enqueueAssistContext()");
3677
3678 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003679 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003680 if (activity == null) {
3681 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3682 return null;
3683 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003684 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003685 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3686 return null;
3687 }
3688 if (focused) {
3689 if (activityToken != null) {
3690 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3691 if (activity != caller) {
3692 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3693 + " is not current top " + activity);
3694 return null;
3695 }
3696 }
3697 } else {
3698 activity = ActivityRecord.forTokenLocked(activityToken);
3699 if (activity == null) {
3700 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3701 + " couldn't be found");
3702 return null;
3703 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003704 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003705 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3706 return null;
3707 }
3708 }
3709
3710 PendingAssistExtras pae;
3711 Bundle extras = new Bundle();
3712 if (args != null) {
3713 extras.putAll(args);
3714 }
3715 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003716 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003717
3718 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3719 userHandle);
3720 pae.isHome = activity.isActivityTypeHome();
3721
3722 // Increment the sessionId if necessary
3723 if (newSessionId) {
3724 mViSessionId++;
3725 }
3726 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003727 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3728 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003729 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003730 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003731 } catch (RemoteException e) {
3732 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3733 return null;
3734 }
3735 return pae;
3736 }
3737 }
3738
3739 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3740 if (result != null) {
3741 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3742 }
3743 if (pae.hint != null) {
3744 pae.extras.putBoolean(pae.hint, true);
3745 }
3746 }
3747
3748 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3749 IAssistDataReceiver receiver;
3750 synchronized (mGlobalLock) {
3751 mPendingAssistExtras.remove(pae);
3752 receiver = pae.receiver;
3753 }
3754 if (receiver != null) {
3755 // Caller wants result sent back to them.
3756 Bundle sendBundle = new Bundle();
3757 // At least return the receiver extras
3758 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3759 try {
3760 pae.receiver.onHandleAssistData(sendBundle);
3761 } catch (RemoteException e) {
3762 }
3763 }
3764 }
3765
3766 public class PendingAssistExtras extends Binder implements Runnable {
3767 public final ActivityRecord activity;
3768 public boolean isHome;
3769 public final Bundle extras;
3770 public final Intent intent;
3771 public final String hint;
3772 public final IAssistDataReceiver receiver;
3773 public final int userHandle;
3774 public boolean haveResult = false;
3775 public Bundle result = null;
3776 public AssistStructure structure = null;
3777 public AssistContent content = null;
3778 public Bundle receiverExtras;
3779
3780 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3781 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3782 int _userHandle) {
3783 activity = _activity;
3784 extras = _extras;
3785 intent = _intent;
3786 hint = _hint;
3787 receiver = _receiver;
3788 receiverExtras = _receiverExtras;
3789 userHandle = _userHandle;
3790 }
3791
3792 @Override
3793 public void run() {
3794 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3795 synchronized (this) {
3796 haveResult = true;
3797 notifyAll();
3798 }
3799 pendingAssistExtrasTimedOut(this);
3800 }
3801 }
3802
3803 @Override
3804 public boolean isAssistDataAllowedOnCurrentActivity() {
3805 int userId;
3806 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003807 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003808 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3809 return false;
3810 }
3811
Wale Ogunwale21e06482019-11-18 05:14:15 -08003812 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003813 if (activity == null) {
3814 return false;
3815 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003816 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003817 }
3818 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3819 }
3820
3821 @Override
3822 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3823 long ident = Binder.clearCallingIdentity();
3824 try {
3825 synchronized (mGlobalLock) {
3826 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003827 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003828 if (top != caller) {
3829 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3830 + " is not current top " + top);
3831 return false;
3832 }
3833 if (!top.nowVisible) {
3834 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3835 + " is not visible");
3836 return false;
3837 }
3838 }
3839 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3840 token);
3841 } finally {
3842 Binder.restoreCallingIdentity(ident);
3843 }
3844 }
3845
3846 @Override
3847 public boolean isRootVoiceInteraction(IBinder token) {
3848 synchronized (mGlobalLock) {
3849 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3850 if (r == null) {
3851 return false;
3852 }
3853 return r.rootVoiceInteraction;
3854 }
3855 }
3856
Wale Ogunwalef6733932018-06-27 05:14:34 -07003857 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3858 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3859 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3860 if (activityToCallback == null) return;
3861 activityToCallback.setVoiceSessionLocked(voiceSession);
3862
3863 // Inform the activity
3864 try {
3865 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3866 voiceInteractor);
3867 long token = Binder.clearCallingIdentity();
3868 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003869 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003870 } finally {
3871 Binder.restoreCallingIdentity(token);
3872 }
3873 // TODO: VI Should we cache the activity so that it's easier to find later
3874 // rather than scan through all the stacks and activities?
3875 } catch (RemoteException re) {
3876 activityToCallback.clearVoiceSessionLocked();
3877 // TODO: VI Should this terminate the voice session?
3878 }
3879 }
3880
3881 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3882 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3883 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3884 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3885 boolean wasRunningVoice = mRunningVoice != null;
3886 mRunningVoice = session;
3887 if (!wasRunningVoice) {
3888 mVoiceWakeLock.acquire();
3889 updateSleepIfNeededLocked();
3890 }
3891 }
3892 }
3893
3894 void finishRunningVoiceLocked() {
3895 if (mRunningVoice != null) {
3896 mRunningVoice = null;
3897 mVoiceWakeLock.release();
3898 updateSleepIfNeededLocked();
3899 }
3900 }
3901
3902 @Override
3903 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3904 synchronized (mGlobalLock) {
3905 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3906 if (keepAwake) {
3907 mVoiceWakeLock.acquire();
3908 } else {
3909 mVoiceWakeLock.release();
3910 }
3911 }
3912 }
3913 }
3914
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003915 @Override
3916 public ComponentName getActivityClassForToken(IBinder token) {
3917 synchronized (mGlobalLock) {
3918 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3919 if (r == null) {
3920 return null;
3921 }
3922 return r.intent.getComponent();
3923 }
3924 }
3925
3926 @Override
3927 public String getPackageForToken(IBinder token) {
3928 synchronized (mGlobalLock) {
3929 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3930 if (r == null) {
3931 return null;
3932 }
3933 return r.packageName;
3934 }
3935 }
3936
3937 @Override
3938 public void showLockTaskEscapeMessage(IBinder token) {
3939 synchronized (mGlobalLock) {
3940 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3941 if (r == null) {
3942 return;
3943 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003944 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003945 }
3946 }
3947
3948 @Override
3949 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003950 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003951 final long token = Binder.clearCallingIdentity();
3952 try {
3953 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003954 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003955 }
3956 } finally {
3957 Binder.restoreCallingIdentity(token);
3958 }
3959 }
3960
3961 /**
3962 * Try to place task to provided position. The final position might be different depending on
3963 * current user and stacks state. The task will be moved to target stack if it's currently in
3964 * different stack.
3965 */
3966 @Override
3967 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003968 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003969 synchronized (mGlobalLock) {
3970 long ident = Binder.clearCallingIdentity();
3971 try {
3972 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3973 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003974 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003975 if (task == null) {
3976 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3977 + taskId);
3978 }
3979
Louis Chang149d5c82019-12-30 09:47:39 +08003980 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003981
3982 if (stack == null) {
3983 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3984 + stackId);
3985 }
3986 if (!stack.isActivityTypeStandardOrUndefined()) {
3987 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3988 + " the position of task " + taskId + " in/to non-standard stack");
3989 }
3990
3991 // TODO: Have the callers of this API call a separate reparent method if that is
3992 // what they intended to do vs. having this method also do reparenting.
3993 if (task.getStack() == stack) {
3994 // Change position in current stack.
3995 stack.positionChildAt(task, position);
3996 } else {
3997 // Reparent to new stack.
3998 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3999 !DEFER_RESUME, "positionTaskInStack");
4000 }
4001 } finally {
4002 Binder.restoreCallingIdentity(ident);
4003 }
4004 }
4005 }
4006
4007 @Override
4008 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
4009 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
4010 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09004011 + Arrays.toString(horizontalSizeConfiguration) + " "
4012 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004013 synchronized (mGlobalLock) {
4014 ActivityRecord record = ActivityRecord.isInStackLocked(token);
4015 if (record == null) {
4016 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
4017 + "found for: " + token);
4018 }
4019 record.setSizeConfigurations(horizontalSizeConfiguration,
4020 verticalSizeConfigurations, smallestSizeConfigurations);
4021 }
4022 }
4023
4024 /**
4025 * Dismisses split-screen multi-window mode.
4026 * @param toTop If true the current primary split-screen stack will be placed or left on top.
4027 */
4028 @Override
4029 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004030 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004031 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
4032 final long ident = Binder.clearCallingIdentity();
4033 try {
4034 synchronized (mGlobalLock) {
4035 final ActivityStack stack =
Louis Chang149d5c82019-12-30 09:47:39 +08004036 mRootWindowContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004037 if (stack == null) {
4038 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
4039 return;
4040 }
4041
4042 if (toTop) {
4043 // Caller wants the current split-screen primary stack to be the top stack after
4044 // it goes fullscreen, so move it to the front.
4045 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004046 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004047 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004048 // stack after it goes fullscreen, so we move the focus to the top-most
4049 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004050 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
4051 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
4052 if (otherStack != null) {
4053 otherStack.moveToFront("dismissSplitScreenMode_other");
4054 }
4055 }
4056
Evan Rosky10475742018-09-05 19:02:48 -07004057 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004058 }
4059 } finally {
4060 Binder.restoreCallingIdentity(ident);
4061 }
4062 }
4063
4064 /**
4065 * Dismisses Pip
4066 * @param animate True if the dismissal should be animated.
4067 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4068 * default animation duration should be used.
4069 */
4070 @Override
4071 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004072 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004073 final long ident = Binder.clearCallingIdentity();
4074 try {
4075 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004076 final ActivityStack stack =
Louis Chang149d5c82019-12-30 09:47:39 +08004077 mRootWindowContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004078 if (stack == null) {
4079 Slog.w(TAG, "dismissPip: pinned stack not found.");
4080 return;
4081 }
4082 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4083 throw new IllegalArgumentException("Stack: " + stack
4084 + " doesn't support animated resize.");
4085 }
Robert Carr8a2f9132019-11-11 15:03:15 -08004086 /**
4087 * TODO(b/146594635): Remove all PIP animation code from WM
4088 * once SysUI handles animation. Don't even try to animate TaskOrganized tasks.
4089 */
4090 if (animate && !stack.isControlledByTaskOrganizer()) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004091 stack.animateResizePinnedStack(null /* destBounds */,
4092 null /* sourceHintBounds */, animationDuration,
4093 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004094 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004095 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004096 }
4097 }
4098 } finally {
4099 Binder.restoreCallingIdentity(ident);
4100 }
4101 }
4102
4103 @Override
4104 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004105 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004106 synchronized (mGlobalLock) {
4107 mSuppressResizeConfigChanges = suppress;
4108 }
4109 }
4110
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004111 @Override
4112 // TODO: API should just be about changing windowing modes...
4113 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004114 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004115 "moveTasksToFullscreenStack()");
4116 synchronized (mGlobalLock) {
4117 final long origId = Binder.clearCallingIdentity();
4118 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004119 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004120 if (stack != null){
4121 if (!stack.isActivityTypeStandardOrUndefined()) {
4122 throw new IllegalArgumentException(
4123 "You can't move tasks from non-standard stacks.");
4124 }
4125 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4126 }
4127 } finally {
4128 Binder.restoreCallingIdentity(origId);
4129 }
4130 }
4131 }
4132
4133 /**
4134 * Moves the top activity in the input stackId to the pinned stack.
4135 *
4136 * @param stackId Id of stack to move the top activity to pinned stack.
4137 * @param bounds Bounds to use for pinned stack.
4138 *
4139 * @return True if the top activity of the input stack was successfully moved to the pinned
4140 * stack.
4141 */
4142 @Override
4143 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004144 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004145 "moveTopActivityToPinnedStack()");
4146 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004147 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004148 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4149 + "Device doesn't support picture-in-picture mode");
4150 }
4151
4152 long ident = Binder.clearCallingIdentity();
4153 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004154 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004155 } finally {
4156 Binder.restoreCallingIdentity(ident);
4157 }
4158 }
4159 }
4160
4161 @Override
4162 public boolean isInMultiWindowMode(IBinder token) {
4163 final long origId = Binder.clearCallingIdentity();
4164 try {
4165 synchronized (mGlobalLock) {
4166 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4167 if (r == null) {
4168 return false;
4169 }
4170 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4171 return r.inMultiWindowMode();
4172 }
4173 } finally {
4174 Binder.restoreCallingIdentity(origId);
4175 }
4176 }
4177
4178 @Override
4179 public boolean isInPictureInPictureMode(IBinder token) {
4180 final long origId = Binder.clearCallingIdentity();
4181 try {
4182 synchronized (mGlobalLock) {
4183 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4184 }
4185 } finally {
4186 Binder.restoreCallingIdentity(origId);
4187 }
4188 }
4189
4190 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004191 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4192 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004193 return false;
4194 }
4195
4196 // If we are animating to fullscreen then we have already dispatched the PIP mode
4197 // changed, so we should reflect that check here as well.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004198 final ActivityStack taskStack = r.getActivityStack();
Yunfan Chen279f5582018-12-12 15:24:50 -08004199 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004200 }
4201
4202 @Override
4203 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4204 final long origId = Binder.clearCallingIdentity();
4205 try {
4206 synchronized (mGlobalLock) {
4207 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4208 "enterPictureInPictureMode", token, params);
4209
4210 // If the activity is already in picture in picture mode, then just return early
4211 if (isInPictureInPictureMode(r)) {
4212 return true;
4213 }
4214
4215 // Activity supports picture-in-picture, now check that we can enter PiP at this
4216 // point, if it is
4217 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4218 false /* beforeStopping */)) {
4219 return false;
4220 }
4221
4222 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004223 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004224 if (r.getParent() == null) {
4225 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4226 return;
4227 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004228 // Only update the saved args from the args that are set
4229 r.pictureInPictureArgs.copyOnlySet(params);
4230 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4231 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4232 // Adjust the source bounds by the insets for the transition down
4233 final Rect sourceBounds = new Rect(
4234 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004235 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004236 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004237 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004238 stack.setPictureInPictureAspectRatio(aspectRatio);
4239 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004240 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4241 r.info.applicationInfo.uid, r.shortComponentName,
4242 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004243 logPictureInPictureArgs(params);
4244 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004245 };
4246
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004247 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004248 // If the keyguard is showing or occluded, then try and dismiss it before
4249 // entering picture-in-picture (this will prompt the user to authenticate if the
4250 // device is currently locked).
4251 dismissKeyguard(token, new KeyguardDismissCallback() {
4252 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004253 public void onDismissSucceeded() {
4254 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004255 }
4256 }, null /* message */);
4257 } else {
4258 // Enter picture in picture immediately otherwise
4259 enterPipRunnable.run();
4260 }
4261 return true;
4262 }
4263 } finally {
4264 Binder.restoreCallingIdentity(origId);
4265 }
4266 }
4267
4268 @Override
4269 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4270 final long origId = Binder.clearCallingIdentity();
4271 try {
4272 synchronized (mGlobalLock) {
4273 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4274 "setPictureInPictureParams", token, params);
4275
4276 // Only update the saved args from the args that are set
4277 r.pictureInPictureArgs.copyOnlySet(params);
4278 if (r.inPinnedWindowingMode()) {
4279 // If the activity is already in picture-in-picture, update the pinned stack now
4280 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4281 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004282 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004283 if (!stack.isAnimatingBoundsToFullscreen()) {
4284 stack.setPictureInPictureAspectRatio(
4285 r.pictureInPictureArgs.getAspectRatio());
4286 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4287 }
4288 }
4289 logPictureInPictureArgs(params);
4290 }
4291 } finally {
4292 Binder.restoreCallingIdentity(origId);
4293 }
4294 }
4295
4296 @Override
4297 public int getMaxNumPictureInPictureActions(IBinder token) {
4298 // Currently, this is a static constant, but later, we may change this to be dependent on
4299 // the context of the activity
4300 return 3;
4301 }
4302
4303 private void logPictureInPictureArgs(PictureInPictureParams params) {
4304 if (params.hasSetActions()) {
4305 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4306 params.getActions().size());
4307 }
4308 if (params.hasSetAspectRatio()) {
4309 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4310 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4311 MetricsLogger.action(lm);
4312 }
4313 }
4314
4315 /**
4316 * Checks the state of the system and the activity associated with the given {@param token} to
4317 * verify that picture-in-picture is supported for that activity.
4318 *
4319 * @return the activity record for the given {@param token} if all the checks pass.
4320 */
4321 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4322 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004323 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004324 throw new IllegalStateException(caller
4325 + ": Device doesn't support picture-in-picture mode.");
4326 }
4327
4328 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4329 if (r == null) {
4330 throw new IllegalStateException(caller
4331 + ": Can't find activity for token=" + token);
4332 }
4333
4334 if (!r.supportsPictureInPicture()) {
4335 throw new IllegalStateException(caller
4336 + ": Current activity does not support picture-in-picture.");
4337 }
4338
4339 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004340 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale0b3d2922019-12-30 08:55:07 -08004341 r.getDisplayId(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004342 final float minAspectRatio = mContext.getResources().getFloat(
4343 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4344 final float maxAspectRatio = mContext.getResources().getFloat(
4345 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4346 throw new IllegalArgumentException(String.format(caller
4347 + ": Aspect ratio is too extreme (must be between %f and %f).",
4348 minAspectRatio, maxAspectRatio));
4349 }
4350
4351 // Truncate the number of actions if necessary
4352 params.truncateActions(getMaxNumPictureInPictureActions(token));
4353
4354 return r;
4355 }
4356
4357 @Override
4358 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004359 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004360 synchronized (mGlobalLock) {
4361 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4362 if (r == null) {
4363 throw new IllegalArgumentException("Activity does not exist; token="
4364 + activityToken);
4365 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004366 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367 }
4368 }
4369
4370 @Override
4371 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4372 Rect tempDockedTaskInsetBounds,
4373 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004374 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004375 long ident = Binder.clearCallingIdentity();
4376 try {
4377 synchronized (mGlobalLock) {
4378 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4379 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4380 PRESERVE_WINDOWS);
4381 }
4382 } finally {
4383 Binder.restoreCallingIdentity(ident);
4384 }
4385 }
4386
4387 @Override
4388 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004389 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004390 final long ident = Binder.clearCallingIdentity();
4391 try {
4392 synchronized (mGlobalLock) {
4393 mStackSupervisor.setSplitScreenResizing(resizing);
4394 }
4395 } finally {
4396 Binder.restoreCallingIdentity(ident);
4397 }
4398 }
4399
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004400 /**
4401 * Check that we have the features required for VR-related API calls, and throw an exception if
4402 * not.
4403 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004404 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004405 if (!mContext.getPackageManager().hasSystemFeature(
4406 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4407 throw new UnsupportedOperationException("VR mode not supported on this device!");
4408 }
4409 }
4410
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004411 @Override
4412 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004413 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004414
4415 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4416
4417 ActivityRecord r;
4418 synchronized (mGlobalLock) {
4419 r = ActivityRecord.isInStackLocked(token);
4420 }
4421
4422 if (r == null) {
4423 throw new IllegalArgumentException();
4424 }
4425
4426 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004427 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004428 VrManagerInternal.NO_ERROR) {
4429 return err;
4430 }
4431
4432 // Clear the binder calling uid since this path may call moveToTask().
4433 final long callingId = Binder.clearCallingIdentity();
4434 try {
4435 synchronized (mGlobalLock) {
4436 r.requestedVrComponent = (enabled) ? packageName : null;
4437
4438 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004439 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004440 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004441 }
4442 return 0;
4443 }
4444 } finally {
4445 Binder.restoreCallingIdentity(callingId);
4446 }
4447 }
4448
4449 @Override
4450 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4451 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4452 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004453 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4455 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4456 }
Louis Changcdec0802019-11-11 11:45:07 +08004457 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004458 || activity.voiceSession != null) {
4459 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4460 return;
4461 }
4462 if (activity.pendingVoiceInteractionStart) {
4463 Slog.w(TAG, "Pending start of voice interaction already.");
4464 return;
4465 }
4466 activity.pendingVoiceInteractionStart = true;
4467 }
4468 LocalServices.getService(VoiceInteractionManagerInternal.class)
4469 .startLocalVoiceInteraction(callingActivity, options);
4470 }
4471
4472 @Override
4473 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4474 LocalServices.getService(VoiceInteractionManagerInternal.class)
4475 .stopLocalVoiceInteraction(callingActivity);
4476 }
4477
4478 @Override
4479 public boolean supportsLocalVoiceInteraction() {
4480 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4481 .supportsLocalVoiceInteraction();
4482 }
4483
4484 /** Notifies all listeners when the pinned stack animation starts. */
4485 @Override
4486 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004487 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004488 }
4489
4490 /** Notifies all listeners when the pinned stack animation ends. */
4491 @Override
4492 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004493 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004494 }
4495
4496 @Override
4497 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004498 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004499 final long ident = Binder.clearCallingIdentity();
4500 try {
4501 synchronized (mGlobalLock) {
4502 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4503 }
4504 } finally {
4505 Binder.restoreCallingIdentity(ident);
4506 }
4507 }
4508
4509 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004510 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004511 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004512
4513 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004514 if (mWindowManager == null) {
4515 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4516 return false;
4517 }
4518
4519 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004520 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004521 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004522 }
4523
Riddle Hsua0022cd2019-09-09 21:12:41 +08004524 mH.sendMessage(PooledLambda.obtainMessage(
4525 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4526 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004527
4528 final long origId = Binder.clearCallingIdentity();
4529 try {
4530 if (values != null) {
4531 Settings.System.clearConfiguration(values);
4532 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004533 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004534 UserHandle.USER_NULL, false /* deferResume */,
4535 mTmpUpdateConfigurationResult);
4536 return mTmpUpdateConfigurationResult.changes != 0;
4537 } finally {
4538 Binder.restoreCallingIdentity(origId);
4539 }
4540 }
4541 }
4542
4543 @Override
4544 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4545 CharSequence message) {
4546 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004547 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004548 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4549 }
4550 final long callingId = Binder.clearCallingIdentity();
4551 try {
4552 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004553 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004554 }
4555 } finally {
4556 Binder.restoreCallingIdentity(callingId);
4557 }
4558 }
4559
4560 @Override
4561 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004562 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004563 "cancelTaskWindowTransition()");
4564 final long ident = Binder.clearCallingIdentity();
4565 try {
4566 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004567 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004568 MATCH_TASK_IN_STACKS_ONLY);
4569 if (task == null) {
4570 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4571 return;
4572 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004573 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004574 }
4575 } finally {
4576 Binder.restoreCallingIdentity(ident);
4577 }
4578 }
4579
4580 @Override
4581 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004582 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004583 final long ident = Binder.clearCallingIdentity();
4584 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004585 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004586 } finally {
4587 Binder.restoreCallingIdentity(ident);
4588 }
4589 }
4590
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004591 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4592 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004593 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004594 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004595 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004596 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4597 if (task == null) {
4598 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4599 return null;
4600 }
4601 }
4602 // Don't call this while holding the lock as this operation might hit the disk.
4603 return task.getSnapshot(reducedResolution, restoreFromDisk);
4604 }
4605
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004606 @Override
4607 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4608 synchronized (mGlobalLock) {
4609 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4610 if (r == null) {
4611 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4612 + token);
4613 return;
4614 }
4615 final long origId = Binder.clearCallingIdentity();
4616 try {
4617 r.setDisablePreviewScreenshots(disable);
4618 } finally {
4619 Binder.restoreCallingIdentity(origId);
4620 }
4621 }
4622 }
4623
Riddle Hsu440f88b2019-11-06 22:17:35 +08004624 @Override
4625 public void invalidateHomeTaskSnapshot(IBinder token) {
4626 synchronized (mGlobalLock) {
4627 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4628 if (r == null || !r.isActivityTypeHome()) {
4629 return;
4630 }
4631 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4632 }
4633 }
4634
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004635 /** Return the user id of the last resumed activity. */
4636 @Override
4637 public @UserIdInt
4638 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004639 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004640 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4641 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004642 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004643 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004644 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004645 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004646 }
4647 }
4648
4649 @Override
4650 public void updateLockTaskFeatures(int userId, int flags) {
4651 final int callingUid = Binder.getCallingUid();
4652 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004653 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004654 "updateLockTaskFeatures()");
4655 }
4656 synchronized (mGlobalLock) {
4657 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4658 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004659 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004660 }
4661 }
4662
4663 @Override
4664 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4665 synchronized (mGlobalLock) {
4666 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4667 if (r == null) {
4668 return;
4669 }
4670 final long origId = Binder.clearCallingIdentity();
4671 try {
4672 r.setShowWhenLocked(showWhenLocked);
4673 } finally {
4674 Binder.restoreCallingIdentity(origId);
4675 }
4676 }
4677 }
4678
4679 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004680 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4681 synchronized (mGlobalLock) {
4682 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4683 if (r == null) {
4684 return;
4685 }
4686 final long origId = Binder.clearCallingIdentity();
4687 try {
4688 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4689 } finally {
4690 Binder.restoreCallingIdentity(origId);
4691 }
4692 }
4693 }
4694
4695 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004696 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4697 synchronized (mGlobalLock) {
4698 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4699 if (r == null) {
4700 return;
4701 }
4702 final long origId = Binder.clearCallingIdentity();
4703 try {
4704 r.setTurnScreenOn(turnScreenOn);
4705 } finally {
4706 Binder.restoreCallingIdentity(origId);
4707 }
4708 }
4709 }
4710
4711 @Override
4712 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004713 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004714 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004715 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004716 synchronized (mGlobalLock) {
4717 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4718 if (r == null) {
4719 return;
4720 }
4721 final long origId = Binder.clearCallingIdentity();
4722 try {
4723 r.registerRemoteAnimations(definition);
4724 } finally {
4725 Binder.restoreCallingIdentity(origId);
4726 }
4727 }
4728 }
4729
4730 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004731 public void unregisterRemoteAnimations(IBinder token) {
4732 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4733 "unregisterRemoteAnimations");
4734 synchronized (mGlobalLock) {
4735 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4736 if (r == null) {
4737 return;
4738 }
4739 final long origId = Binder.clearCallingIdentity();
4740 try {
4741 r.unregisterRemoteAnimations();
4742 } finally {
4743 Binder.restoreCallingIdentity(origId);
4744 }
4745 }
4746 }
4747
4748 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004749 public void registerRemoteAnimationForNextActivityStart(String packageName,
4750 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004751 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004752 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004753 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004754 synchronized (mGlobalLock) {
4755 final long origId = Binder.clearCallingIdentity();
4756 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004757 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004758 packageName, adapter);
4759 } finally {
4760 Binder.restoreCallingIdentity(origId);
4761 }
4762 }
4763 }
4764
Evan Rosky966759f2019-01-15 10:33:58 -08004765 @Override
4766 public void registerRemoteAnimationsForDisplay(int displayId,
4767 RemoteAnimationDefinition definition) {
4768 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4769 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004770 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004771 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004772 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004773 if (display == null) {
4774 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4775 return;
4776 }
4777 final long origId = Binder.clearCallingIdentity();
4778 try {
4779 display.mDisplayContent.registerRemoteAnimations(definition);
4780 } finally {
4781 Binder.restoreCallingIdentity(origId);
4782 }
4783 }
4784 }
4785
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004786 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4787 @Override
4788 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4789 synchronized (mGlobalLock) {
4790 final long origId = Binder.clearCallingIdentity();
4791 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004792 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004793 } finally {
4794 Binder.restoreCallingIdentity(origId);
4795 }
4796 }
4797 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004798
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004799 @Override
4800 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004801 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004802 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004803 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004804 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004805 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004806 }
4807 }
4808
4809 @Override
4810 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004811 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004812 != PERMISSION_GRANTED) {
4813 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4814 + Binder.getCallingPid()
4815 + ", uid=" + Binder.getCallingUid()
4816 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4817 Slog.w(TAG, msg);
4818 throw new SecurityException(msg);
4819 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004820 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004821 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004822 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004823 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004824 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004825 }
4826 }
4827
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004828 @Override
4829 public void stopAppSwitches() {
4830 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4831 synchronized (mGlobalLock) {
4832 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004833 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004834 mDidAppSwitch = false;
4835 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4836 }
4837 }
4838
4839 @Override
4840 public void resumeAppSwitches() {
4841 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4842 synchronized (mGlobalLock) {
4843 // Note that we don't execute any pending app switches... we will
4844 // let those wait until either the timeout, or the next start
4845 // activity request.
4846 mAppSwitchesAllowedTime = 0;
4847 }
4848 }
4849
Ricky Wai906af482019-06-03 17:25:28 +01004850 long getLastStopAppSwitchesTime() {
4851 return mLastStopAppSwitchesTime;
4852 }
4853
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004854 void onStartActivitySetDidAppSwitch() {
4855 if (mDidAppSwitch) {
4856 // This is the second allowed switch since we stopped switches, so now just generally
4857 // allow switches. Use case:
4858 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4859 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4860 // anyone to switch again).
4861 mAppSwitchesAllowedTime = 0;
4862 } else {
4863 mDidAppSwitch = true;
4864 }
4865 }
4866
4867 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004868 boolean shouldDisableNonVrUiLocked() {
4869 return mVrController.shouldDisableNonVrUiLocked();
4870 }
4871
Wale Ogunwale53783742018-09-16 10:21:51 -07004872 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004873 // 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 +00004874 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004875 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004876 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4877 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004878 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004879 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004880 }
4881 mH.post(() -> {
4882 if (!mVrController.onVrModeChanged(r)) {
4883 return;
4884 }
4885 synchronized (mGlobalLock) {
4886 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4887 mWindowManager.disableNonVrUi(disableNonVrUi);
4888 if (disableNonVrUi) {
4889 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4890 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004891 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004892 }
4893 }
4894 });
4895 }
4896
Wale Ogunwale53783742018-09-16 10:21:51 -07004897 @Override
4898 public int getPackageScreenCompatMode(String packageName) {
4899 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4900 synchronized (mGlobalLock) {
4901 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4902 }
4903 }
4904
4905 @Override
4906 public void setPackageScreenCompatMode(String packageName, int mode) {
4907 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4908 "setPackageScreenCompatMode");
4909 synchronized (mGlobalLock) {
4910 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4911 }
4912 }
4913
4914 @Override
4915 public boolean getPackageAskScreenCompat(String packageName) {
4916 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4917 synchronized (mGlobalLock) {
4918 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4919 }
4920 }
4921
4922 @Override
4923 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4924 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4925 "setPackageAskScreenCompat");
4926 synchronized (mGlobalLock) {
4927 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4928 }
4929 }
4930
Wale Ogunwale64258362018-10-16 15:13:37 -07004931 public static String relaunchReasonToString(int relaunchReason) {
4932 switch (relaunchReason) {
4933 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4934 return "window_resize";
4935 case RELAUNCH_REASON_FREE_RESIZE:
4936 return "free_resize";
4937 default:
4938 return null;
4939 }
4940 }
4941
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004942 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004943 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004944 }
4945
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004946 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004947 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004948 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4949 }
4950
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004951 boolean isKeyguardLocked() {
4952 return mKeyguardController.isKeyguardLocked();
4953 }
4954
Garfield Tan01548632018-11-27 10:15:48 -08004955 /**
4956 * Clears launch params for the given package.
4957 * @param packageNames the names of the packages of which the launch params are to be cleared
4958 */
4959 @Override
4960 public void clearLaunchParamsForPackages(List<String> packageNames) {
4961 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4962 "clearLaunchParamsForPackages");
4963 synchronized (mGlobalLock) {
4964 for (int i = 0; i < packageNames.size(); ++i) {
4965 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4966 }
4967 }
4968 }
4969
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004970 /**
4971 * Makes the display with the given id a single task instance display. I.e the display can only
4972 * contain one task.
4973 */
4974 @Override
4975 public void setDisplayToSingleTaskInstance(int displayId) {
4976 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4977 "setDisplayToSingleTaskInstance");
4978 final long origId = Binder.clearCallingIdentity();
4979 try {
Louis Chang677921f2019-12-06 16:44:24 +08004980 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004981 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004982 if (display != null) {
4983 display.setDisplayToSingleTaskInstance();
4984 }
4985 } finally {
4986 Binder.restoreCallingIdentity(origId);
4987 }
4988 }
4989
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004990 /**
4991 * Requests that an activity should enter picture-in-picture mode if possible.
4992 */
4993 @Override
4994 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4995 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4996 "requestPictureInPictureMode");
4997 final long origId = Binder.clearCallingIdentity();
4998 try {
4999 synchronized (mGlobalLock) {
5000 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
5001 if (activity == null) {
5002 return;
5003 }
5004
5005 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
5006 "requestPictureInPictureMode", /* beforeStopping */ false);
5007 if (!canEnterPictureInPicture) {
5008 throw new IllegalStateException(
5009 "Requested PIP on an activity that doesn't support it");
5010 }
5011
5012 try {
5013 final ClientTransaction transaction = ClientTransaction.obtain(
5014 activity.app.getThread(),
5015 activity.token);
5016 transaction.addCallback(EnterPipRequestedItem.obtain());
5017 getLifecycleManager().scheduleTransaction(transaction);
5018 } catch (Exception e) {
5019 Slog.w(TAG, "Failed to send enter pip requested item: "
5020 + activity.intent.getComponent(), e);
5021 }
5022 }
5023 } finally {
5024 Binder.restoreCallingIdentity(origId);
5025 }
5026 }
5027
Wale Ogunwale31913b52018-10-13 08:29:31 -07005028 void dumpLastANRLocked(PrintWriter pw) {
5029 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
5030 if (mLastANRState == null) {
5031 pw.println(" <no ANR has occurred since boot>");
5032 } else {
5033 pw.println(mLastANRState);
5034 }
5035 }
5036
5037 void dumpLastANRTracesLocked(PrintWriter pw) {
5038 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
5039
5040 final File[] files = new File(ANR_TRACE_DIR).listFiles();
5041 if (ArrayUtils.isEmpty(files)) {
5042 pw.println(" <no ANR has occurred since boot>");
5043 return;
5044 }
5045 // Find the latest file.
5046 File latest = null;
5047 for (File f : files) {
5048 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
5049 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005050 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005051 }
5052 pw.print("File: ");
5053 pw.print(latest.getName());
5054 pw.println();
5055 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
5056 String line;
5057 while ((line = in.readLine()) != null) {
5058 pw.println(line);
5059 }
5060 } catch (IOException e) {
5061 pw.print("Unable to read: ");
5062 pw.print(e);
5063 pw.println();
5064 }
5065 }
5066
5067 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5068 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
5069 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
5070 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
5071 }
5072
5073 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5074 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5075 pw.println(header);
5076
Louis Chang149d5c82019-12-30 09:47:39 +08005077 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005078 dumpPackage);
5079 boolean needSep = printedAnything;
5080
5081 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08005082 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005083 " ResumedActivity: ");
5084 if (printed) {
5085 printedAnything = true;
5086 needSep = false;
5087 }
5088
5089 if (dumpPackage == null) {
5090 if (needSep) {
5091 pw.println();
5092 }
5093 printedAnything = true;
5094 mStackSupervisor.dump(pw, " ");
5095 }
5096
5097 if (!printedAnything) {
5098 pw.println(" (nothing)");
5099 }
5100 }
5101
5102 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005103 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005104 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005105 pw.println(" ");
5106 }
5107
5108 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5109 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5110 getActivityStartController().dump(pw, "", dumpPackage);
5111 }
5112
5113 /**
5114 * There are three things that cmd can be:
5115 * - a flattened component name that matches an existing activity
5116 * - the cmd arg isn't the flattened component name of an existing activity:
5117 * dump all activity whose component contains the cmd as a substring
5118 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005119 * <p>
5120 * The caller should not hold lock when calling this method because it will wait for the
5121 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005122 *
5123 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5124 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5125 */
5126 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5127 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5128 ArrayList<ActivityRecord> activities;
5129
5130 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005131 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005132 dumpFocusedStackOnly);
5133 }
5134
5135 if (activities.size() <= 0) {
5136 return false;
5137 }
5138
5139 String[] newArgs = new String[args.length - opti];
5140 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5141
Louis Changcdec0802019-11-11 11:45:07 +08005142 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005143 boolean needSep = false;
5144 for (int i = activities.size() - 1; i >= 0; i--) {
5145 ActivityRecord r = activities.get(i);
5146 if (needSep) {
5147 pw.println();
5148 }
5149 needSep = true;
5150 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005151 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005152 if (lastTask != task) {
5153 lastTask = task;
5154 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005155 pw.print(" id="); pw.print(lastTask.mTaskId);
5156 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005157 if (dumpAll) {
5158 lastTask.dump(pw, " ");
5159 }
5160 }
5161 }
5162 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5163 }
5164 return true;
5165 }
5166
5167 /**
5168 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5169 * there is a thread associated with the activity.
5170 */
5171 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5172 final ActivityRecord r, String[] args, boolean dumpAll) {
5173 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005174 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005175 synchronized (mGlobalLock) {
5176 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5177 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5178 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005179 if (r.hasProcess()) {
5180 pw.println(r.app.getPid());
5181 appThread = r.app.getThread();
5182 } else {
5183 pw.println("(not running)");
5184 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005185 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005186 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005187 }
5188 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005189 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005190 // flush anything that is already in the PrintWriter since the thread is going
5191 // to write to the file descriptor directly
5192 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005193 try (TransferPipe tp = new TransferPipe()) {
5194 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5195 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005196 } catch (IOException e) {
5197 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5198 } catch (RemoteException e) {
5199 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5200 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005201 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005202 }
5203
sanryhuang498e77e2018-12-06 14:57:01 +08005204 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5205 boolean testPssMode) {
5206 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5207 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5208 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005209 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005210 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5211 st.toString());
5212 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005213 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5214 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5215 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005216 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5217 testPssMode);
5218 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005219 }
5220
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005221 int getCurrentUserId() {
5222 return mAmInternal.getCurrentUserId();
5223 }
5224
5225 private void enforceNotIsolatedCaller(String caller) {
5226 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5227 throw new SecurityException("Isolated process not allowed to call " + caller);
5228 }
5229 }
5230
Wale Ogunwalef6733932018-06-27 05:14:34 -07005231 public Configuration getConfiguration() {
5232 Configuration ci;
5233 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005234 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005235 ci.userSetLocale = false;
5236 }
5237 return ci;
5238 }
5239
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005240 /**
5241 * Current global configuration information. Contains general settings for the entire system,
5242 * also corresponds to the merged configuration of the default display.
5243 */
5244 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005245 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005246 // while initializing process record for system, see {@link
5247 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005248 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005249 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005250 }
5251
5252 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5253 boolean initLocale) {
5254 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5255 }
5256
5257 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5258 boolean initLocale, boolean deferResume) {
5259 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5260 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5261 UserHandle.USER_NULL, deferResume);
5262 }
5263
Wale Ogunwale59507092018-10-29 09:00:30 -07005264 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005265 final long origId = Binder.clearCallingIdentity();
5266 try {
5267 synchronized (mGlobalLock) {
5268 updateConfigurationLocked(values, null, false, true, userId,
5269 false /* deferResume */);
5270 }
5271 } finally {
5272 Binder.restoreCallingIdentity(origId);
5273 }
5274 }
5275
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005276 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5277 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5278 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5279 deferResume, null /* result */);
5280 }
5281
5282 /**
5283 * Do either or both things: (1) change the current configuration, and (2)
5284 * make sure the given activity is running with the (now) current
5285 * configuration. Returns true if the activity has been left running, or
5286 * false if <var>starting</var> is being destroyed to match the new
5287 * configuration.
5288 *
5289 * @param userId is only used when persistent parameter is set to true to persist configuration
5290 * for that particular user
5291 */
5292 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5293 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5294 ActivityTaskManagerService.UpdateConfigurationResult result) {
5295 int changes = 0;
5296 boolean kept = true;
5297
Riddle Hsua0022cd2019-09-09 21:12:41 +08005298 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005299 try {
5300 if (values != null) {
5301 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5302 deferResume);
5303 }
5304
5305 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5306 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005307 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005308 }
5309
5310 if (result != null) {
5311 result.changes = changes;
5312 result.activityRelaunched = !kept;
5313 }
5314 return kept;
5315 }
5316
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005317 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005318 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005319 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005320
Louis Chang677921f2019-12-06 16:44:24 +08005321 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005322 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005323
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005324 mTempConfig.setTo(getGlobalConfiguration());
5325 final int changes = mTempConfig.updateFrom(values);
5326 if (changes == 0) {
5327 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5328 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5329 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5330 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005331 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005332 return 0;
5333 }
5334
5335 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5336 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005337 writeConfigurationChanged(changes);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005338 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5339 values.colorMode,
5340 values.densityDpi,
5341 values.fontScale,
5342 values.hardKeyboardHidden,
5343 values.keyboard,
5344 values.keyboardHidden,
5345 values.mcc,
5346 values.mnc,
5347 values.navigation,
5348 values.navigationHidden,
5349 values.orientation,
5350 values.screenHeightDp,
5351 values.screenLayout,
5352 values.screenWidthDp,
5353 values.smallestScreenWidthDp,
5354 values.touchscreen,
5355 values.uiMode);
5356
5357
5358 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5359 final LocaleList locales = values.getLocales();
5360 int bestLocaleIndex = 0;
5361 if (locales.size() > 1) {
5362 if (mSupportedSystemLocales == null) {
5363 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5364 }
5365 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5366 }
5367 SystemProperties.set("persist.sys.locale",
5368 locales.get(bestLocaleIndex).toLanguageTag());
5369 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005370
5371 final Message m = PooledLambda.obtainMessage(
5372 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5373 locales.get(bestLocaleIndex));
5374 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005375 }
5376
Yunfan Chen75157d72018-07-27 14:47:21 +09005377 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005378
5379 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005380 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005381
5382 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5383 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005384 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005385
5386 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005387 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005388
5389 AttributeCache ac = AttributeCache.instance();
5390 if (ac != null) {
5391 ac.updateConfiguration(mTempConfig);
5392 }
5393
5394 // Make sure all resources in our process are updated right now, so that anyone who is going
5395 // to retrieve resource values after we return will be sure to get the new ones. This is
5396 // especially important during boot, where the first config change needs to guarantee all
5397 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005398 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005399
5400 // We need another copy of global config because we're scheduling some calls instead of
5401 // running them in place. We need to be sure that object we send will be handled unchanged.
5402 final Configuration configCopy = new Configuration(mTempConfig);
5403 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005404 final Message msg = PooledLambda.obtainMessage(
5405 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5406 this, userId, configCopy);
5407 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005408 }
5409
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005410 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5411 for (int i = pidMap.size() - 1; i >= 0; i--) {
5412 final int pid = pidMap.keyAt(i);
5413 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005414 if (DEBUG_CONFIGURATION) {
5415 Slog.v(TAG_CONFIGURATION, "Update process config of "
5416 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005417 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005418 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005419 }
5420
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005421 final Message msg = PooledLambda.obtainMessage(
5422 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5423 mAmInternal, changes, initLocale);
5424 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005425
5426 // Override configuration of the default display duplicates global config, so we need to
5427 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005428 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005429 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005430
5431 return changes;
5432 }
5433
Riddle Hsua0022cd2019-09-09 21:12:41 +08005434 /** @see WindowSurfacePlacer#deferLayout */
5435 void deferWindowLayout() {
5436 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5437 // Reset the reasons at the first entrance because we only care about the changes in the
5438 // deferred scope.
5439 mLayoutReasons = 0;
5440 }
5441
5442 mWindowManager.mWindowPlacerLocked.deferLayout();
5443 }
5444
5445 /** @see WindowSurfacePlacer#continueLayout */
5446 void continueWindowLayout() {
5447 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5448 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5449 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5450 }
5451 }
5452
5453 /**
5454 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5455 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5456 * defer count is gone.
5457 */
5458 void addWindowLayoutReasons(@LayoutReason int reasons) {
5459 mLayoutReasons |= reasons;
5460 }
5461
Wale Ogunwalef6733932018-06-27 05:14:34 -07005462 private void updateEventDispatchingLocked(boolean booted) {
5463 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5464 }
5465
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005466 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5467 final ContentResolver resolver = mContext.getContentResolver();
5468 Settings.System.putConfigurationForUser(resolver, config, userId);
5469 }
5470
5471 private void sendLocaleToMountDaemonMsg(Locale l) {
5472 try {
5473 IBinder service = ServiceManager.getService("mount");
5474 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5475 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5476 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5477 } catch (RemoteException e) {
5478 Log.e(TAG, "Error storing locale for decryption UI", e);
5479 }
5480 }
5481
Alison Cichowlas3e340502018-08-07 17:15:01 -04005482 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5483 mStartActivitySources.remove(permissionToken);
5484 mExpiredStartAsCallerTokens.add(permissionToken);
5485 }
5486
5487 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5488 mExpiredStartAsCallerTokens.remove(permissionToken);
5489 }
5490
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005491 boolean isActivityStartsLoggingEnabled() {
5492 return mAmInternal.isActivityStartsLoggingEnabled();
5493 }
5494
Michal Karpinski8596ded2018-11-14 14:43:48 +00005495 boolean isBackgroundActivityStartsEnabled() {
5496 return mAmInternal.isBackgroundActivityStartsEnabled();
5497 }
5498
Wale Ogunwalef6733932018-06-27 05:14:34 -07005499 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005500 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005501 mWindowManager.enableScreenAfterBoot();
5502
5503 synchronized (mGlobalLock) {
5504 updateEventDispatchingLocked(booted);
5505 }
5506 }
5507
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005508 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5509 if (r == null || !r.hasProcess()) {
5510 return KEY_DISPATCHING_TIMEOUT_MS;
5511 }
5512 return getInputDispatchingTimeoutLocked(r.app);
5513 }
5514
5515 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005516 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005517 }
5518
Wale Ogunwalef6733932018-06-27 05:14:34 -07005519 /**
5520 * Decide based on the configuration whether we should show the ANR,
5521 * crash, etc dialogs. The idea is that if there is no affordance to
5522 * press the on-screen buttons, or the user experience would be more
5523 * greatly impacted than the crash itself, we shouldn't show the dialog.
5524 *
5525 * A thought: SystemUI might also want to get told about this, the Power
5526 * dialog / global actions also might want different behaviors.
5527 */
5528 private void updateShouldShowDialogsLocked(Configuration config) {
5529 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5530 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5531 && config.navigation == Configuration.NAVIGATION_NONAV);
5532 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5533 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5534 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5535 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5536 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5537 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5538 HIDE_ERROR_DIALOGS, 0) != 0;
5539 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5540 }
5541
5542 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5543 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5544 FONT_SCALE, 1.0f, userId);
5545
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005546 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005547 if (getGlobalConfiguration().fontScale == scaleFactor) {
5548 return;
5549 }
5550
5551 final Configuration configuration
5552 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5553 configuration.fontScale = scaleFactor;
5554 updatePersistentConfiguration(configuration, userId);
5555 }
5556 }
5557
5558 // Actually is sleeping or shutting down or whatever else in the future
5559 // is an inactive state.
5560 boolean isSleepingOrShuttingDownLocked() {
5561 return isSleepingLocked() || mShuttingDown;
5562 }
5563
5564 boolean isSleepingLocked() {
5565 return mSleeping;
5566 }
5567
Riddle Hsu16567132018-08-16 21:37:47 +08005568 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005569 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005570 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005571 if (task.isActivityTypeStandard()) {
5572 if (mCurAppTimeTracker != r.appTimeTracker) {
5573 // We are switching app tracking. Complete the current one.
5574 if (mCurAppTimeTracker != null) {
5575 mCurAppTimeTracker.stop();
5576 mH.obtainMessage(
5577 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005578 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005579 mCurAppTimeTracker = null;
5580 }
5581 if (r.appTimeTracker != null) {
5582 mCurAppTimeTracker = r.appTimeTracker;
5583 startTimeTrackingFocusedActivityLocked();
5584 }
5585 } else {
5586 startTimeTrackingFocusedActivityLocked();
5587 }
5588 } else {
5589 r.appTimeTracker = null;
5590 }
5591 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5592 // TODO: Probably not, because we don't want to resume voice on switching
5593 // back to this activity
5594 if (task.voiceInteractor != null) {
5595 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5596 } else {
5597 finishRunningVoiceLocked();
5598
5599 if (mLastResumedActivity != null) {
5600 final IVoiceInteractionSession session;
5601
Louis Changcdec0802019-11-11 11:45:07 +08005602 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005603 if (lastResumedActivityTask != null
5604 && lastResumedActivityTask.voiceSession != null) {
5605 session = lastResumedActivityTask.voiceSession;
5606 } else {
5607 session = mLastResumedActivity.voiceSession;
5608 }
5609
5610 if (session != null) {
5611 // We had been in a voice interaction session, but now focused has
5612 // move to something different. Just finish the session, we can't
5613 // return to it and retain the proper state and synchronization with
5614 // the voice interaction service.
5615 finishVoiceTask(session);
5616 }
5617 }
5618 }
5619
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005620 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5621 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005622 }
5623 updateResumedAppTrace(r);
5624 mLastResumedActivity = r;
5625
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005626 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005627
5628 applyUpdateLockStateLocked(r);
5629 applyUpdateVrModeLocked(r);
5630
Jeff Changd136e772019-11-05 20:33:52 +08005631 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005632 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005633 r == null ? "NULL" : r.shortComponentName,
5634 reason);
5635 }
5636
5637 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5638 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005639 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005640 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005641 updateSleepIfNeededLocked();
5642 return token;
5643 }
5644 }
5645
5646 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005647 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005648 final boolean wasSleeping = mSleeping;
5649 boolean updateOomAdj = false;
5650
5651 if (!shouldSleep) {
5652 // If wasSleeping is true, we need to wake up activity manager state from when
5653 // we started sleeping. In either case, we need to apply the sleep tokens, which
5654 // will wake up stacks or put them to sleep as appropriate.
5655 if (wasSleeping) {
5656 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005657 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5658 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005659 startTimeTrackingFocusedActivityLocked();
5660 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005661 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005662 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5663 }
Louis Chang149d5c82019-12-30 09:47:39 +08005664 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005665 if (wasSleeping) {
5666 updateOomAdj = true;
5667 }
5668 } else if (!mSleeping && shouldSleep) {
5669 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005670 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5671 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005672 if (mCurAppTimeTracker != null) {
5673 mCurAppTimeTracker.stop();
5674 }
5675 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005676 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005677 mStackSupervisor.goingToSleepLocked();
5678 updateResumedAppTrace(null /* resumed */);
5679 updateOomAdj = true;
5680 }
5681 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005682 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005683 }
5684 }
5685
5686 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005687 mH.removeCallbacks(mUpdateOomAdjRunnable);
5688 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005689 }
5690
Wale Ogunwale53783742018-09-16 10:21:51 -07005691 void updateCpuStats() {
5692 mH.post(mAmInternal::updateCpuStats);
5693 }
5694
Hui Yu03d12402018-12-06 18:00:37 -08005695 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5696 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005697 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5698 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005699 mH.sendMessage(m);
5700 }
5701
Hui Yu03d12402018-12-06 18:00:37 -08005702 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005703 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005704 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005705 if (task != null) {
5706 final ActivityRecord rootActivity = task.getRootActivity();
5707 if (rootActivity != null) {
5708 taskRoot = rootActivity.mActivityComponent;
5709 }
5710 }
5711
Hui Yu03d12402018-12-06 18:00:37 -08005712 final Message m = PooledLambda.obtainMessage(
5713 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005714 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005715 mH.sendMessage(m);
5716 }
5717
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005718 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5719 String hostingType) {
5720 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005721 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5722 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005723 + activity.processName);
5724 }
5725 // Post message to start process to avoid possible deadlock of calling into AMS with the
5726 // ATMS lock held.
5727 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5728 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5729 isTop, hostingType, activity.intent.getComponent());
5730 mH.sendMessage(m);
5731 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005732 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005733 }
5734 }
5735
Wale Ogunwale53783742018-09-16 10:21:51 -07005736 void setBooting(boolean booting) {
5737 mAmInternal.setBooting(booting);
5738 }
5739
5740 boolean isBooting() {
5741 return mAmInternal.isBooting();
5742 }
5743
5744 void setBooted(boolean booted) {
5745 mAmInternal.setBooted(booted);
5746 }
5747
5748 boolean isBooted() {
5749 return mAmInternal.isBooted();
5750 }
5751
5752 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5753 mH.post(() -> {
5754 if (finishBooting) {
5755 mAmInternal.finishBooting();
5756 }
5757 if (enableScreen) {
5758 mInternal.enableScreenAfterBoot(isBooted());
5759 }
5760 });
5761 }
5762
5763 void setHeavyWeightProcess(ActivityRecord root) {
5764 mHeavyWeightProcess = root.app;
5765 final Message m = PooledLambda.obtainMessage(
5766 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005767 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005768 mH.sendMessage(m);
5769 }
5770
5771 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5772 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5773 return;
5774 }
5775
5776 mHeavyWeightProcess = null;
5777 final Message m = PooledLambda.obtainMessage(
5778 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5779 proc.mUserId);
5780 mH.sendMessage(m);
5781 }
5782
5783 private void cancelHeavyWeightProcessNotification(int userId) {
5784 final INotificationManager inm = NotificationManager.getService();
5785 if (inm == null) {
5786 return;
5787 }
5788 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005789 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005790 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5791 } catch (RuntimeException e) {
5792 Slog.w(TAG, "Error canceling notification for service", e);
5793 } catch (RemoteException e) {
5794 }
5795
5796 }
5797
5798 private void postHeavyWeightProcessNotification(
5799 WindowProcessController proc, Intent intent, int userId) {
5800 if (proc == null) {
5801 return;
5802 }
5803
5804 final INotificationManager inm = NotificationManager.getService();
5805 if (inm == null) {
5806 return;
5807 }
5808
5809 try {
5810 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5811 String text = mContext.getString(R.string.heavy_weight_notification,
5812 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5813 Notification notification =
5814 new Notification.Builder(context,
5815 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5816 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5817 .setWhen(0)
5818 .setOngoing(true)
5819 .setTicker(text)
5820 .setColor(mContext.getColor(
5821 com.android.internal.R.color.system_notification_accent_color))
5822 .setContentTitle(text)
5823 .setContentText(
5824 mContext.getText(R.string.heavy_weight_notification_detail))
5825 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5826 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5827 new UserHandle(userId)))
5828 .build();
5829 try {
5830 inm.enqueueNotificationWithTag("android", "android", null,
5831 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5832 } catch (RuntimeException e) {
5833 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5834 } catch (RemoteException e) {
5835 }
5836 } catch (PackageManager.NameNotFoundException e) {
5837 Slog.w(TAG, "Unable to create context for heavy notification", e);
5838 }
5839
5840 }
5841
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005842 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5843 IBinder token, String resultWho, int requestCode, Intent[] intents,
5844 String[] resolvedTypes, int flags, Bundle bOptions) {
5845
5846 ActivityRecord activity = null;
5847 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5848 activity = ActivityRecord.isInStackLocked(token);
5849 if (activity == null) {
5850 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5851 return null;
5852 }
5853 if (activity.finishing) {
5854 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5855 return null;
5856 }
5857 }
5858
5859 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5860 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5861 bOptions);
5862 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5863 if (noCreate) {
5864 return rec;
5865 }
5866 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5867 if (activity.pendingResults == null) {
5868 activity.pendingResults = new HashSet<>();
5869 }
5870 activity.pendingResults.add(rec.ref);
5871 }
5872 return rec;
5873 }
5874
Andrii Kulian52d255c2018-07-13 11:32:19 -07005875 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005876 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005877 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005878 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5879 mCurAppTimeTracker.start(resumedActivity.packageName);
5880 }
5881 }
5882
5883 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5884 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005885 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005886 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5887 }
5888 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005889 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005890 constructResumedTraceName(resumed.packageName), 0);
5891 }
5892 mTracedResumedActivity = resumed;
5893 }
5894
5895 private String constructResumedTraceName(String packageName) {
5896 return "focused app: " + packageName;
5897 }
5898
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005899 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005900 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005901 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005902 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005903 // mainStack is null during startup.
5904 if (mainStack != null) {
5905 if (changes != 0 && starting == null) {
5906 // If the configuration changed, and the caller is not already
5907 // in the process of starting an activity, then find the top
5908 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005909 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005910 }
5911
5912 if (starting != null) {
5913 kept = starting.ensureActivityConfiguration(changes,
5914 false /* preserveWindow */);
5915 // And we need to make sure at this point that all other activities
5916 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005917 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005918 !PRESERVE_WINDOWS);
5919 }
5920 }
5921
5922 return kept;
5923 }
5924
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005925 void scheduleAppGcsLocked() {
5926 mH.post(() -> mAmInternal.scheduleAppGcs());
5927 }
5928
Wale Ogunwale53783742018-09-16 10:21:51 -07005929 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5930 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5931 }
5932
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005933 /**
5934 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5935 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5936 * on demand.
5937 */
5938 IPackageManager getPackageManager() {
5939 return AppGlobals.getPackageManager();
5940 }
5941
5942 PackageManagerInternal getPackageManagerInternalLocked() {
5943 if (mPmInternal == null) {
5944 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5945 }
5946 return mPmInternal;
5947 }
5948
Hai Zhangf4da9be2019-05-01 13:46:06 +08005949 PermissionPolicyInternal getPermissionPolicyInternal() {
5950 if (mPermissionPolicyInternal == null) {
5951 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5952 }
5953 return mPermissionPolicyInternal;
5954 }
5955
Wale Ogunwale008163e2018-07-23 23:11:08 -07005956 AppWarnings getAppWarningsLocked() {
5957 return mAppWarnings;
5958 }
5959
Wale Ogunwale214f3482018-10-04 11:00:47 -07005960 Intent getHomeIntent() {
5961 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5962 intent.setComponent(mTopComponent);
5963 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5964 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5965 intent.addCategory(Intent.CATEGORY_HOME);
5966 }
5967 return intent;
5968 }
5969
Chilun2ef71f72018-11-16 17:57:15 +08005970 /**
5971 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5972 * activities.
5973 *
5974 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5975 * component defined in config_secondaryHomeComponent.
5976 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5977 */
5978 Intent getSecondaryHomeIntent(String preferredPackage) {
5979 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005980 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5981 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5982 if (preferredPackage == null || useSystemProvidedLauncher) {
5983 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005984 final String secondaryHomeComponent = mContext.getResources().getString(
5985 com.android.internal.R.string.config_secondaryHomeComponent);
5986 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5987 } else {
5988 intent.setPackage(preferredPackage);
5989 }
5990 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5991 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5992 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5993 }
5994 return intent;
5995 }
5996
Wale Ogunwale214f3482018-10-04 11:00:47 -07005997 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5998 if (info == null) return null;
5999 ApplicationInfo newInfo = new ApplicationInfo(info);
6000 newInfo.initForUser(userId);
6001 return newInfo;
6002 }
6003
Wale Ogunwale9c103022018-10-18 07:44:54 -07006004 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006005 if (uid == SYSTEM_UID) {
6006 // The system gets to run in any process. If there are multiple processes with the same
6007 // uid, just pick the first (this should never happen).
6008 final SparseArray<WindowProcessController> procs =
6009 mProcessNames.getMap().get(processName);
6010 if (procs == null) return null;
6011 final int procCount = procs.size();
6012 for (int i = 0; i < procCount; i++) {
6013 final int procUid = procs.keyAt(i);
6014 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
6015 // Don't use an app process or different user process for system component.
6016 continue;
6017 }
6018 return procs.valueAt(i);
6019 }
6020 }
6021
6022 return mProcessNames.get(processName, uid);
6023 }
6024
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006025 WindowProcessController getProcessController(IApplicationThread thread) {
6026 if (thread == null) {
6027 return null;
6028 }
6029
6030 final IBinder threadBinder = thread.asBinder();
6031 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
6032 for (int i = pmap.size()-1; i >= 0; i--) {
6033 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
6034 for (int j = procs.size() - 1; j >= 0; j--) {
6035 final WindowProcessController proc = procs.valueAt(j);
6036 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
6037 return proc;
6038 }
6039 }
6040 }
6041
6042 return null;
6043 }
6044
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006045 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006046 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09006047 if (proc == null) return null;
6048 if (UserHandle.isApp(uid) && proc.mUid == uid) {
6049 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006050 }
6051 return null;
6052 }
6053
Riddle Hsua0536432019-02-16 00:38:59 +08006054 int getUidState(int uid) {
6055 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006056 }
6057
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006058 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01006059 // A uid is considered to be foreground if it has a visible non-toast window.
6060 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006061 }
6062
Ricky Wai96f5c352019-04-10 18:40:17 +01006063 boolean isDeviceOwner(int uid) {
6064 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006065 }
6066
Ricky Wai96f5c352019-04-10 18:40:17 +01006067 void setDeviceOwnerUid(int uid) {
6068 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006069 }
6070
Wale Ogunwale9de19442018-10-18 19:05:03 -07006071 /**
6072 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6073 * the whitelist
6074 */
6075 String getPendingTempWhitelistTagForUidLocked(int uid) {
6076 return mPendingTempWhitelist.get(uid);
6077 }
6078
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006079 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6080 if (true || Build.IS_USER) {
6081 return;
6082 }
6083
6084 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6085 StrictMode.allowThreadDiskWrites();
6086 try {
6087 File tracesDir = new File("/data/anr");
6088 File tracesFile = null;
6089 try {
6090 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6091
6092 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006093 String timeString =
6094 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6095 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006096 sb.append(": ");
6097 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6098 sb.append(" since ");
6099 sb.append(msg);
6100 FileOutputStream fos = new FileOutputStream(tracesFile);
6101 fos.write(sb.toString().getBytes());
6102 if (app == null) {
6103 fos.write("\n*** No application process!".getBytes());
6104 }
6105 fos.close();
6106 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6107 } catch (IOException e) {
6108 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6109 return;
6110 }
6111
6112 if (app != null && app.getPid() > 0) {
6113 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6114 firstPids.add(app.getPid());
6115 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6116 }
6117
6118 File lastTracesFile = null;
6119 File curTracesFile = null;
6120 for (int i=9; i>=0; i--) {
6121 String name = String.format(Locale.US, "slow%02d.txt", i);
6122 curTracesFile = new File(tracesDir, name);
6123 if (curTracesFile.exists()) {
6124 if (lastTracesFile != null) {
6125 curTracesFile.renameTo(lastTracesFile);
6126 } else {
6127 curTracesFile.delete();
6128 }
6129 }
6130 lastTracesFile = curTracesFile;
6131 }
6132 tracesFile.renameTo(curTracesFile);
6133 } finally {
6134 StrictMode.setThreadPolicy(oldPolicy);
6135 }
6136 }
6137
Michal Karpinskida34cd42019-04-02 19:46:52 +01006138 boolean isAssociatedCompanionApp(int userId, int uid) {
6139 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6140 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006141 return false;
6142 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006143 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006144 }
6145
Issei Suzuki734bc942019-06-05 13:59:52 +02006146 void notifySingleTaskDisplayEmpty(int displayId) {
6147 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6148 }
6149
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006150 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006151 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006152
6153
Wale Ogunwale98875612018-10-12 07:53:02 -07006154 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6155 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006156
Riddle Hsud93a6c42018-11-29 21:50:06 +08006157 H(Looper looper) {
6158 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006159 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006160
6161 @Override
6162 public void handleMessage(Message msg) {
6163 switch (msg.what) {
6164 case REPORT_TIME_TRACKER_MSG: {
6165 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6166 tracker.deliverResult(mContext);
6167 } break;
6168 }
6169 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006170 }
6171
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006172 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006173 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006174
6175 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006176 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006177 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006178
6179 @Override
6180 public void handleMessage(Message msg) {
6181 switch (msg.what) {
6182 case DISMISS_DIALOG_UI_MSG: {
6183 final Dialog d = (Dialog) msg.obj;
6184 d.dismiss();
6185 break;
6186 }
6187 }
6188 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006189 }
6190
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006191 final class LocalService extends ActivityTaskManagerInternal {
6192 @Override
6193 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006194 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006195 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006196 }
6197
6198 @Override
6199 public ComponentName getHomeActivityForUser(int userId) {
6200 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006201 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006202 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006203 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006204 }
6205 }
6206
6207 @Override
6208 public void onLocalVoiceInteractionStarted(IBinder activity,
6209 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6210 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006211 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006212 }
6213 }
6214
6215 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006216 public void notifySingleTaskDisplayDrawn(int displayId) {
6217 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6218 }
6219
6220 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006221 public void notifyAppTransitionFinished() {
6222 synchronized (mGlobalLock) {
6223 mStackSupervisor.notifyAppTransitionDone();
6224 }
6225 }
6226
6227 @Override
6228 public void notifyAppTransitionCancelled() {
6229 synchronized (mGlobalLock) {
6230 mStackSupervisor.notifyAppTransitionDone();
6231 }
6232 }
6233
6234 @Override
6235 public List<IBinder> getTopVisibleActivities() {
6236 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006237 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006238 }
6239 }
6240
6241 @Override
6242 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6243 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006244 mRootWindowContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006245 }
6246 }
6247
6248 @Override
6249 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6250 Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006251 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006252 final String[] resolvedTypes = new String[intents.length];
6253
6254 // UID of the package on user userId.
6255 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6256 // packageUid may not be initialized.
6257 int packageUid = 0;
6258 final long ident = Binder.clearCallingIdentity();
6259
6260 try {
6261 for (int i = 0; i < intents.length; i++) {
6262 resolvedTypes[i] =
6263 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6264 }
6265
6266 packageUid = AppGlobals.getPackageManager().getPackageUid(
6267 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6268 } catch (RemoteException e) {
6269 // Shouldn't happen.
6270 } finally {
6271 Binder.restoreCallingIdentity(ident);
6272 }
6273
Riddle Hsu591bf612019-02-14 17:55:31 +08006274 return getActivityStartController().startActivitiesInPackage(
6275 packageUid, packageName,
6276 intents, resolvedTypes, null /* resultTo */,
6277 SafeActivityOptions.fromBundle(bOptions), userId,
6278 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6279 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006280 }
6281
6282 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006283 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6284 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6285 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6286 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006287 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006288 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006289 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6290 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6291 userId, validateIncomingUser, originatingPendingIntent,
6292 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006293 }
6294 }
6295
6296 @Override
6297 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6298 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6299 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006300 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006301 PendingIntentRecord originatingPendingIntent,
6302 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006303 synchronized (mGlobalLock) {
6304 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6305 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6306 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006307 validateIncomingUser, originatingPendingIntent,
6308 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006309 }
6310 }
6311
6312 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006313 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6314 Intent intent, Bundle options, int userId) {
6315 return ActivityTaskManagerService.this.startActivityAsUser(
6316 caller, callerPacakge, intent,
6317 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6318 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6319 false /*validateIncomingUser*/);
6320 }
6321
6322 @Override
lumark588a3e82018-07-20 18:53:54 +08006323 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006324 synchronized (mGlobalLock) {
6325
6326 // We might change the visibilities here, so prepare an empty app transition which
6327 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006328 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006329 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006330 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006331 return;
6332 }
Louis Chang677921f2019-12-06 16:44:24 +08006333 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006334 final boolean wasTransitionSet =
6335 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006336 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006337 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006338 }
Louis Chang149d5c82019-12-30 09:47:39 +08006339 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006340
6341 // If there was a transition set already we don't want to interfere with it as we
6342 // might be starting it too early.
6343 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006344 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006345 }
6346 }
6347 if (callback != null) {
6348 callback.run();
6349 }
6350 }
6351
6352 @Override
6353 public void notifyKeyguardTrustedChanged() {
6354 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006355 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006356 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006357 }
6358 }
6359 }
6360
6361 /**
6362 * Called after virtual display Id is updated by
6363 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6364 * {@param vrVr2dDisplayId}.
6365 */
6366 @Override
6367 public void setVr2dDisplayId(int vr2dDisplayId) {
6368 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6369 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006370 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006371 }
6372 }
6373
6374 @Override
6375 public void setFocusedActivity(IBinder token) {
6376 synchronized (mGlobalLock) {
6377 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6378 if (r == null) {
6379 throw new IllegalArgumentException(
6380 "setFocusedActivity: No activity record matching token=" + token);
6381 }
Louis Chang19443452018-10-09 12:10:21 +08006382 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006383 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006384 }
6385 }
6386 }
6387
6388 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006389 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006390 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006391 }
6392
6393 @Override
6394 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006395 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006396 }
6397
6398 @Override
6399 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006400 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006401 }
6402
6403 @Override
6404 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6405 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6406 }
6407
6408 @Override
6409 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006410 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006411 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006412
6413 @Override
6414 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6415 synchronized (mGlobalLock) {
6416 mActiveVoiceInteractionServiceComponent = component;
6417 }
6418 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006419
6420 @Override
6421 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6422 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6423 return;
6424 }
6425 synchronized (mGlobalLock) {
6426 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6427 if (types == null) {
6428 if (uid < 0) {
6429 return;
6430 }
6431 types = new ArrayMap<>();
6432 mAllowAppSwitchUids.put(userId, types);
6433 }
6434 if (uid < 0) {
6435 types.remove(type);
6436 } else {
6437 types.put(type, uid);
6438 }
6439 }
6440 }
6441
6442 @Override
6443 public void onUserStopped(int userId) {
6444 synchronized (mGlobalLock) {
6445 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6446 mAllowAppSwitchUids.remove(userId);
6447 }
6448 }
6449
6450 @Override
6451 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6452 synchronized (mGlobalLock) {
6453 return ActivityTaskManagerService.this.isGetTasksAllowed(
6454 caller, callingPid, callingUid);
6455 }
6456 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006457
Riddle Hsua0536432019-02-16 00:38:59 +08006458 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006459 @Override
6460 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006461 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006462 mProcessNames.put(proc.mName, proc.mUid, proc);
6463 }
6464 }
6465
Riddle Hsua0536432019-02-16 00:38:59 +08006466 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006467 @Override
6468 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006469 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006470 mProcessNames.remove(name, uid);
6471 }
6472 }
6473
Riddle Hsua0536432019-02-16 00:38:59 +08006474 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006475 @Override
6476 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006477 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006478 if (proc == mHomeProcess) {
6479 mHomeProcess = null;
6480 }
6481 if (proc == mPreviousProcess) {
6482 mPreviousProcess = null;
6483 }
6484 }
6485 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006486
Riddle Hsua0536432019-02-16 00:38:59 +08006487 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006488 @Override
6489 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006490 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006491 return mTopProcessState;
6492 }
6493 }
6494
Riddle Hsua0536432019-02-16 00:38:59 +08006495 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006496 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006497 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006498 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006499 return proc == mHeavyWeightProcess;
6500 }
6501 }
6502
Riddle Hsua0536432019-02-16 00:38:59 +08006503 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006504 @Override
6505 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006506 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006507 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6508 }
6509 }
6510
6511 @Override
6512 public void finishHeavyWeightApp() {
6513 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006514 if (mHeavyWeightProcess != null) {
6515 mHeavyWeightProcess.finishActivities();
6516 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006517 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6518 mHeavyWeightProcess);
6519 }
6520 }
6521
Riddle Hsua0536432019-02-16 00:38:59 +08006522 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006523 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006524 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006525 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006526 return isSleepingLocked();
6527 }
6528 }
6529
6530 @Override
6531 public boolean isShuttingDown() {
6532 synchronized (mGlobalLock) {
6533 return mShuttingDown;
6534 }
6535 }
6536
6537 @Override
6538 public boolean shuttingDown(boolean booted, int timeout) {
6539 synchronized (mGlobalLock) {
6540 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006541 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006542 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006543 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006544 return mStackSupervisor.shutdownLocked(timeout);
6545 }
6546 }
6547
6548 @Override
6549 public void enableScreenAfterBoot(boolean booted) {
6550 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006551 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006552 mWindowManager.enableScreenAfterBoot();
6553 updateEventDispatchingLocked(booted);
6554 }
6555 }
6556
6557 @Override
6558 public boolean showStrictModeViolationDialog() {
6559 synchronized (mGlobalLock) {
6560 return mShowDialogs && !mSleeping && !mShuttingDown;
6561 }
6562 }
6563
6564 @Override
6565 public void showSystemReadyErrorDialogsIfNeeded() {
6566 synchronized (mGlobalLock) {
6567 try {
6568 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6569 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6570 + " data partition or your device will be unstable.");
6571 mUiHandler.post(() -> {
6572 if (mShowDialogs) {
6573 AlertDialog d = new BaseErrorDialog(mUiContext);
6574 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6575 d.setCancelable(false);
6576 d.setTitle(mUiContext.getText(R.string.android_system_label));
6577 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6578 d.setButton(DialogInterface.BUTTON_POSITIVE,
6579 mUiContext.getText(R.string.ok),
6580 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6581 d.show();
6582 }
6583 });
6584 }
6585 } catch (RemoteException e) {
6586 }
6587
6588 if (!Build.isBuildConsistent()) {
6589 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6590 mUiHandler.post(() -> {
6591 if (mShowDialogs) {
6592 AlertDialog d = new BaseErrorDialog(mUiContext);
6593 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6594 d.setCancelable(false);
6595 d.setTitle(mUiContext.getText(R.string.android_system_label));
6596 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6597 d.setButton(DialogInterface.BUTTON_POSITIVE,
6598 mUiContext.getText(R.string.ok),
6599 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6600 d.show();
6601 }
6602 });
6603 }
6604 }
6605 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006606
6607 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006608 public void onProcessMapped(int pid, WindowProcessController proc) {
6609 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006610 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006611 }
6612 }
6613
6614 @Override
6615 public void onProcessUnMapped(int pid) {
6616 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006617 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006618 }
6619 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006620
6621 @Override
6622 public void onPackageDataCleared(String name) {
6623 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006624 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006625 mAppWarnings.onPackageDataCleared(name);
6626 }
6627 }
6628
6629 @Override
6630 public void onPackageUninstalled(String name) {
6631 synchronized (mGlobalLock) {
6632 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006633 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006634 }
6635 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006636
6637 @Override
6638 public void onPackageAdded(String name, boolean replacing) {
6639 synchronized (mGlobalLock) {
6640 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6641 }
6642 }
6643
6644 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006645 public void onPackageReplaced(ApplicationInfo aInfo) {
6646 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006647 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006648 }
6649 }
6650
6651 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006652 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6653 synchronized (mGlobalLock) {
6654 return compatibilityInfoForPackageLocked(ai);
6655 }
6656 }
6657
Yunfan Chen75157d72018-07-27 14:47:21 +09006658 /**
6659 * Set the corresponding display information for the process global configuration. To be
6660 * called when we need to show IME on a different display.
6661 *
6662 * @param pid The process id associated with the IME window.
6663 * @param displayId The ID of the display showing the IME.
6664 */
6665 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006666 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006667 // Don't update process-level configuration for Multi-Client IME process since other
6668 // IMEs on other displays will also receive this configuration change due to IME
6669 // services use the same application config/context.
6670 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006671
Yunfan Chen75157d72018-07-27 14:47:21 +09006672 if (pid == MY_PID || pid < 0) {
6673 if (DEBUG_CONFIGURATION) {
6674 Slog.w(TAG,
6675 "Trying to update display configuration for system/invalid process.");
6676 }
6677 return;
6678 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006679 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006680 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006681 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006682 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006683 // Call might come when display is not yet added or has been removed.
6684 if (DEBUG_CONFIGURATION) {
6685 Slog.w(TAG, "Trying to update display configuration for non-existing "
6686 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006687 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006688 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006689 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006690 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006691 if (process == null) {
6692 if (DEBUG_CONFIGURATION) {
6693 Slog.w(TAG, "Trying to update display configuration for invalid "
6694 + "process, pid=" + pid);
6695 }
6696 return;
6697 }
lumarkddc77fb2019-06-27 22:22:23 +08006698 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006699 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006700 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006701 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006702
6703 @Override
6704 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006705 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006706 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006707 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6708 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006709 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006710 }
6711 }
6712 }
6713
6714 @Override
6715 public void clearPendingResultForActivity(IBinder activityToken,
6716 WeakReference<PendingIntentRecord> pir) {
6717 synchronized (mGlobalLock) {
6718 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6719 if (r != null && r.pendingResults != null) {
6720 r.pendingResults.remove(pir);
6721 }
6722 }
6723 }
6724
6725 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006726 public ActivityTokens getTopActivityForTask(int taskId) {
6727 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006728 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006729 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006730 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6731 + " Requested task not found");
6732 return null;
6733 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006734 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006735 if (activity == null) {
6736 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6737 + " Requested activity not found");
6738 return null;
6739 }
6740 if (!activity.attachedToProcess()) {
6741 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6742 + activity);
6743 return null;
6744 }
6745 return new ActivityTokens(activity.appToken, activity.assistToken,
6746 activity.app.getThread());
6747 }
6748 }
6749
6750 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006751 public IIntentSender getIntentSender(int type, String packageName,
6752 int callingUid, int userId, IBinder token, String resultWho,
6753 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6754 Bundle bOptions) {
6755 synchronized (mGlobalLock) {
6756 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6757 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6758 }
6759 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006760
6761 @Override
6762 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6763 synchronized (mGlobalLock) {
6764 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6765 if (r == null) {
6766 return null;
6767 }
6768 if (r.mServiceConnectionsHolder == null) {
6769 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6770 ActivityTaskManagerService.this, r);
6771 }
6772
6773 return r.mServiceConnectionsHolder;
6774 }
6775 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006776
6777 @Override
6778 public Intent getHomeIntent() {
6779 synchronized (mGlobalLock) {
6780 return ActivityTaskManagerService.this.getHomeIntent();
6781 }
6782 }
6783
6784 @Override
6785 public boolean startHomeActivity(int userId, String reason) {
6786 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006787 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006788 }
6789 }
6790
6791 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006792 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006793 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006794 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006795 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006796 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006797 }
Chilun8b1f1be2019-03-13 17:14:36 +08006798 }
6799
6800 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006801 public boolean startHomeOnAllDisplays(int userId, String reason) {
6802 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006803 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006804 }
6805 }
6806
Riddle Hsua0536432019-02-16 00:38:59 +08006807 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006808 @Override
6809 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006810 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006811 if (mFactoryTest == FACTORY_TEST_OFF) {
6812 return false;
6813 }
6814 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6815 && wpc.mName.equals(mTopComponent.getPackageName())) {
6816 return true;
6817 }
6818 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6819 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6820 }
6821 }
6822
6823 @Override
6824 public void updateTopComponentForFactoryTest() {
6825 synchronized (mGlobalLock) {
6826 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6827 return;
6828 }
6829 final ResolveInfo ri = mContext.getPackageManager()
6830 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6831 final CharSequence errorMsg;
6832 if (ri != null) {
6833 final ActivityInfo ai = ri.activityInfo;
6834 final ApplicationInfo app = ai.applicationInfo;
6835 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6836 mTopAction = Intent.ACTION_FACTORY_TEST;
6837 mTopData = null;
6838 mTopComponent = new ComponentName(app.packageName, ai.name);
6839 errorMsg = null;
6840 } else {
6841 errorMsg = mContext.getResources().getText(
6842 com.android.internal.R.string.factorytest_not_system);
6843 }
6844 } else {
6845 errorMsg = mContext.getResources().getText(
6846 com.android.internal.R.string.factorytest_no_action);
6847 }
6848 if (errorMsg == null) {
6849 return;
6850 }
6851
6852 mTopAction = null;
6853 mTopData = null;
6854 mTopComponent = null;
6855 mUiHandler.post(() -> {
6856 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6857 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006858 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006859 });
6860 }
6861 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006862
Riddle Hsua0536432019-02-16 00:38:59 +08006863 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006864 @Override
6865 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6866 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006867 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006868 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006869 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006870
6871 wpc.clearRecentTasks();
6872 wpc.clearActivities();
6873
6874 if (wpc.isInstrumenting()) {
6875 finishInstrumentationCallback.run();
6876 }
6877
Jorim Jaggid0752812018-10-16 16:07:20 +02006878 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006879 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006880 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006881 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006882 // If there was nothing to resume, and we are not already restarting
6883 // this process, but there is a visible activity that is hosted by the
6884 // process...then make sure all visible activities are running, taking
6885 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006886 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006887 !PRESERVE_WINDOWS);
6888 }
6889 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006890 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006891 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006892 }
6893 }
6894 }
6895
6896 @Override
6897 public void closeSystemDialogs(String reason) {
6898 enforceNotIsolatedCaller("closeSystemDialogs");
6899
6900 final int pid = Binder.getCallingPid();
6901 final int uid = Binder.getCallingUid();
6902 final long origId = Binder.clearCallingIdentity();
6903 try {
6904 synchronized (mGlobalLock) {
6905 // Only allow this from foreground processes, so that background
6906 // applications can't abuse it to prevent system UI from being shown.
6907 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006908 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006909 if (!proc.isPerceptible()) {
6910 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6911 + " from background process " + proc);
6912 return;
6913 }
6914 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006915 mWindowManager.closeSystemDialogs(reason);
6916
Louis Chang149d5c82019-12-30 09:47:39 +08006917 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006918 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006919 // Call into AM outside the synchronized block.
6920 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006921 } finally {
6922 Binder.restoreCallingIdentity(origId);
6923 }
6924 }
6925
6926 @Override
6927 public void cleanupDisabledPackageComponents(
6928 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6929 synchronized (mGlobalLock) {
6930 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006931 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006932 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006933 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006934 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006935 }
6936
6937 // Clean-up disabled tasks
6938 getRecentTasks().cleanupDisabledPackageTasksLocked(
6939 packageName, disabledClasses, userId);
6940 }
6941 }
6942
6943 @Override
6944 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6945 int userId) {
6946 synchronized (mGlobalLock) {
6947
6948 boolean didSomething =
6949 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006950 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006951 null, doit, evenPersistent, userId);
6952 return didSomething;
6953 }
6954 }
6955
6956 @Override
6957 public void resumeTopActivities(boolean scheduleIdle) {
6958 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006959 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006960 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006961 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006962 }
6963 }
6964 }
6965
Riddle Hsua0536432019-02-16 00:38:59 +08006966 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006967 @Override
6968 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006969 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006970 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6971 }
6972 }
6973
Riddle Hsua0536432019-02-16 00:38:59 +08006974 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006975 @Override
6976 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006977 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006978 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6979 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6980 }
6981 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006982 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006983 } finally {
6984 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6985 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006986 }
6987 }
6988
6989 @Override
6990 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6991 try {
6992 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6993 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6994 }
6995 } catch (RemoteException ex) {
6996 throw new SecurityException("Fail to check is caller a privileged app", ex);
6997 }
6998
6999 synchronized (mGlobalLock) {
7000 final long ident = Binder.clearCallingIdentity();
7001 try {
7002 if (mAmInternal.shouldConfirmCredentials(userId)) {
7003 if (mKeyguardController.isKeyguardLocked()) {
7004 // Showing launcher to avoid user entering credential twice.
7005 startHomeActivity(currentUserId, "notifyLockedProfile");
7006 }
Louis Chang149d5c82019-12-30 09:47:39 +08007007 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007008 }
7009 } finally {
7010 Binder.restoreCallingIdentity(ident);
7011 }
7012 }
7013 }
7014
7015 @Override
7016 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
7017 mAmInternal.enforceCallingPermission(
7018 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
7019
7020 synchronized (mGlobalLock) {
7021 final long ident = Binder.clearCallingIdentity();
7022 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01007023 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
7024 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07007025 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007026 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
7027 UserHandle.CURRENT);
7028 } finally {
7029 Binder.restoreCallingIdentity(ident);
7030 }
7031 }
7032 }
7033
7034 @Override
7035 public void writeActivitiesToProto(ProtoOutputStream proto) {
7036 synchronized (mGlobalLock) {
7037 // The output proto of "activity --proto activities"
7038 // is ActivityManagerServiceDumpActivitiesProto
Louis Chang149d5c82019-12-30 09:47:39 +08007039 mRootWindowContainer.dumpDebug(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08007040 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
7041 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007042 }
7043 }
7044
7045 @Override
7046 public void saveANRState(String reason) {
7047 synchronized (mGlobalLock) {
7048 final StringWriter sw = new StringWriter();
7049 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
7050 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
7051 if (reason != null) {
7052 pw.println(" Reason: " + reason);
7053 }
7054 pw.println();
7055 getActivityStartController().dump(pw, " ", null);
7056 pw.println();
7057 pw.println("-------------------------------------------------------------------------------");
7058 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7059 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7060 "" /* header */);
7061 pw.println();
7062 pw.close();
7063
7064 mLastANRState = sw.toString();
7065 }
7066 }
7067
7068 @Override
7069 public void clearSavedANRState() {
7070 synchronized (mGlobalLock) {
7071 mLastANRState = null;
7072 }
7073 }
7074
7075 @Override
7076 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7077 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7078 synchronized (mGlobalLock) {
7079 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7080 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7081 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7082 dumpLastANRLocked(pw);
7083 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7084 dumpLastANRTracesLocked(pw);
7085 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7086 dumpActivityStarterLocked(pw, dumpPackage);
7087 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7088 dumpActivityContainersLocked(pw);
7089 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7090 if (getRecentTasks() != null) {
7091 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7092 }
7093 }
7094 }
7095 }
7096
7097 @Override
7098 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7099 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7100 int wakefulness) {
7101 synchronized (mGlobalLock) {
7102 if (mHomeProcess != null && (dumpPackage == null
7103 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7104 if (needSep) {
7105 pw.println();
7106 needSep = false;
7107 }
7108 pw.println(" mHomeProcess: " + mHomeProcess);
7109 }
7110 if (mPreviousProcess != null && (dumpPackage == null
7111 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7112 if (needSep) {
7113 pw.println();
7114 needSep = false;
7115 }
7116 pw.println(" mPreviousProcess: " + mPreviousProcess);
7117 }
7118 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7119 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7120 StringBuilder sb = new StringBuilder(128);
7121 sb.append(" mPreviousProcessVisibleTime: ");
7122 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7123 pw.println(sb);
7124 }
7125 if (mHeavyWeightProcess != null && (dumpPackage == null
7126 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7127 if (needSep) {
7128 pw.println();
7129 needSep = false;
7130 }
7131 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7132 }
7133 if (dumpPackage == null) {
7134 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007135 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007136 }
7137 if (dumpAll) {
7138 if (dumpPackage == null) {
7139 pw.println(" mConfigWillChange: "
7140 + getTopDisplayFocusedStack().mConfigWillChange);
7141 }
7142 if (mCompatModePackages.getPackages().size() > 0) {
7143 boolean printed = false;
7144 for (Map.Entry<String, Integer> entry
7145 : mCompatModePackages.getPackages().entrySet()) {
7146 String pkg = entry.getKey();
7147 int mode = entry.getValue();
7148 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7149 continue;
7150 }
7151 if (!printed) {
7152 pw.println(" mScreenCompatPackages:");
7153 printed = true;
7154 }
7155 pw.println(" " + pkg + ": " + mode);
7156 }
7157 }
7158 }
7159
7160 if (dumpPackage == null) {
7161 pw.println(" mWakefulness="
7162 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007163 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007164 if (mRunningVoice != null) {
7165 pw.println(" mRunningVoice=" + mRunningVoice);
7166 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7167 }
7168 pw.println(" mSleeping=" + mSleeping);
7169 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7170 pw.println(" mVrController=" + mVrController);
7171 }
7172 if (mCurAppTimeTracker != null) {
7173 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7174 }
7175 if (mAllowAppSwitchUids.size() > 0) {
7176 boolean printed = false;
7177 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7178 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7179 for (int j = 0; j < types.size(); j++) {
7180 if (dumpPackage == null ||
7181 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7182 if (needSep) {
7183 pw.println();
7184 needSep = false;
7185 }
7186 if (!printed) {
7187 pw.println(" mAllowAppSwitchUids:");
7188 printed = true;
7189 }
7190 pw.print(" User ");
7191 pw.print(mAllowAppSwitchUids.keyAt(i));
7192 pw.print(": Type ");
7193 pw.print(types.keyAt(j));
7194 pw.print(" = ");
7195 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7196 pw.println();
7197 }
7198 }
7199 }
7200 }
7201 if (dumpPackage == null) {
7202 if (mController != null) {
7203 pw.println(" mController=" + mController
7204 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7205 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007206 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7207 pw.println(" mLaunchingActivityWakeLock="
7208 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007209 }
7210
7211 return needSep;
7212 }
7213 }
7214
7215 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007216 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7217 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007218 synchronized (mGlobalLock) {
7219 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007220 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007221 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007222 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7223 if (mRunningVoice != null) {
7224 final long vrToken = proto.start(
7225 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7226 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7227 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007228 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007229 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7230 proto.end(vrToken);
7231 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007232 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007233 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007234 if (mController != null) {
7235 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007236 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7237 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007238 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7239 proto.end(token);
7240 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007241 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7242 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007243 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007244 }
7245
7246 if (mHomeProcess != null && (dumpPackage == null
7247 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007248 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007249 }
7250
7251 if (mPreviousProcess != null && (dumpPackage == null
7252 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007253 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007254 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7255 }
7256
7257 if (mHeavyWeightProcess != null && (dumpPackage == null
7258 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007259 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007260 }
7261
7262 for (Map.Entry<String, Integer> entry
7263 : mCompatModePackages.getPackages().entrySet()) {
7264 String pkg = entry.getKey();
7265 int mode = entry.getValue();
7266 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7267 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7268 proto.write(PACKAGE, pkg);
7269 proto.write(MODE, mode);
7270 proto.end(compatToken);
7271 }
7272 }
7273
7274 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007275 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007276 }
7277
7278 }
7279 }
7280
7281 @Override
7282 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7283 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7284 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007285 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7286 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007287 }
7288
7289 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007290 public void dumpForOom(PrintWriter pw) {
7291 synchronized (mGlobalLock) {
7292 pw.println(" mHomeProcess: " + mHomeProcess);
7293 pw.println(" mPreviousProcess: " + mPreviousProcess);
7294 if (mHeavyWeightProcess != null) {
7295 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7296 }
7297 }
7298 }
7299
7300 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007301 public boolean canGcNow() {
7302 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007303 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007304 }
7305 }
7306
Riddle Hsua0536432019-02-16 00:38:59 +08007307 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007308 @Override
7309 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007310 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007311 if (mRootWindowContainer == null) {
7312 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007313 // oomadj after AMS created.
7314 return null;
7315 }
Louis Chang149d5c82019-12-30 09:47:39 +08007316 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007317 return top != null ? top.app : null;
7318 }
7319 }
7320
Riddle Hsua0536432019-02-16 00:38:59 +08007321 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007322 @Override
7323 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007324 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007325 if (mRootWindowContainer != null) {
7326 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007327 }
7328 }
7329 }
7330
7331 @Override
7332 public void scheduleDestroyAllActivities(String reason) {
7333 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007334 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007335 }
7336 }
7337
7338 @Override
7339 public void removeUser(int userId) {
7340 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007341 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007342 }
7343 }
7344
7345 @Override
7346 public boolean switchUser(int userId, UserState userState) {
7347 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007348 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007349 }
7350 }
7351
7352 @Override
7353 public void onHandleAppCrash(WindowProcessController wpc) {
7354 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007355 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007356 }
7357 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007358
7359 @Override
7360 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7361 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007362 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007363 }
7364 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007365
Riddle Hsua0536432019-02-16 00:38:59 +08007366 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007367 @Override
7368 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007369 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007370 }
7371
Riddle Hsua0536432019-02-16 00:38:59 +08007372 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007373 @Override
7374 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007375 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007376 }
7377
Riddle Hsua0536432019-02-16 00:38:59 +08007378 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007379 @Override
7380 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007381 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007382 }
7383
Riddle Hsua0536432019-02-16 00:38:59 +08007384 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007385 @Override
7386 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007387 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007388 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007389
7390 @Override
7391 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007392 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007393 mPendingTempWhitelist.put(uid, tag);
7394 }
7395 }
7396
7397 @Override
7398 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007399 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007400 mPendingTempWhitelist.remove(uid);
7401 }
7402 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007403
7404 @Override
7405 public boolean handleAppCrashInActivityController(String processName, int pid,
7406 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7407 Runnable killCrashingAppCallback) {
7408 synchronized (mGlobalLock) {
7409 if (mController == null) {
7410 return false;
7411 }
7412
7413 try {
7414 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7415 stackTrace)) {
7416 killCrashingAppCallback.run();
7417 return true;
7418 }
7419 } catch (RemoteException e) {
7420 mController = null;
7421 Watchdog.getInstance().setActivityController(null);
7422 }
7423 return false;
7424 }
7425 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007426
7427 @Override
7428 public void removeRecentTasksByPackageName(String packageName, int userId) {
7429 synchronized (mGlobalLock) {
7430 mRecentTasks.removeTasksByPackageName(packageName, userId);
7431 }
7432 }
7433
7434 @Override
7435 public void cleanupRecentTasksForUser(int userId) {
7436 synchronized (mGlobalLock) {
7437 mRecentTasks.cleanupLocked(userId);
7438 }
7439 }
7440
7441 @Override
7442 public void loadRecentTasksForUser(int userId) {
7443 synchronized (mGlobalLock) {
7444 mRecentTasks.loadUserRecentsLocked(userId);
7445 }
7446 }
7447
7448 @Override
7449 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7450 synchronized (mGlobalLock) {
7451 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7452 }
7453 }
7454
7455 @Override
7456 public void flushRecentTasks() {
7457 mRecentTasks.flush();
7458 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007459
7460 @Override
7461 public WindowProcessController getHomeProcess() {
7462 synchronized (mGlobalLock) {
7463 return mHomeProcess;
7464 }
7465 }
7466
7467 @Override
7468 public WindowProcessController getPreviousProcess() {
7469 synchronized (mGlobalLock) {
7470 return mPreviousProcess;
7471 }
7472 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007473
7474 @Override
7475 public void clearLockedTasks(String reason) {
7476 synchronized (mGlobalLock) {
7477 getLockTaskController().clearLockedTasks(reason);
7478 }
7479 }
7480
7481 @Override
7482 public void updateUserConfiguration() {
7483 synchronized (mGlobalLock) {
7484 final Configuration configuration = new Configuration(getGlobalConfiguration());
7485 final int currentUserId = mAmInternal.getCurrentUserId();
7486 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7487 configuration, currentUserId, Settings.System.canWrite(mContext));
7488 updateConfigurationLocked(configuration, null /* starting */,
7489 false /* initLocale */, false /* persistent */, currentUserId,
7490 false /* deferResume */);
7491 }
7492 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007493
7494 @Override
7495 public boolean canShowErrorDialogs() {
7496 synchronized (mGlobalLock) {
7497 return mShowDialogs && !mSleeping && !mShuttingDown
7498 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7499 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7500 mAmInternal.getCurrentUserId())
7501 && !(UserManager.isDeviceInDemoMode(mContext)
7502 && mAmInternal.getCurrentUser().isDemo());
7503 }
7504 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007505
7506 @Override
7507 public void setProfileApp(String profileApp) {
7508 synchronized (mGlobalLock) {
7509 mProfileApp = profileApp;
7510 }
7511 }
7512
7513 @Override
7514 public void setProfileProc(WindowProcessController wpc) {
7515 synchronized (mGlobalLock) {
7516 mProfileProc = wpc;
7517 }
7518 }
7519
7520 @Override
7521 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7522 synchronized (mGlobalLock) {
7523 mProfilerInfo = profilerInfo;
7524 }
7525 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007526
7527 @Override
7528 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7529 synchronized (mGlobalLock) {
7530 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7531 }
7532 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007533
7534 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007535 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7536 boolean reducedResolution) {
7537 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7538 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007539 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007540
7541 @Override
7542 public boolean isUidForeground(int uid) {
7543 synchronized (mGlobalLock) {
7544 return ActivityTaskManagerService.this.isUidForeground(uid);
7545 }
7546 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007547
7548 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007549 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007550 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007551 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007552 }
7553 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007554
7555 @Override
7556 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007557 // Translate package names into UIDs
7558 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007559 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007560 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7561 if (uid >= 0) {
7562 result.add(uid);
7563 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007564 }
7565 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007566 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007567 }
7568 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007569 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007570}