blob: efd21ec83924d19189c07d7d5aac6da513ff4477 [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;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootActivityContainer.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;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700159import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700160import android.content.ActivityNotFoundException;
161import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700162import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700163import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700164import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700165import android.content.IIntentSender;
166import android.content.Intent;
167import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700168import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900169import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700170import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700172import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.pm.ParceledListSlice;
174import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700175import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700177import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700178import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.graphics.Bitmap;
180import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.metrics.LogMaker;
183import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700184import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700187import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700189import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700190import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700191import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700192import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800193import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700194import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700197import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100198import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700199import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700201import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700202import android.os.SystemClock;
203import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700204import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700205import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700206import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700207import android.os.UserManager;
208import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700209import android.os.storage.IStorageManager;
210import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import android.provider.Settings;
212import android.service.voice.IVoiceInteractionSession;
213import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900214import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700215import android.telecom.TelecomManager;
216import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100217import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700219import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700221import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.SparseArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700223import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700224import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700225import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700226import android.view.IRecentsAnimationRunner;
227import android.view.RemoteAnimationAdapter;
228import android.view.RemoteAnimationDefinition;
Evan Roskyddedfd42019-10-04 13:38:38 -0700229import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700230import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700231
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700233import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700235import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700237import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700240import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
241import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700242import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700243import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700244import com.android.internal.policy.IKeyguardDismissCallback;
245import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700246import com.android.internal.util.ArrayUtils;
247import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700248import com.android.internal.util.Preconditions;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800249import com.android.internal.util.function.pooled.PooledConsumer;
250import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700251import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700252import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700253import com.android.server.LocalServices;
254import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700255import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800256import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700257import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700258import com.android.server.am.ActivityManagerService;
259import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
260import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
261import com.android.server.am.AppTimeTracker;
262import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700263import com.android.server.am.PendingIntentController;
264import com.android.server.am.PendingIntentRecord;
265import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900266import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700267import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700268import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700269import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800270import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700271import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700275import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700277import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700279import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700280import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700281import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800282import java.lang.annotation.ElementType;
283import java.lang.annotation.Retention;
284import java.lang.annotation.RetentionPolicy;
285import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700286import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700288import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700289import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700290import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400291import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700292import java.util.HashSet;
Evan Roskyddedfd42019-10-04 13:38:38 -0700293import java.util.Iterator;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700295import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700296import java.util.Map;
297import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700298
299/**
300 * System service for managing activities and their containers (task, stacks, displays,... ).
301 *
302 * {@hide}
303 */
304public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700305 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700306 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700307 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
308 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
309 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
310 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
311 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700312 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700313
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700314 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700315 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700316 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700317 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100318 // How long we permit background activity starts after an activity in the process
319 // started or finished.
320 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700321
Wale Ogunwale98875612018-10-12 07:53:02 -0700322 /** Used to indicate that an app transition should be animated. */
323 static final boolean ANIMATE = true;
324
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700325 /** Hardware-reported OpenGLES version. */
326 final int GL_ES_VERSION;
327
Wale Ogunwale31913b52018-10-13 08:29:31 -0700328 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
329 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
330 public static final String DUMP_LASTANR_CMD = "lastanr" ;
331 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
332 public static final String DUMP_STARTER_CMD = "starter" ;
333 public static final String DUMP_CONTAINERS_CMD = "containers" ;
334 public static final String DUMP_RECENTS_CMD = "recents" ;
335 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
336
Wale Ogunwale64258362018-10-16 15:13:37 -0700337 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
338 public static final int RELAUNCH_REASON_NONE = 0;
339 /** This activity is being relaunched due to windowing mode change. */
340 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
341 /** This activity is being relaunched due to a free-resize operation. */
342 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
343
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700344 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700345
Wale Ogunwalef6733932018-06-27 05:14:34 -0700346 /**
347 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
348 * change at runtime. Use mContext for non-UI purposes.
349 */
350 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700351 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700352 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700353 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700354 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700355 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700356 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800357 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800358 @VisibleForTesting
359 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700360 PowerManagerInternal mPowerManagerInternal;
361 private UsageStatsManagerInternal mUsageStatsInternal;
362
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700363 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700364 IntentFirewall mIntentFirewall;
365
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700366 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800367 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800368 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700369 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800370 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
371 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
372 *
373 * @see WindowManagerThreadPriorityBooster
374 */
375 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700376 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800377 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700378 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700379 private UserManagerService mUserManager;
380 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700381 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800382 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700383 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700384 /** All processes currently running that might have a window organized by name. */
385 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100386 /** All processes we currently have running mapped by pid and uid */
387 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700388 /** This is the process holding what we currently consider to be the "home" activity. */
389 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700390 /** The currently running heavy-weight process, if any. */
391 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700392 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700393 /**
394 * This is the process holding the activity the user last visited that is in a different process
395 * from the one they are currently in.
396 */
397 WindowProcessController mPreviousProcess;
398 /** The time at which the previous process was last visible. */
399 long mPreviousProcessVisibleTime;
400
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700401 /** List of intents that were used to start the most recent tasks. */
402 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700403 /** State of external calls telling us if the device is awake or asleep. */
404 private boolean mKeyguardShown = false;
405
406 // Wrapper around VoiceInteractionServiceManager
407 private AssistUtils mAssistUtils;
408
409 // VoiceInteraction session ID that changes for each new request except when
410 // being called for multi-window assist in a single session.
411 private int mViSessionId = 1000;
412
413 // How long to wait in getAssistContextExtras for the activity and foreground services
414 // to respond with the result.
415 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
416
417 // How long top wait when going through the modern assist (which doesn't need to block
418 // on getting this result before starting to launch its UI).
419 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
420
421 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
422 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
423
Alison Cichowlas3e340502018-08-07 17:15:01 -0400424 // Permission tokens are used to temporarily granted a trusted app the ability to call
425 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
426 // showing any appropriate error messages to the user.
427 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
428 10 * MINUTE_IN_MILLIS;
429
430 // How long before the service actually expires a token. This is slightly longer than
431 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
432 // expiration exception.
433 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
434 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
435
436 // How long the service will remember expired tokens, for the purpose of providing error
437 // messaging when a client uses an expired token.
438 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
439 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
440
441 // Activity tokens of system activities that are delegating their call to
442 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
443 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
444
445 // Permission tokens that have expired, but we remember for error reporting.
446 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
447
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700448 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
449
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700450 // Keeps track of the active voice interaction service component, notified from
451 // VoiceInteractionManagerService
452 ComponentName mActiveVoiceInteractionServiceComponent;
453
Michal Karpinskida34cd42019-04-02 19:46:52 +0100454 // A map userId and all its companion app uids
455 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000456
Wale Ogunwalee2172292018-10-25 10:11:10 -0700457 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700458 KeyguardController mKeyguardController;
459 private final ClientLifecycleManager mLifecycleManager;
460 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700461 /** The controller for all operations related to locktask. */
462 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700463 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700464
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700465 boolean mSuppressResizeConfigChanges;
466
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700467 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700468 new UpdateConfigurationResult();
469
470 static final class UpdateConfigurationResult {
471 // Configuration changes that were updated.
472 int changes;
473 // If the activity was relaunched to match the new configuration.
474 boolean activityRelaunched;
475
476 void reset() {
477 changes = 0;
478 activityRelaunched = false;
479 }
480 }
481
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700482 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700483 private int mConfigurationSeq;
484 // To cache the list of supported system locales
485 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700486
487 /**
488 * Temp object used when global and/or display override configuration is updated. It is also
489 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
490 * anyone...
491 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492 private Configuration mTempConfig = new Configuration();
493
Wale Ogunwalef6733932018-06-27 05:14:34 -0700494 /** Temporary to avoid allocations. */
495 final StringBuilder mStringBuilder = new StringBuilder(256);
496
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700497 // Amount of time after a call to stopAppSwitches() during which we will
498 // prevent further untrusted switches from happening.
499 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
500
501 /**
502 * The time at which we will allow normal application switches again,
503 * after a call to {@link #stopAppSwitches()}.
504 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700506 /**
507 * This is set to true after the first switch after mAppSwitchesAllowedTime
508 * is set; any switches after that will clear the time.
509 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700510 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511
Ricky Wai906af482019-06-03 17:25:28 +0100512 /**
513 * Last stop app switches time, apps finished before this time cannot start background activity
514 * even if they are in grace period.
515 */
516 private long mLastStopAppSwitchesTime;
517
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700518 IActivityController mController = null;
519 boolean mControllerIsAMonkey = false;
520
Wale Ogunwale214f3482018-10-04 11:00:47 -0700521 final int mFactoryTest;
522
523 /** Used to control how we initialize the service. */
524 ComponentName mTopComponent;
525 String mTopAction = Intent.ACTION_MAIN;
526 String mTopData;
527
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800528 /** Profiling app information. */
529 String mProfileApp = null;
530 WindowProcessController mProfileProc = null;
531 ProfilerInfo mProfilerInfo = null;
532
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700533 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700534 * Dump of the activity state at the time of the last ANR. Cleared after
535 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
536 */
537 String mLastANRState;
538
539 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700540 * Used to retain an update lock when the foreground activity is in
541 * immersive mode.
542 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700543 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700544
545 /**
546 * Packages that are being allowed to perform unrestricted app switches. Mapping is
547 * User -> Type -> uid.
548 */
549 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
550
551 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700552 private int mThumbnailWidth;
553 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700554
555 /**
556 * Flag that indicates if multi-window is enabled.
557 *
558 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
559 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
560 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
561 * At least one of the forms of multi-window must be enabled in order for this flag to be
562 * initialized to 'true'.
563 *
564 * @see #mSupportsSplitScreenMultiWindow
565 * @see #mSupportsFreeformWindowManagement
566 * @see #mSupportsPictureInPicture
567 * @see #mSupportsMultiDisplay
568 */
569 boolean mSupportsMultiWindow;
570 boolean mSupportsSplitScreenMultiWindow;
571 boolean mSupportsFreeformWindowManagement;
572 boolean mSupportsPictureInPicture;
573 boolean mSupportsMultiDisplay;
574 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700575 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700576
577 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
578
579 // VR Vr2d Display Id.
580 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700581
Wale Ogunwalef6733932018-06-27 05:14:34 -0700582 /**
583 * Set while we are wanting to sleep, to prevent any
584 * activities from being started/resumed.
585 *
586 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
587 *
588 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
589 * while in the sleep state until there is a pending transition out of sleep, in which case
590 * mSleeping is set to false, and remains false while awake.
591 *
592 * Whether mSleeping can quickly toggled between true/false without the device actually
593 * display changing states is undefined.
594 */
595 private boolean mSleeping = false;
596
597 /**
598 * The process state used for processes that are running the top activities.
599 * This changes between TOP and TOP_SLEEPING to following mSleeping.
600 */
601 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
602
Riddle Hsua0022cd2019-09-09 21:12:41 +0800603 @Retention(RetentionPolicy.SOURCE)
604 @IntDef({
605 LAYOUT_REASON_CONFIG_CHANGED,
606 LAYOUT_REASON_VISIBILITY_CHANGED,
607 })
608 @interface LayoutReason {}
609 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
610 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
611
612 /** The reasons to perform surface placement. */
613 @LayoutReason
614 private int mLayoutReasons;
615
Wale Ogunwalef6733932018-06-27 05:14:34 -0700616 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
617 // automatically. Important for devices without direct input devices.
618 private boolean mShowDialogs = true;
619
620 /** Set if we are shutting down the system, similar to sleeping. */
621 boolean mShuttingDown = false;
622
623 /**
624 * We want to hold a wake lock while running a voice interaction session, since
625 * this may happen with the screen off and we need to keep the CPU running to
626 * be able to continue to interact with the user.
627 */
628 PowerManager.WakeLock mVoiceWakeLock;
629
630 /**
631 * Set while we are running a voice interaction. This overrides sleeping while it is active.
632 */
633 IVoiceInteractionSession mRunningVoice;
634
635 /**
636 * The last resumed activity. This is identical to the current resumed activity most
637 * of the time but could be different when we're pausing one activity before we resume
638 * another activity.
639 */
640 ActivityRecord mLastResumedActivity;
641
642 /**
643 * The activity that is currently being traced as the active resumed activity.
644 *
645 * @see #updateResumedAppTrace
646 */
647 private @Nullable ActivityRecord mTracedResumedActivity;
648
649 /** If non-null, we are tracking the time the user spends in the currently focused app. */
650 AppTimeTracker mCurAppTimeTracker;
651
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700652 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700653
Wale Ogunwale53783742018-09-16 10:21:51 -0700654 /**
655 * Packages that the user has asked to have run in screen size
656 * compatibility mode instead of filling the screen.
657 */
658 CompatModePackages mCompatModePackages;
659
Wale Ogunwalef6733932018-06-27 05:14:34 -0700660 private FontScaleSettingObserver mFontScaleSettingObserver;
661
Ricky Wai96f5c352019-04-10 18:40:17 +0100662 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000663
Wale Ogunwalef6733932018-06-27 05:14:34 -0700664 private final class FontScaleSettingObserver extends ContentObserver {
665 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
666 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
667
668 public FontScaleSettingObserver() {
669 super(mH);
670 final ContentResolver resolver = mContext.getContentResolver();
671 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
672 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
673 UserHandle.USER_ALL);
674 }
675
676 @Override
677 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
678 if (mFontScaleUri.equals(uri)) {
679 updateFontScaleIfNeeded(userId);
680 } else if (mHideErrorDialogsUri.equals(uri)) {
681 synchronized (mGlobalLock) {
682 updateShouldShowDialogsLocked(getGlobalConfiguration());
683 }
684 }
685 }
686 }
687
Riddle Hsua0536432019-02-16 00:38:59 +0800688 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
689 @Target(ElementType.METHOD)
690 @Retention(RetentionPolicy.SOURCE)
691 @interface HotPath {
692 int NONE = 0;
693 int OOM_ADJUSTMENT = 1;
694 int LRU_UPDATE = 2;
695 int PROCESS_CHANGE = 3;
696 int caller() default NONE;
697 }
698
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800699 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
700 @Override
701 public void run() {
702 mAmInternal.updateOomAdj();
703 }
704 };
705
Charles Chen8d98dd22018-12-26 17:36:54 +0800706 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
707 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700708 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700709 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700710 mSystemThread = ActivityThread.currentActivityThread();
711 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700712 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800713 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700714 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700715 }
716
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700717 public void onSystemReady() {
718 synchronized (mGlobalLock) {
719 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
720 PackageManager.FEATURE_CANT_SAVE_STATE);
721 mAssistUtils = new AssistUtils(mContext);
722 mVrController.onSystemReady();
723 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700724 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700725 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700726 }
727
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700728 public void onInitPowerManagement() {
729 synchronized (mGlobalLock) {
730 mStackSupervisor.initPowerManagement();
731 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
732 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
733 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
734 mVoiceWakeLock.setReferenceCounted(false);
735 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700736 }
737
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700738 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700739 mFontScaleSettingObserver = new FontScaleSettingObserver();
740 }
741
Wale Ogunwale59507092018-10-29 09:00:30 -0700742 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700743 final boolean freeformWindowManagement =
744 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
745 || Settings.Global.getInt(
746 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
747
748 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
749 final boolean supportsPictureInPicture = supportsMultiWindow &&
750 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
751 final boolean supportsSplitScreenMultiWindow =
752 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
753 final boolean supportsMultiDisplay = mContext.getPackageManager()
754 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700755 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
756 final boolean forceResizable = Settings.Global.getInt(
757 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700758 final boolean sizeCompatFreeform = Settings.Global.getInt(
759 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700760
761 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900762 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700763
764 final Configuration configuration = new Configuration();
765 Settings.System.getConfiguration(resolver, configuration);
766 if (forceRtl) {
767 // This will take care of setting the correct layout direction flags
768 configuration.setLayoutDirection(configuration.locale);
769 }
770
771 synchronized (mGlobalLock) {
772 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700773 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700774 final boolean multiWindowFormEnabled = freeformWindowManagement
775 || supportsSplitScreenMultiWindow
776 || supportsPictureInPicture
777 || supportsMultiDisplay;
778 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
779 mSupportsMultiWindow = true;
780 mSupportsFreeformWindowManagement = freeformWindowManagement;
781 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
782 mSupportsPictureInPicture = supportsPictureInPicture;
783 mSupportsMultiDisplay = supportsMultiDisplay;
784 } else {
785 mSupportsMultiWindow = false;
786 mSupportsFreeformWindowManagement = false;
787 mSupportsSplitScreenMultiWindow = false;
788 mSupportsPictureInPicture = false;
789 mSupportsMultiDisplay = false;
790 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700791 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700792 // This happens before any activities are started, so we can change global configuration
793 // in-place.
794 updateConfigurationLocked(configuration, null, true);
795 final Configuration globalConfig = getGlobalConfiguration();
796 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
797
798 // Load resources only after the current configuration has been set.
799 final Resources res = mContext.getResources();
800 mThumbnailWidth = res.getDimensionPixelSize(
801 com.android.internal.R.dimen.thumbnail_width);
802 mThumbnailHeight = res.getDimensionPixelSize(
803 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700804 }
805 }
806
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800807 public WindowManagerGlobalLock getGlobalLock() {
808 return mGlobalLock;
809 }
810
Yunfan Chen585f2932019-01-29 16:04:45 +0900811 /** For test purpose only. */
812 @VisibleForTesting
813 public ActivityTaskManagerInternal getAtmInternal() {
814 return mInternal;
815 }
816
Riddle Hsud93a6c42018-11-29 21:50:06 +0800817 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
818 Looper looper) {
819 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700820 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700821 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700822 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800823 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700824 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700825 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700826
827 mTempConfig.setToDefaults();
828 mTempConfig.setLocales(LocaleList.getDefault());
829 mConfigurationSeq = mTempConfig.seq = 1;
830 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800831 mRootActivityContainer = new RootActivityContainer(this);
832 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700833
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700834 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700835 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700836 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700837 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700838 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700839 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700840 mKeyguardController = mStackSupervisor.getKeyguardController();
841 }
842
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700843 public void onActivityManagerInternalAdded() {
844 synchronized (mGlobalLock) {
845 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
846 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
847 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700848 }
849
Yunfan Chen75157d72018-07-27 14:47:21 +0900850 int increaseConfigurationSeqLocked() {
851 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
852 return mConfigurationSeq;
853 }
854
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700855 protected ActivityStackSupervisor createStackSupervisor() {
856 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
857 supervisor.initialize();
858 return supervisor;
859 }
860
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800861 protected AppWarnings createAppWarnings(
862 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
863 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
864 }
865
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700866 public void setWindowManager(WindowManagerService wm) {
867 synchronized (mGlobalLock) {
868 mWindowManager = wm;
869 mLockTaskController.setWindowManager(wm);
870 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800871 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700872 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700873 }
874
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700875 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
876 synchronized (mGlobalLock) {
877 mUsageStatsInternal = usageStatsManager;
878 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700879 }
880
Wale Ogunwalef6733932018-06-27 05:14:34 -0700881 UserManagerService getUserManager() {
882 if (mUserManager == null) {
883 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
884 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
885 }
886 return mUserManager;
887 }
888
889 AppOpsService getAppOpsService() {
890 if (mAppOpsService == null) {
891 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
892 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
893 }
894 return mAppOpsService;
895 }
896
897 boolean hasUserRestriction(String restriction, int userId) {
898 return getUserManager().hasUserRestriction(restriction, userId);
899 }
900
Michal Karpinski15486842019-04-25 17:33:42 +0100901 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
902 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700903 callingUid, callingPackage, /* featureId */ null);
Michal Karpinski15486842019-04-25 17:33:42 +0100904 if (mode == AppOpsManager.MODE_DEFAULT) {
905 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
906 == PERMISSION_GRANTED;
907 }
908 return mode == AppOpsManager.MODE_ALLOWED;
909 }
910
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700911 @VisibleForTesting
912 protected void setRecentTasks(RecentTasks recentTasks) {
913 mRecentTasks = recentTasks;
914 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700915 }
916
917 RecentTasks getRecentTasks() {
918 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700919 }
920
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700921 ClientLifecycleManager getLifecycleManager() {
922 return mLifecycleManager;
923 }
924
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700925 ActivityStartController getActivityStartController() {
926 return mActivityStartController;
927 }
928
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700929 TaskChangeNotificationController getTaskChangeNotificationController() {
930 return mTaskChangeNotificationController;
931 }
932
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700933 LockTaskController getLockTaskController() {
934 return mLockTaskController;
935 }
936
Yunfan Chen75157d72018-07-27 14:47:21 +0900937 /**
938 * Return the global configuration used by the process corresponding to the input pid. This is
939 * usually the global configuration with some overrides specific to that process.
940 */
941 Configuration getGlobalConfigurationForCallingPid() {
942 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800943 return getGlobalConfigurationForPid(pid);
944 }
945
946 /**
947 * Return the global configuration used by the process corresponding to the given pid.
948 */
949 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900950 if (pid == MY_PID || pid < 0) {
951 return getGlobalConfiguration();
952 }
953 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100954 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900955 return app != null ? app.getConfiguration() : getGlobalConfiguration();
956 }
957 }
958
959 /**
960 * Return the device configuration info used by the process corresponding to the input pid.
961 * The value is consistent with the global configuration for the process.
962 */
963 @Override
964 public ConfigurationInfo getDeviceConfigurationInfo() {
965 ConfigurationInfo config = new ConfigurationInfo();
966 synchronized (mGlobalLock) {
967 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
968 config.reqTouchScreen = globalConfig.touchscreen;
969 config.reqKeyboardType = globalConfig.keyboard;
970 config.reqNavigation = globalConfig.navigation;
971 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
972 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
973 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
974 }
975 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
976 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
977 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
978 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700979 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900980 }
981 return config;
982 }
983
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700984 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700985 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700986 }
987
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700988 public static final class Lifecycle extends SystemService {
989 private final ActivityTaskManagerService mService;
990
991 public Lifecycle(Context context) {
992 super(context);
993 mService = new ActivityTaskManagerService(context);
994 }
995
996 @Override
997 public void onStart() {
998 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700999 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001000 }
1001
Garfield Tan891146c2018-10-09 12:14:00 -07001002 @Override
1003 public void onUnlockUser(int userId) {
1004 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001005 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001006 }
1007 }
1008
1009 @Override
1010 public void onCleanupUser(int userId) {
1011 synchronized (mService.getGlobalLock()) {
1012 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1013 }
1014 }
1015
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001016 public ActivityTaskManagerService getService() {
1017 return mService;
1018 }
1019 }
1020
1021 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022 public final int startActivity(IApplicationThread caller, String callingPackage,
1023 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1024 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1025 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1026 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1027 UserHandle.getCallingUserId());
1028 }
1029
1030 @Override
1031 public final int startActivities(IApplicationThread caller, String callingPackage,
1032 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1033 int userId) {
1034 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001035 enforceNotIsolatedCaller(reason);
1036 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001037 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001038 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1039 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1040 reason, null /* originatingPendingIntent */,
1041 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001042 }
1043
1044 @Override
1045 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1046 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1047 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1048 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1049 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1050 true /*validateIncomingUser*/);
1051 }
1052
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001053 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001054 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1055 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1056 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001057 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001058
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001059 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1061
1062 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001063 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001064 .setCaller(caller)
1065 .setCallingPackage(callingPackage)
1066 .setResolvedType(resolvedType)
1067 .setResultTo(resultTo)
1068 .setResultWho(resultWho)
1069 .setRequestCode(requestCode)
1070 .setStartFlags(startFlags)
1071 .setProfilerInfo(profilerInfo)
1072 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001073 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001074 .execute();
1075
1076 }
1077
1078 @Override
1079 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1080 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001081 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1082 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001083 // Refuse possible leaked file descriptors
1084 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1085 throw new IllegalArgumentException("File descriptors passed in Intent");
1086 }
1087
1088 if (!(target instanceof PendingIntentRecord)) {
1089 throw new IllegalArgumentException("Bad PendingIntent object");
1090 }
1091
1092 PendingIntentRecord pir = (PendingIntentRecord)target;
1093
1094 synchronized (mGlobalLock) {
1095 // If this is coming from the currently resumed activity, it is
1096 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001097 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001098 if (stack.mResumedActivity != null &&
1099 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001100 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001101 }
1102 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001103 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001104 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001105 }
1106
1107 @Override
1108 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1109 Bundle bOptions) {
1110 // Refuse possible leaked file descriptors
1111 if (intent != null && intent.hasFileDescriptors()) {
1112 throw new IllegalArgumentException("File descriptors passed in Intent");
1113 }
1114 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1115
1116 synchronized (mGlobalLock) {
1117 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1118 if (r == null) {
1119 SafeActivityOptions.abort(options);
1120 return false;
1121 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001122 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001123 // The caller is not running... d'oh!
1124 SafeActivityOptions.abort(options);
1125 return false;
1126 }
1127 intent = new Intent(intent);
1128 // The caller is not allowed to change the data.
1129 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1130 // And we are resetting to find the next component...
1131 intent.setComponent(null);
1132
1133 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1134
1135 ActivityInfo aInfo = null;
1136 try {
1137 List<ResolveInfo> resolves =
1138 AppGlobals.getPackageManager().queryIntentActivities(
1139 intent, r.resolvedType,
1140 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1141 UserHandle.getCallingUserId()).getList();
1142
1143 // Look for the original activity in the list...
1144 final int N = resolves != null ? resolves.size() : 0;
1145 for (int i=0; i<N; i++) {
1146 ResolveInfo rInfo = resolves.get(i);
1147 if (rInfo.activityInfo.packageName.equals(r.packageName)
1148 && rInfo.activityInfo.name.equals(r.info.name)) {
1149 // We found the current one... the next matching is
1150 // after it.
1151 i++;
1152 if (i<N) {
1153 aInfo = resolves.get(i).activityInfo;
1154 }
1155 if (debug) {
1156 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1157 + "/" + r.info.name);
1158 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1159 ? "null" : aInfo.packageName + "/" + aInfo.name));
1160 }
1161 break;
1162 }
1163 }
1164 } catch (RemoteException e) {
1165 }
1166
1167 if (aInfo == null) {
1168 // Nobody who is next!
1169 SafeActivityOptions.abort(options);
1170 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1171 return false;
1172 }
1173
1174 intent.setComponent(new ComponentName(
1175 aInfo.applicationInfo.packageName, aInfo.name));
1176 intent.setFlags(intent.getFlags()&~(
1177 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1178 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1179 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1180 FLAG_ACTIVITY_NEW_TASK));
1181
1182 // Okay now we need to start the new activity, replacing the currently running activity.
1183 // This is a little tricky because we want to start the new one as if the current one is
1184 // finished, but not finish the current one first so that there is no flicker.
1185 // And thus...
1186 final boolean wasFinishing = r.finishing;
1187 r.finishing = true;
1188
1189 // Propagate reply information over to the new activity.
1190 final ActivityRecord resultTo = r.resultTo;
1191 final String resultWho = r.resultWho;
1192 final int requestCode = r.requestCode;
1193 r.resultTo = null;
1194 if (resultTo != null) {
1195 resultTo.removeResultsLocked(r, resultWho, requestCode);
1196 }
1197
1198 final long origId = Binder.clearCallingIdentity();
1199 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001200 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001201 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001202 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001203 .setResolvedType(r.resolvedType)
1204 .setActivityInfo(aInfo)
1205 .setResultTo(resultTo != null ? resultTo.appToken : null)
1206 .setResultWho(resultWho)
1207 .setRequestCode(requestCode)
1208 .setCallingPid(-1)
1209 .setCallingUid(r.launchedFromUid)
1210 .setCallingPackage(r.launchedFromPackage)
1211 .setRealCallingPid(-1)
1212 .setRealCallingUid(r.launchedFromUid)
1213 .setActivityOptions(options)
1214 .execute();
1215 Binder.restoreCallingIdentity(origId);
1216
1217 r.finishing = wasFinishing;
1218 if (res != ActivityManager.START_SUCCESS) {
1219 return false;
1220 }
1221 return true;
1222 }
1223 }
1224
1225 @Override
1226 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1227 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1228 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1229 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001230 enforceNotIsolatedCaller("startActivityAndWait");
1231 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1232 userId, "startActivityAndWait");
1233 // TODO: Switch to user app stacks here.
1234 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1235 .setCaller(caller)
1236 .setCallingPackage(callingPackage)
1237 .setResolvedType(resolvedType)
1238 .setResultTo(resultTo)
1239 .setResultWho(resultWho)
1240 .setRequestCode(requestCode)
1241 .setStartFlags(startFlags)
1242 .setActivityOptions(bOptions)
1243 .setUserId(userId)
1244 .setProfilerInfo(profilerInfo)
1245 .setWaitResult(res)
1246 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001247 return res;
1248 }
1249
1250 @Override
1251 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1252 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1253 int startFlags, Configuration config, Bundle bOptions, int userId) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001254 enforceNotIsolatedCaller("startActivityWithConfig");
1255 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1256 "startActivityWithConfig");
1257 // TODO: Switch to user app stacks here.
1258 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1259 .setCaller(caller)
1260 .setCallingPackage(callingPackage)
1261 .setResolvedType(resolvedType)
1262 .setResultTo(resultTo)
1263 .setResultWho(resultWho)
1264 .setRequestCode(requestCode)
1265 .setStartFlags(startFlags)
1266 .setGlobalConfiguration(config)
1267 .setActivityOptions(bOptions)
1268 .setUserId(userId)
1269 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001270 }
1271
Alison Cichowlas3e340502018-08-07 17:15:01 -04001272
1273 @Override
1274 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1275 int callingUid = Binder.getCallingUid();
1276 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1277 throw new SecurityException("Only the system process can request a permission token, "
1278 + "received request from uid: " + callingUid);
1279 }
1280 IBinder permissionToken = new Binder();
1281 synchronized (mGlobalLock) {
1282 mStartActivitySources.put(permissionToken, delegatorToken);
1283 }
1284
1285 Message expireMsg = PooledLambda.obtainMessage(
1286 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1287 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1288
1289 Message forgetMsg = PooledLambda.obtainMessage(
1290 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1291 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1292
1293 return permissionToken;
1294 }
1295
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001296 @Override
1297 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1298 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001299 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1300 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001301 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001302 // permission grants) as any app that may launch one of your own activities. So we only
1303 // allow this in two cases:
1304 // 1) The caller is an activity that is part of the core framework, and then only when it
1305 // is running as the system.
1306 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1307 // can only be requested by a system activity, which may then delegate this call to
1308 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001309 final ActivityRecord sourceRecord;
1310 final int targetUid;
1311 final String targetPackage;
1312 final boolean isResolver;
1313 synchronized (mGlobalLock) {
1314 if (resultTo == null) {
1315 throw new SecurityException("Must be called from an activity");
1316 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001317 final IBinder sourceToken;
1318 if (permissionToken != null) {
1319 // To even attempt to use a permissionToken, an app must also have this signature
1320 // permission.
1321 mAmInternal.enforceCallingPermission(
1322 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1323 "startActivityAsCaller");
1324 // If called with a permissionToken, we want the sourceRecord from the delegator
1325 // activity that requested this token.
1326 sourceToken = mStartActivitySources.remove(permissionToken);
1327 if (sourceToken == null) {
1328 // Invalid permissionToken, check if it recently expired.
1329 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1330 throw new SecurityException("Called with expired permission token: "
1331 + permissionToken);
1332 } else {
1333 throw new SecurityException("Called with invalid permission token: "
1334 + permissionToken);
1335 }
1336 }
1337 } else {
1338 // This method was called directly by the source.
1339 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001340 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001341
Wale Ogunwaled32da472018-11-16 07:19:28 -08001342 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001343 if (sourceRecord == null) {
1344 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001345 }
1346 if (sourceRecord.app == null) {
1347 throw new SecurityException("Called without a process attached to activity");
1348 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001349
1350 // Whether called directly or from a delegate, the source activity must be from the
1351 // android package.
1352 if (!sourceRecord.info.packageName.equals("android")) {
1353 throw new SecurityException("Must be called from an activity that is "
1354 + "declared in the android package");
1355 }
1356
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001357 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001358 // This is still okay, as long as this activity is running under the
1359 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001360 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001361 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001362 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001363 + " must be system uid or original calling uid "
1364 + sourceRecord.launchedFromUid);
1365 }
1366 }
1367 if (ignoreTargetSecurity) {
1368 if (intent.getComponent() == null) {
1369 throw new SecurityException(
1370 "Component must be specified with ignoreTargetSecurity");
1371 }
1372 if (intent.getSelector() != null) {
1373 throw new SecurityException(
1374 "Selector not allowed with ignoreTargetSecurity");
1375 }
1376 }
1377 targetUid = sourceRecord.launchedFromUid;
1378 targetPackage = sourceRecord.launchedFromPackage;
1379 isResolver = sourceRecord.isResolverOrChildActivity();
1380 }
1381
1382 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001383 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001384 }
1385
1386 // TODO: Switch to user app stacks here.
1387 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001388 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001389 .setCallingUid(targetUid)
1390 .setCallingPackage(targetPackage)
1391 .setResolvedType(resolvedType)
1392 .setResultTo(resultTo)
1393 .setResultWho(resultWho)
1394 .setRequestCode(requestCode)
1395 .setStartFlags(startFlags)
1396 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001397 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001398 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1399 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001400 // The target may well be in the background, which would normally prevent it
1401 // from starting an activity. Here we definitely want the start to succeed.
1402 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001403 .execute();
1404 } catch (SecurityException e) {
1405 // XXX need to figure out how to propagate to original app.
1406 // A SecurityException here is generally actually a fault of the original
1407 // calling activity (such as a fairly granting permissions), so propagate it
1408 // back to them.
1409 /*
1410 StringBuilder msg = new StringBuilder();
1411 msg.append("While launching");
1412 msg.append(intent.toString());
1413 msg.append(": ");
1414 msg.append(e.getMessage());
1415 */
1416 throw e;
1417 }
1418 }
1419
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001420 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1421 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1422 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1423 }
1424
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001425 @Override
1426 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1427 Intent intent, String resolvedType, IVoiceInteractionSession session,
1428 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1429 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001430 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001431 if (session == null || interactor == null) {
1432 throw new NullPointerException("null session or interactor");
1433 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001434 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001435 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001436 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001437 .setCallingUid(callingUid)
1438 .setCallingPackage(callingPackage)
1439 .setResolvedType(resolvedType)
1440 .setVoiceSession(session)
1441 .setVoiceInteractor(interactor)
1442 .setStartFlags(startFlags)
1443 .setProfilerInfo(profilerInfo)
1444 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001445 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001446 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001447 .execute();
1448 }
1449
1450 @Override
1451 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1452 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001453 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1454 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001456 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001457 .setCallingUid(callingUid)
1458 .setCallingPackage(callingPackage)
1459 .setResolvedType(resolvedType)
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
Riddle Hsu609a8e22019-06-27 16:46:29 -06001466 /**
1467 * Start the recents activity to perform the recents animation.
1468 *
1469 * @param intent The intent to start the recents activity.
1470 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1471 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001472 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001473 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1474 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001475 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001476 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001477 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001478 final long origId = Binder.clearCallingIdentity();
1479 try {
1480 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001481 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1482 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001483 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001484
1485 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001486 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001487 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001488 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001489 if (recentsAnimationRunner == null) {
1490 anim.preloadRecentsActivity();
1491 } else {
1492 anim.startRecentsActivity(recentsAnimationRunner);
1493 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001494 }
1495 } finally {
1496 Binder.restoreCallingIdentity(origId);
1497 }
1498 }
1499
1500 @Override
1501 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001502 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001503 "startActivityFromRecents()");
1504
1505 final int callingPid = Binder.getCallingPid();
1506 final int callingUid = Binder.getCallingUid();
1507 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1508 final long origId = Binder.clearCallingIdentity();
1509 try {
1510 synchronized (mGlobalLock) {
1511 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1512 safeOptions);
1513 }
1514 } finally {
1515 Binder.restoreCallingIdentity(origId);
1516 }
1517 }
1518
1519 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001520 * Public API to check if the client is allowed to start an activity on specified display.
1521 *
1522 * If the target display is private or virtual, some restrictions will apply.
1523 *
1524 * @param displayId Target display id.
1525 * @param intent Intent used to launch the activity.
1526 * @param resolvedType The MIME type of the intent.
1527 * @param userId The id of the user for whom the call is made.
1528 * @return {@code true} if a call to start an activity on the target display should succeed and
1529 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1530 */
1531 @Override
1532 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1533 String resolvedType, int userId) {
1534 final int callingUid = Binder.getCallingUid();
1535 final int callingPid = Binder.getCallingPid();
1536 final long origId = Binder.clearCallingIdentity();
1537
1538 try {
1539 // Collect information about the target of the Intent.
1540 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1541 0 /* startFlags */, null /* profilerInfo */, userId,
1542 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1543 UserHandle.USER_NULL));
1544 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1545
1546 synchronized (mGlobalLock) {
1547 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1548 aInfo);
1549 }
1550 } finally {
1551 Binder.restoreCallingIdentity(origId);
1552 }
1553 }
1554
1555 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001556 * This is the internal entry point for handling Activity.finish().
1557 *
1558 * @param token The Binder token referencing the Activity we want to finish.
1559 * @param resultCode Result code, if any, from this Activity.
1560 * @param resultData Result data (Intent), if any, from this Activity.
1561 * @param finishTask Whether to finish the task associated with this Activity.
1562 *
1563 * @return Returns true if the activity successfully finished, or false if it is still running.
1564 */
1565 @Override
1566 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1567 int finishTask) {
1568 // Refuse possible leaked file descriptors
1569 if (resultData != null && resultData.hasFileDescriptors()) {
1570 throw new IllegalArgumentException("File descriptors passed in Intent");
1571 }
1572
1573 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001574 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001575 if (r == null) {
1576 return true;
1577 }
1578 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001579 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001580 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001581 if (rootR == null) {
1582 Slog.w(TAG, "Finishing task with all activities already finished");
1583 }
1584 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1585 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001586 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001587 return false;
1588 }
1589
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001590 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1591 // We should consolidate.
1592 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001593 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001594 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001595 if (next != null) {
1596 // ask watcher if this is allowed
1597 boolean resumeOK = true;
1598 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001599 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001600 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001601 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001602 Watchdog.getInstance().setActivityController(null);
1603 }
1604
1605 if (!resumeOK) {
1606 Slog.i(TAG, "Not finishing activity because controller resumed");
1607 return false;
1608 }
1609 }
1610 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001611
1612 // note down that the process has finished an activity and is in background activity
1613 // starts grace period
1614 if (r.app != null) {
1615 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1616 }
1617
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001618 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001619 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001620 try {
1621 boolean res;
1622 final boolean finishWithRootActivity =
1623 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1624 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1625 || (finishWithRootActivity && r == rootR)) {
1626 // If requested, remove the task that is associated to this activity only if it
1627 // was the root activity in the task. The result code and data is ignored
1628 // because we don't support returning them across task boundaries. Also, to
1629 // keep backwards compatibility we remove the task from recents when finishing
1630 // task with root activity.
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001631 res = mStackSupervisor.removeTaskByIdLocked(tr.mTaskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001632 finishWithRootActivity, "finish-activity");
1633 if (!res) {
1634 Slog.i(TAG, "Removing task failed to finish activity");
1635 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001636 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001637 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001638 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001639 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001640 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001641 if (!res) {
1642 Slog.i(TAG, "Failed to finish by app-request");
1643 }
1644 }
1645 return res;
1646 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001647 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001648 Binder.restoreCallingIdentity(origId);
1649 }
1650 }
1651 }
1652
1653 @Override
1654 public boolean finishActivityAffinity(IBinder token) {
1655 synchronized (mGlobalLock) {
1656 final long origId = Binder.clearCallingIdentity();
1657 try {
1658 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1659 if (r == null) {
1660 return false;
1661 }
1662
1663 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1664 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001665 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001666 return false;
1667 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001668
1669 final PooledFunction p = PooledLambda.obtainFunction(
1670 ActivityRecord::finishIfSameAffinity, r,
1671 PooledLambda.__(ActivityRecord.class));
1672 r.getTask().forAllActivities(
1673 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1674 p.recycle();
1675
Andrii Kuliande93eff2019-07-12 12:21:27 -07001676 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001677 } finally {
1678 Binder.restoreCallingIdentity(origId);
1679 }
1680 }
1681 }
1682
1683 @Override
1684 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1685 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001686 try {
1687 WindowProcessController proc = null;
1688 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001689 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001690 ActivityStack stack = ActivityRecord.getStackLocked(token);
1691 if (stack == null) {
1692 return;
1693 }
1694 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1695 false /* fromTimeout */, false /* processPausingActivities */, config);
1696 if (r != null) {
1697 proc = r.app;
1698 }
1699 if (stopProfiling && proc != null) {
1700 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001701 }
1702 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001703 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001704 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001705 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001706 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001707 }
1708
1709 @Override
1710 public final void activityResumed(IBinder token) {
1711 final long origId = Binder.clearCallingIdentity();
1712 synchronized (mGlobalLock) {
1713 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001714 }
1715 Binder.restoreCallingIdentity(origId);
1716 }
1717
1718 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001719 public final void activityTopResumedStateLost() {
1720 final long origId = Binder.clearCallingIdentity();
1721 synchronized (mGlobalLock) {
1722 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1723 }
1724 Binder.restoreCallingIdentity(origId);
1725 }
1726
1727 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001728 public final void activityPaused(IBinder token) {
1729 final long origId = Binder.clearCallingIdentity();
1730 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001731 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001732 ActivityStack stack = ActivityRecord.getStackLocked(token);
1733 if (stack != null) {
1734 stack.activityPausedLocked(token, false);
1735 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001736 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001737 }
1738 Binder.restoreCallingIdentity(origId);
1739 }
1740
1741 @Override
1742 public final void activityStopped(IBinder token, Bundle icicle,
1743 PersistableBundle persistentState, CharSequence description) {
1744 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1745
1746 // Refuse possible leaked file descriptors
1747 if (icicle != null && icicle.hasFileDescriptors()) {
1748 throw new IllegalArgumentException("File descriptors passed in Bundle");
1749 }
1750
1751 final long origId = Binder.clearCallingIdentity();
1752
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001753 String restartingName = null;
1754 int restartingUid = 0;
1755 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001757 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001758 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001759 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001760 if (r.attachedToProcess()
1761 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1762 // The activity was requested to restart from
1763 // {@link #restartActivityProcessIfVisible}.
1764 restartingName = r.app.mName;
1765 restartingUid = r.app.mUid;
1766 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001767 r.activityStoppedLocked(icicle, persistentState, description);
1768 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001769 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001770 }
1771
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001772 if (restartingName != null) {
1773 // In order to let the foreground activity can be restarted with its saved state from
1774 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1775 // until the activity reports stopped with the state. And the activity record will be
1776 // kept because the record state is restarting, then the activity will be restarted
1777 // immediately if it is still the top one.
1778 mStackSupervisor.removeRestartTimeouts(r);
1779 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1780 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001781 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001782
1783 Binder.restoreCallingIdentity(origId);
1784 }
1785
1786 @Override
1787 public final void activityDestroyed(IBinder token) {
1788 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1789 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001790 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001791 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001792 try {
1793 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1794 if (activity != null) {
1795 activity.destroyed("activityDestroyed");
1796 }
1797 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001798 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001799 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 }
1801 }
1802 }
1803
1804 @Override
1805 public final void activityRelaunched(IBinder token) {
1806 final long origId = Binder.clearCallingIdentity();
1807 synchronized (mGlobalLock) {
1808 mStackSupervisor.activityRelaunchedLocked(token);
1809 }
1810 Binder.restoreCallingIdentity(origId);
1811 }
1812
1813 public final void activitySlept(IBinder token) {
1814 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1815
1816 final long origId = Binder.clearCallingIdentity();
1817
1818 synchronized (mGlobalLock) {
1819 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1820 if (r != null) {
1821 mStackSupervisor.activitySleptLocked(r);
1822 }
1823 }
1824
1825 Binder.restoreCallingIdentity(origId);
1826 }
1827
1828 @Override
1829 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1830 synchronized (mGlobalLock) {
1831 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1832 if (r == null) {
1833 return;
1834 }
1835 final long origId = Binder.clearCallingIdentity();
1836 try {
1837 r.setRequestedOrientation(requestedOrientation);
1838 } finally {
1839 Binder.restoreCallingIdentity(origId);
1840 }
1841 }
1842 }
1843
1844 @Override
1845 public int getRequestedOrientation(IBinder token) {
1846 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001847 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1848 return (r != null)
1849 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001850 }
1851 }
1852
1853 @Override
1854 public void setImmersive(IBinder token, boolean immersive) {
1855 synchronized (mGlobalLock) {
1856 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1857 if (r == null) {
1858 throw new IllegalArgumentException();
1859 }
1860 r.immersive = immersive;
1861
1862 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001863 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001864 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001865 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001866 }
1867 }
1868 }
1869
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001870 void applyUpdateLockStateLocked(ActivityRecord r) {
1871 // Modifications to the UpdateLock state are done on our handler, outside
1872 // the activity manager's locks. The new state is determined based on the
1873 // state *now* of the relevant activity record. The object is passed to
1874 // the handler solely for logging detail, not to be consulted/modified.
1875 final boolean nextState = r != null && r.immersive;
1876 mH.post(() -> {
1877 if (mUpdateLock.isHeld() != nextState) {
1878 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1879 "Applying new update lock state '" + nextState + "' for " + r);
1880 if (nextState) {
1881 mUpdateLock.acquire();
1882 } else {
1883 mUpdateLock.release();
1884 }
1885 }
1886 });
1887 }
1888
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001889 @Override
1890 public boolean isImmersive(IBinder token) {
1891 synchronized (mGlobalLock) {
1892 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1893 if (r == null) {
1894 throw new IllegalArgumentException();
1895 }
1896 return r.immersive;
1897 }
1898 }
1899
1900 @Override
1901 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001902 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001903 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001904 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001905 return (r != null) ? r.immersive : false;
1906 }
1907 }
1908
1909 @Override
1910 public void overridePendingTransition(IBinder token, String packageName,
1911 int enterAnim, int exitAnim) {
1912 synchronized (mGlobalLock) {
1913 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1914 if (self == null) {
1915 return;
1916 }
1917
1918 final long origId = Binder.clearCallingIdentity();
1919
1920 if (self.isState(
1921 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001922 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001923 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001924 }
1925
1926 Binder.restoreCallingIdentity(origId);
1927 }
1928 }
1929
1930 @Override
1931 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001932 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001933 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001934 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001935 if (r == null) {
1936 return ActivityManager.COMPAT_MODE_UNKNOWN;
1937 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001938 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001939 }
1940 }
1941
1942 @Override
1943 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001944 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001946 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001947 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001948 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001949 if (r == null) {
1950 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1951 return;
1952 }
1953 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001954 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001955 }
1956 }
1957
1958 @Override
1959 public int getLaunchedFromUid(IBinder activityToken) {
1960 ActivityRecord srec;
1961 synchronized (mGlobalLock) {
1962 srec = ActivityRecord.forTokenLocked(activityToken);
1963 }
1964 if (srec == null) {
1965 return -1;
1966 }
1967 return srec.launchedFromUid;
1968 }
1969
1970 @Override
1971 public String getLaunchedFromPackage(IBinder activityToken) {
1972 ActivityRecord srec;
1973 synchronized (mGlobalLock) {
1974 srec = ActivityRecord.forTokenLocked(activityToken);
1975 }
1976 if (srec == null) {
1977 return null;
1978 }
1979 return srec.launchedFromPackage;
1980 }
1981
1982 @Override
1983 public boolean convertFromTranslucent(IBinder token) {
1984 final long origId = Binder.clearCallingIdentity();
1985 try {
1986 synchronized (mGlobalLock) {
1987 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1988 if (r == null) {
1989 return false;
1990 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001991 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001992 }
1993 } finally {
1994 Binder.restoreCallingIdentity(origId);
1995 }
1996 }
1997
1998 @Override
1999 public boolean convertToTranslucent(IBinder token, Bundle options) {
2000 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2001 final long origId = Binder.clearCallingIdentity();
2002 try {
2003 synchronized (mGlobalLock) {
2004 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2005 if (r == null) {
2006 return false;
2007 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002008 final ActivityRecord under = r.getTask().getActivityBelow(r);
2009 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002010 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2011 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002012 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002013 }
2014 } finally {
2015 Binder.restoreCallingIdentity(origId);
2016 }
2017 }
2018
2019 @Override
2020 public void notifyActivityDrawn(IBinder token) {
2021 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2022 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002023 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002024 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002025 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002026 }
2027 }
2028 }
2029
2030 @Override
2031 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2032 synchronized (mGlobalLock) {
2033 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2034 if (r == null) {
2035 return;
2036 }
2037 r.reportFullyDrawnLocked(restoredFromBundle);
2038 }
2039 }
2040
2041 @Override
2042 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2043 synchronized (mGlobalLock) {
2044 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2045 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2046 return stack.mDisplayId;
2047 }
2048 return DEFAULT_DISPLAY;
2049 }
2050 }
2051
2052 @Override
2053 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002054 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002055 long ident = Binder.clearCallingIdentity();
2056 try {
2057 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002058 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002059 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002060 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002061 }
2062 return null;
2063 }
2064 } finally {
2065 Binder.restoreCallingIdentity(ident);
2066 }
2067 }
2068
2069 @Override
2070 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002071 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002072 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2073 final long callingId = Binder.clearCallingIdentity();
2074 try {
2075 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002076 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002077 if (stack == null) {
2078 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2079 return;
2080 }
2081 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002082 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002083 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002084 }
2085 }
2086 } finally {
2087 Binder.restoreCallingIdentity(callingId);
2088 }
2089 }
2090
2091 @Override
2092 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002093 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002094 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2095 final long callingId = Binder.clearCallingIdentity();
2096 try {
2097 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002098 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002099 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002100 if (task == null) {
2101 return;
2102 }
2103 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002104 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002105 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002106 }
2107 }
2108 } finally {
2109 Binder.restoreCallingIdentity(callingId);
2110 }
2111 }
2112
2113 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002114 public void restartActivityProcessIfVisible(IBinder activityToken) {
2115 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2116 final long callingId = Binder.clearCallingIdentity();
2117 try {
2118 synchronized (mGlobalLock) {
2119 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2120 if (r == null) {
2121 return;
2122 }
2123 r.restartProcessIfVisible();
2124 }
2125 } finally {
2126 Binder.restoreCallingIdentity(callingId);
2127 }
2128 }
2129
2130 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002131 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002132 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002133 synchronized (mGlobalLock) {
2134 final long ident = Binder.clearCallingIdentity();
2135 try {
2136 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2137 "remove-task");
2138 } finally {
2139 Binder.restoreCallingIdentity(ident);
2140 }
2141 }
2142 }
2143
2144 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002145 public void removeAllVisibleRecentTasks() {
2146 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2147 synchronized (mGlobalLock) {
2148 final long ident = Binder.clearCallingIdentity();
2149 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002150 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002151 } finally {
2152 Binder.restoreCallingIdentity(ident);
2153 }
2154 }
2155 }
2156
2157 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002158 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2159 synchronized (mGlobalLock) {
2160 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2161 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002162 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002163 }
2164 }
2165 return false;
2166 }
2167
2168 @Override
2169 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2170 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002171
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002172 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002173 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2174 if (r != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002175 return r.getActivityStack().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002176 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002177 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002178 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002179 }
2180 }
2181
2182 /**
2183 * Attempts to move a task backwards in z-order (the order of activities within the task is
2184 * unchanged).
2185 *
2186 * There are several possible results of this call:
2187 * - if the task is locked, then we will show the lock toast
2188 * - if there is a task behind the provided task, then that task is made visible and resumed as
2189 * this task is moved to the back
2190 * - otherwise, if there are no other tasks in the stack:
2191 * - if this task is in the pinned stack, then we remove the stack completely, which will
2192 * have the effect of moving the task to the top or bottom of the fullscreen stack
2193 * (depending on whether it is visible)
2194 * - otherwise, we simply return home and hide this task
2195 *
2196 * @param token A reference to the activity we wish to move
2197 * @param nonRoot If false then this only works if the activity is the root
2198 * of a task; if true it will work for any activity in a task.
2199 * @return Returns true if the move completed, false if not.
2200 */
2201 @Override
2202 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002203 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002204 synchronized (mGlobalLock) {
2205 final long origId = Binder.clearCallingIdentity();
2206 try {
2207 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Changcdec0802019-11-11 11:45:07 +08002208 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002209 if (task != null) {
2210 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2211 }
2212 } finally {
2213 Binder.restoreCallingIdentity(origId);
2214 }
2215 }
2216 return false;
2217 }
2218
2219 @Override
2220 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002221 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002222 long ident = Binder.clearCallingIdentity();
2223 Rect rect = new Rect();
2224 try {
2225 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002226 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2228 if (task == null) {
2229 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2230 return rect;
2231 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002232 if (task.getParent() != null) {
2233 rect.set(task.getBounds());
2234 } else if (task.mLastNonFullscreenBounds != null) {
2235 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002236 }
2237 }
2238 } finally {
2239 Binder.restoreCallingIdentity(ident);
2240 }
2241 return rect;
2242 }
2243
2244 @Override
2245 public ActivityManager.TaskDescription getTaskDescription(int id) {
2246 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002247 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002248 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Changcdec0802019-11-11 11:45:07 +08002249 final Task tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002250 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2251 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002252 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002253 }
2254 }
2255 return null;
2256 }
2257
2258 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002259 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2260 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2261 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2262 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2263 return;
2264 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002265 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002266 synchronized (mGlobalLock) {
2267 final long ident = Binder.clearCallingIdentity();
2268 try {
Louis Changcdec0802019-11-11 11:45:07 +08002269 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002270 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002271 if (task == null) {
2272 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2273 return;
2274 }
2275
2276 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2277 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2278
2279 if (!task.isActivityTypeStandardOrUndefined()) {
2280 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2281 + " non-standard task " + taskId + " to windowing mode="
2282 + windowingMode);
2283 }
2284
2285 final ActivityStack stack = task.getStack();
2286 if (toTop) {
2287 stack.moveToFront("setTaskWindowingMode", task);
2288 }
2289 stack.setWindowingMode(windowingMode);
2290 } finally {
2291 Binder.restoreCallingIdentity(ident);
2292 }
2293 }
2294 }
2295
2296 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002297 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002298 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002299 ActivityRecord r = getCallingRecordLocked(token);
2300 return r != null ? r.info.packageName : null;
2301 }
2302 }
2303
2304 @Override
2305 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002306 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002307 ActivityRecord r = getCallingRecordLocked(token);
2308 return r != null ? r.intent.getComponent() : null;
2309 }
2310 }
2311
2312 private ActivityRecord getCallingRecordLocked(IBinder token) {
2313 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2314 if (r == null) {
2315 return null;
2316 }
2317 return r.resultTo;
2318 }
2319
2320 @Override
2321 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002322 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002323
2324 synchronized (mGlobalLock) {
2325 final long origId = Binder.clearCallingIdentity();
2326 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002327 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002328 } finally {
2329 Binder.restoreCallingIdentity(origId);
2330 }
2331 }
2332 }
2333
Mark Renouf446251d2019-04-26 10:22:41 -04002334 @Override
2335 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2336 synchronized (mGlobalLock) {
2337 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2338 if (r == null) {
2339 return;
2340 }
2341 ActivityStack stack = r.getActivityStack();
2342 if (stack != null && stack.isSingleTaskInstance()) {
2343 // Single-task stacks are used for activities which are presented in floating
2344 // windows above full screen activities. Instead of directly finishing the
2345 // task, a task change listener is used to notify SystemUI so the action can be
2346 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002347 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002348 mTaskChangeNotificationController
2349 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2350 } else {
2351 try {
2352 callback.requestFinish();
2353 } catch (RemoteException e) {
2354 Slog.e(TAG, "Failed to invoke request finish callback", e);
2355 }
2356 }
2357 }
2358 }
2359
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002360 /**
2361 * TODO: Add mController hook
2362 */
2363 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002364 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2365 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002366 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002367
2368 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2369 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002370 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2371 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002372 }
2373 }
2374
Ricky Waiaca8a772019-04-04 16:01:06 +01002375 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2376 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002377 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002378
Ricky Waiaca8a772019-04-04 16:01:06 +01002379 final int callingPid = Binder.getCallingPid();
2380 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002381 if (!isSameApp(callingUid, callingPackage)) {
2382 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2383 + Binder.getCallingPid() + " as package " + callingPackage;
2384 Slog.w(TAG, msg);
2385 throw new SecurityException(msg);
2386 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002387 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002388 SafeActivityOptions.abort(options);
2389 return;
2390 }
2391 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002392 WindowProcessController callerApp = null;
2393 if (appThread != null) {
2394 callerApp = getProcessController(appThread);
2395 }
2396 final ActivityStarter starter = getActivityStartController().obtainStarter(
2397 null /* intent */, "moveTaskToFront");
2398 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2399 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002400 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002401 return;
2402 }
2403 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002404 try {
Louis Changcdec0802019-11-11 11:45:07 +08002405 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002406 if (task == null) {
2407 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002408 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002409 return;
2410 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002411 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002412 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002413 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002414 return;
2415 }
2416 ActivityOptions realOptions = options != null
2417 ? options.getOptions(mStackSupervisor)
2418 : null;
2419 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2420 false /* forceNonResizable */);
2421
Wale Ogunwale21e06482019-11-18 05:14:15 -08002422 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002423 if (topActivity != null) {
2424
2425 // We are reshowing a task, use a starting window to hide the initial draw delay
2426 // so the transition can start earlier.
2427 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2428 true /* taskSwitch */, fromRecents);
2429 }
2430 } finally {
2431 Binder.restoreCallingIdentity(origId);
2432 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002433 }
2434
Ricky Waiaca8a772019-04-04 16:01:06 +01002435 /**
2436 * Return true if callingUid is system, or packageName belongs to that callingUid.
2437 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002438 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002439 try {
2440 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2441 if (packageName == null) {
2442 return false;
2443 }
2444 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2445 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2446 UserHandle.getUserId(callingUid));
2447 return UserHandle.isSameApp(callingUid, uid);
2448 }
2449 } catch (RemoteException e) {
2450 // Should not happen
2451 }
2452 return true;
2453 }
2454
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002455 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2456 int callingPid, int callingUid, String name) {
2457 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2458 return true;
2459 }
2460
2461 if (getRecentTasks().isCallerRecents(sourceUid)) {
2462 return true;
2463 }
2464
2465 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2466 if (perm == PackageManager.PERMISSION_GRANTED) {
2467 return true;
2468 }
2469 if (checkAllowAppSwitchUid(sourceUid)) {
2470 return true;
2471 }
2472
2473 // If the actual IPC caller is different from the logical source, then
2474 // also see if they are allowed to control app switches.
2475 if (callingUid != -1 && callingUid != sourceUid) {
2476 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2477 if (perm == PackageManager.PERMISSION_GRANTED) {
2478 return true;
2479 }
2480 if (checkAllowAppSwitchUid(callingUid)) {
2481 return true;
2482 }
2483 }
2484
2485 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2486 return false;
2487 }
2488
2489 private boolean checkAllowAppSwitchUid(int uid) {
2490 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2491 if (types != null) {
2492 for (int i = types.size() - 1; i >= 0; i--) {
2493 if (types.valueAt(i).intValue() == uid) {
2494 return true;
2495 }
2496 }
2497 }
2498 return false;
2499 }
2500
2501 @Override
2502 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2503 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2504 "setActivityController()");
2505 synchronized (mGlobalLock) {
2506 mController = controller;
2507 mControllerIsAMonkey = imAMonkey;
2508 Watchdog.getInstance().setActivityController(controller);
2509 }
2510 }
2511
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002512 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002513 synchronized (mGlobalLock) {
2514 return mController != null && mControllerIsAMonkey;
2515 }
2516 }
2517
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002518 @Override
2519 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2520 synchronized (mGlobalLock) {
2521 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2522 }
2523 }
2524
2525 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002526 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2527 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2528 }
2529
2530 @Override
2531 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2532 @WindowConfiguration.ActivityType int ignoreActivityType,
2533 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2534 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002535 final int callingPid = Binder.getCallingPid();
2536 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002537 final int[] profileIds = getUserManager().getProfileIds(
2538 UserHandle.getUserId(callingUid), true);
2539 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2540 for (int i = 0; i < profileIds.length; i++) {
2541 callingProfileIds.add(profileIds[i]);
2542 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002543 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2544
2545 synchronized (mGlobalLock) {
2546 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2547
Nicholas Sauer0259e532019-08-30 08:24:55 -07002548 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002549 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002550 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002551 }
2552
2553 return list;
2554 }
2555
2556 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002557 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2558 synchronized (mGlobalLock) {
2559 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002560 try {
2561 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2562 if (r == null) return;
2563
2564 final PooledConsumer c = PooledLambda.obtainConsumer(
2565 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2566 r, resultWho, requestCode);
2567 // TODO: This should probably only loop over the task since you need to be in the
2568 // same task to return results.
2569 r.getActivityStack().forAllActivities(c);
2570 c.recycle();
2571
2572 updateOomAdj();
2573 } finally {
2574 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002575 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002576 }
2577 }
2578
2579 @Override
2580 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002581 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002582 ActivityStack stack = ActivityRecord.getStackLocked(token);
2583 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002584 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002585 }
2586 return false;
2587 }
2588 }
2589
2590 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002591 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002592 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002593 synchronized (mGlobalLock) {
2594 final long ident = Binder.clearCallingIdentity();
2595 try {
Louis Changcdec0802019-11-11 11:45:07 +08002596 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002597 if (task == null) {
2598 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2599 return;
2600 }
2601
2602 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2603 + " to stackId=" + stackId + " toTop=" + toTop);
2604
Wale Ogunwaled32da472018-11-16 07:19:28 -08002605 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002606 if (stack == null) {
2607 throw new IllegalStateException(
2608 "moveTaskToStack: No stack for stackId=" + stackId);
2609 }
2610 if (!stack.isActivityTypeStandardOrUndefined()) {
2611 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2612 + taskId + " to stack " + stackId);
2613 }
2614 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002615 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002616 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2617 }
2618 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2619 "moveTaskToStack");
2620 } finally {
2621 Binder.restoreCallingIdentity(ident);
2622 }
2623 }
2624 }
2625
2626 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002627 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2628 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002629
2630 final long ident = Binder.clearCallingIdentity();
2631 try {
2632 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002633 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2634 if (stack == null) {
2635 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2636 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002637 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002638 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2639 throw new IllegalArgumentException("Stack: " + stackId
2640 + " doesn't support animated resize.");
2641 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002642 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002643 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002644 }
2645 } finally {
2646 Binder.restoreCallingIdentity(ident);
2647 }
2648 }
2649
wilsonshih5c4cf522019-01-25 09:03:47 +08002650 @Override
2651 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2652 int animationDuration) {
2653 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2654
2655 final long ident = Binder.clearCallingIdentity();
2656 try {
2657 synchronized (mGlobalLock) {
2658 if (xOffset == 0 && yOffset == 0) {
2659 return;
2660 }
2661 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2662 if (stack == null) {
2663 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2664 return;
2665 }
2666 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2667 throw new IllegalArgumentException("Stack: " + stackId
2668 + " doesn't support animated resize.");
2669 }
2670 final Rect destBounds = new Rect();
2671 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002672 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002673 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2674 return;
2675 }
2676 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002677 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002678 animationDuration, false /* fromFullscreen */);
2679 }
2680 } finally {
2681 Binder.restoreCallingIdentity(ident);
2682 }
2683 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002684 /**
2685 * Moves the specified task to the primary-split-screen stack.
2686 *
2687 * @param taskId Id of task to move.
2688 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2689 * exist already. See
2690 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2691 * and
2692 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2693 * @param toTop If the task and stack should be moved to the top.
2694 * @param animate Whether we should play an animation for the moving the task.
2695 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2696 * stack. Pass {@code null} to use default bounds.
2697 * @param showRecents If the recents activity should be shown on the other side of the task
2698 * going into split-screen mode.
2699 */
2700 @Override
2701 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2702 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002703 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002704 "setTaskWindowingModeSplitScreenPrimary()");
2705 synchronized (mGlobalLock) {
2706 final long ident = Binder.clearCallingIdentity();
2707 try {
Louis Changcdec0802019-11-11 11:45:07 +08002708 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002709 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002710 if (task == null) {
2711 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2712 return false;
2713 }
2714 if (DEBUG_STACK) Slog.d(TAG_STACK,
2715 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2716 + " to createMode=" + createMode + " toTop=" + toTop);
2717 if (!task.isActivityTypeStandardOrUndefined()) {
2718 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2719 + " non-standard task " + taskId + " to split-screen windowing mode");
2720 }
2721
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002722 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002723 final int windowingMode = task.getWindowingMode();
2724 final ActivityStack stack = task.getStack();
2725 if (toTop) {
2726 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2727 }
2728 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002729 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2730 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002731 return windowingMode != task.getWindowingMode();
2732 } finally {
2733 Binder.restoreCallingIdentity(ident);
2734 }
2735 }
2736 }
2737
2738 /**
2739 * Removes stacks in the input windowing modes from the system if they are of activity type
2740 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2741 */
2742 @Override
2743 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002744 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002745 "removeStacksInWindowingModes()");
2746
2747 synchronized (mGlobalLock) {
2748 final long ident = Binder.clearCallingIdentity();
2749 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002750 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002751 } finally {
2752 Binder.restoreCallingIdentity(ident);
2753 }
2754 }
2755 }
2756
2757 @Override
2758 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002759 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002760 "removeStacksWithActivityTypes()");
2761
2762 synchronized (mGlobalLock) {
2763 final long ident = Binder.clearCallingIdentity();
2764 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002765 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002766 } finally {
2767 Binder.restoreCallingIdentity(ident);
2768 }
2769 }
2770 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002771
2772 @Override
2773 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2774 int userId) {
2775 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002776 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2777 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002778 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002779 final boolean detailed = checkGetTasksPermission(
2780 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2781 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002782 == PackageManager.PERMISSION_GRANTED;
2783
2784 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002785 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002786 callingUid);
2787 }
2788 }
2789
2790 @Override
2791 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002792 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002793 long ident = Binder.clearCallingIdentity();
2794 try {
2795 synchronized (mGlobalLock) {
Evan Roskyfd439692019-11-06 16:12:59 -08002796 return mRootActivityContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002797 }
2798 } finally {
2799 Binder.restoreCallingIdentity(ident);
2800 }
2801 }
2802
2803 @Override
2804 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002805 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002806 long ident = Binder.clearCallingIdentity();
2807 try {
2808 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002809 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002810 }
2811 } finally {
2812 Binder.restoreCallingIdentity(ident);
2813 }
2814 }
2815
2816 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002817 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2818 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2819 long ident = Binder.clearCallingIdentity();
2820 try {
2821 synchronized (mGlobalLock) {
2822 return mRootActivityContainer.getAllStackInfos(displayId);
2823 }
2824 } finally {
2825 Binder.restoreCallingIdentity(ident);
2826 }
2827 }
2828
2829 @Override
2830 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2831 int displayId) {
2832 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2833 long ident = Binder.clearCallingIdentity();
2834 try {
2835 synchronized (mGlobalLock) {
2836 return mRootActivityContainer.getStackInfo(windowingMode, activityType, displayId);
2837 }
2838 } finally {
2839 Binder.restoreCallingIdentity(ident);
2840 }
2841 }
2842
2843 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002844 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002845 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002846 final long callingUid = Binder.getCallingUid();
2847 final long origId = Binder.clearCallingIdentity();
2848 try {
2849 synchronized (mGlobalLock) {
2850 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002851 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002852 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2853 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2854 }
2855 } finally {
2856 Binder.restoreCallingIdentity(origId);
2857 }
2858 }
2859
2860 @Override
2861 public void startLockTaskModeByToken(IBinder token) {
2862 synchronized (mGlobalLock) {
2863 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2864 if (r == null) {
2865 return;
2866 }
Louis Changcdec0802019-11-11 11:45:07 +08002867 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002868 }
2869 }
2870
2871 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002872 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002873 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002874 // This makes inner call to look as if it was initiated by system.
2875 long ident = Binder.clearCallingIdentity();
2876 try {
2877 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002878 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002879 MATCH_TASK_IN_STACKS_ONLY);
2880 if (task == null) {
2881 return;
2882 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883
2884 // When starting lock task mode the stack must be in front and focused
2885 task.getStack().moveToFront("startSystemLockTaskMode");
2886 startLockTaskModeLocked(task, true /* isSystemCaller */);
2887 }
2888 } finally {
2889 Binder.restoreCallingIdentity(ident);
2890 }
2891 }
2892
2893 @Override
2894 public void stopLockTaskModeByToken(IBinder token) {
2895 synchronized (mGlobalLock) {
2896 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2897 if (r == null) {
2898 return;
2899 }
Louis Changcdec0802019-11-11 11:45:07 +08002900 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002901 }
2902 }
2903
2904 /**
2905 * This API should be called by SystemUI only when user perform certain action to dismiss
2906 * lock task mode. We should only dismiss pinned lock task mode in this case.
2907 */
2908 @Override
2909 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002910 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002911 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2912 }
2913
Louis Changcdec0802019-11-11 11:45:07 +08002914 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002915 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2916 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2917 return;
2918 }
2919
Wale Ogunwaled32da472018-11-16 07:19:28 -08002920 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002921 if (stack == null || task != stack.topTask()) {
2922 throw new IllegalArgumentException("Invalid task, not in foreground");
2923 }
2924
2925 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2926 // system or a specific app.
2927 // * System-initiated requests will only start the pinned mode (screen pinning)
2928 // * App-initiated requests
2929 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2930 // - will start the pinned mode, otherwise
2931 final int callingUid = Binder.getCallingUid();
2932 long ident = Binder.clearCallingIdentity();
2933 try {
2934 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002935 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002936
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002937 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002938 } finally {
2939 Binder.restoreCallingIdentity(ident);
2940 }
2941 }
2942
Louis Changcdec0802019-11-11 11:45:07 +08002943 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002944 final int callingUid = Binder.getCallingUid();
2945 long ident = Binder.clearCallingIdentity();
2946 try {
2947 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002948 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002949 }
2950 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2951 // task and jumping straight into a call in the case of emergency call back.
2952 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2953 if (tm != null) {
2954 tm.showInCallScreen(false);
2955 }
2956 } finally {
2957 Binder.restoreCallingIdentity(ident);
2958 }
2959 }
2960
2961 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002962 public void updateLockTaskPackages(int userId, String[] packages) {
2963 final int callingUid = Binder.getCallingUid();
2964 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2965 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2966 "updateLockTaskPackages()");
2967 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002968 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002969 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2970 + Arrays.toString(packages));
2971 getLockTaskController().updateLockTaskPackages(userId, packages);
2972 }
2973 }
2974
2975 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002976 public boolean isInLockTaskMode() {
2977 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2978 }
2979
2980 @Override
2981 public int getLockTaskModeState() {
2982 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002983 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002984 }
2985 }
2986
2987 @Override
2988 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2989 synchronized (mGlobalLock) {
2990 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2991 if (r != null) {
2992 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08002993 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002994 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002995 }
2996 }
2997 }
2998
2999 @Override
3000 public Bundle getActivityOptions(IBinder token) {
3001 final long origId = Binder.clearCallingIdentity();
3002 try {
3003 synchronized (mGlobalLock) {
3004 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3005 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003006 final ActivityOptions activityOptions = r.takeOptionsLocked(
3007 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003008 return activityOptions == null ? null : activityOptions.toBundle();
3009 }
3010 return null;
3011 }
3012 } finally {
3013 Binder.restoreCallingIdentity(origId);
3014 }
3015 }
3016
3017 @Override
3018 public List<IBinder> getAppTasks(String callingPackage) {
3019 int callingUid = Binder.getCallingUid();
3020 long ident = Binder.clearCallingIdentity();
3021 try {
3022 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003023 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003024 }
3025 } finally {
3026 Binder.restoreCallingIdentity(ident);
3027 }
3028 }
3029
3030 @Override
3031 public void finishVoiceTask(IVoiceInteractionSession session) {
3032 synchronized (mGlobalLock) {
3033 final long origId = Binder.clearCallingIdentity();
3034 try {
3035 // TODO: VI Consider treating local voice interactions and voice tasks
3036 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08003037 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003038 } finally {
3039 Binder.restoreCallingIdentity(origId);
3040 }
3041 }
3042
3043 }
3044
3045 @Override
3046 public boolean isTopOfTask(IBinder token) {
3047 synchronized (mGlobalLock) {
3048 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003049 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003050 }
3051 }
3052
3053 @Override
3054 public void notifyLaunchTaskBehindComplete(IBinder token) {
3055 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3056 }
3057
3058 @Override
3059 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003060 mH.post(() -> {
3061 synchronized (mGlobalLock) {
3062 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003063 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003064 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003065 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003066 } catch (RemoteException e) {
3067 }
3068 }
3069 }
3070
3071 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003072 }
3073
3074 /** Called from an app when assist data is ready. */
3075 @Override
3076 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3077 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003078 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003079 synchronized (pae) {
3080 pae.result = extras;
3081 pae.structure = structure;
3082 pae.content = content;
3083 if (referrer != null) {
3084 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3085 }
3086 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003087 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003088 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003089 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003090 structure.setHomeActivity(pae.isHome);
3091 }
3092 pae.haveResult = true;
3093 pae.notifyAll();
3094 if (pae.intent == null && pae.receiver == null) {
3095 // Caller is just waiting for the result.
3096 return;
3097 }
3098 }
3099 // We are now ready to launch the assist activity.
3100 IAssistDataReceiver sendReceiver = null;
3101 Bundle sendBundle = null;
3102 synchronized (mGlobalLock) {
3103 buildAssistBundleLocked(pae, extras);
3104 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003105 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003106 if (!exists) {
3107 // Timed out.
3108 return;
3109 }
3110
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003111 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003112 // Caller wants result sent back to them.
3113 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003114 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003115 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003116 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3117 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003118 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3119 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3120 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3121 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3122 }
3123 }
3124 if (sendReceiver != null) {
3125 try {
3126 sendReceiver.onHandleAssistData(sendBundle);
3127 } catch (RemoteException e) {
3128 }
3129 return;
3130 }
3131
3132 final long ident = Binder.clearCallingIdentity();
3133 try {
3134 if (TextUtils.equals(pae.intent.getAction(),
3135 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003136 // Start voice interaction through VoiceInteractionManagerService.
3137 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3138 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003139 } else {
3140 pae.intent.replaceExtras(pae.extras);
3141 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3142 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3143 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003144 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003145
3146 try {
3147 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3148 } catch (ActivityNotFoundException e) {
3149 Slog.w(TAG, "No activity to handle assist action.", e);
3150 }
3151 }
3152 } finally {
3153 Binder.restoreCallingIdentity(ident);
3154 }
3155 }
3156
3157 @Override
3158 public int addAppTask(IBinder activityToken, Intent intent,
3159 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3160 final int callingUid = Binder.getCallingUid();
3161 final long callingIdent = Binder.clearCallingIdentity();
3162
3163 try {
3164 synchronized (mGlobalLock) {
3165 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3166 if (r == null) {
3167 throw new IllegalArgumentException("Activity does not exist; token="
3168 + activityToken);
3169 }
3170 ComponentName comp = intent.getComponent();
3171 if (comp == null) {
3172 throw new IllegalArgumentException("Intent " + intent
3173 + " must specify explicit component");
3174 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003175 if (thumbnail.getWidth() != mThumbnailWidth
3176 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003177 throw new IllegalArgumentException("Bad thumbnail size: got "
3178 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003179 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003180 }
3181 if (intent.getSelector() != null) {
3182 intent.setSelector(null);
3183 }
3184 if (intent.getSourceBounds() != null) {
3185 intent.setSourceBounds(null);
3186 }
3187 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3188 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3189 // The caller has added this as an auto-remove task... that makes no
3190 // sense, so turn off auto-remove.
3191 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3192 }
3193 }
3194 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3195 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3196 if (ainfo.applicationInfo.uid != callingUid) {
3197 throw new SecurityException(
3198 "Can't add task for another application: target uid="
3199 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3200 }
3201
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003202 final ActivityStack stack = r.getActivityStack();
Louis Changcdec0802019-11-11 11:45:07 +08003203 final Task task = stack.createTask(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003204 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003205 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003206 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003207 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003208 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003209 return INVALID_TASK_ID;
3210 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003211 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003212
3213 // TODO: Send the thumbnail to WM to store it.
3214
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003215 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003216 }
3217 } finally {
3218 Binder.restoreCallingIdentity(callingIdent);
3219 }
3220 }
3221
3222 @Override
3223 public Point getAppTaskThumbnailSize() {
3224 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003225 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003226 }
3227 }
3228
3229 @Override
3230 public void setTaskResizeable(int taskId, int resizeableMode) {
3231 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08003232 final Task task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003233 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3234 if (task == null) {
3235 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3236 return;
3237 }
3238 task.setResizeMode(resizeableMode);
3239 }
3240 }
3241
3242 @Override
3243 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003244 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003245 long ident = Binder.clearCallingIdentity();
3246 try {
3247 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08003248 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003249 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003250 if (task == null) {
3251 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3252 return;
3253 }
3254 // Place the task in the right stack if it isn't there already based on
3255 // the requested bounds.
3256 // The stack transition logic is:
3257 // - a null bounds on a freeform task moves that task to fullscreen
3258 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3259 // that task to freeform
3260 // - otherwise the task is not moved
3261 ActivityStack stack = task.getStack();
3262 if (!task.getWindowConfiguration().canResizeTask()) {
3263 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3264 }
3265 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3266 stack = stack.getDisplay().getOrCreateStack(
3267 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3268 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3269 stack = stack.getDisplay().getOrCreateStack(
3270 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3271 }
3272
3273 // Reparent the task to the right stack if necessary
3274 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3275 if (stack != task.getStack()) {
3276 // Defer resume until the task is resized below
3277 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3278 DEFER_RESUME, "resizeTask");
3279 preserveWindow = false;
3280 }
3281
3282 // After reparenting (which only resizes the task to the stack bounds), resize the
3283 // task to the actual bounds provided
3284 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3285 }
3286 } finally {
3287 Binder.restoreCallingIdentity(ident);
3288 }
3289 }
3290
Evan Roskyddedfd42019-10-04 13:38:38 -07003291 private void sanitizeAndApplyConfigChange(ConfigurationContainer container,
3292 WindowContainerTransaction.Change change) {
Evan Rosky282ee672019-11-13 15:50:46 -08003293 if (!(container instanceof Task || container instanceof ActivityStack)) {
Evan Roskyddedfd42019-10-04 13:38:38 -07003294 throw new RuntimeException("Invalid token in task transaction");
3295 }
3296 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3297 // masks here.
3298 int configMask = change.getConfigSetMask();
3299 int windowMask = change.getWindowSetMask();
3300 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3301 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3302 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
3303 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3304 c.setTo(change.getConfiguration(), configMask, windowMask);
3305 container.onRequestedOverrideConfigurationChanged(c);
3306 }
3307
3308 @Override
3309 public void applyContainerTransaction(WindowContainerTransaction t) {
3310 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
3311 long ident = Binder.clearCallingIdentity();
3312 try {
3313 if (t == null) {
3314 return;
3315 }
3316 synchronized (mGlobalLock) {
3317 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3318 t.getChanges().entrySet().iterator();
3319 while (entries.hasNext()) {
3320 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3321 entries.next();
3322 final ConfigurationContainer cc = ConfigurationContainer.RemoteToken.fromBinder(
3323 entry.getKey()).getContainer();
3324 sanitizeAndApplyConfigChange(cc, entry.getValue());
3325 }
3326 }
3327 } finally {
3328 Binder.restoreCallingIdentity(ident);
3329 }
3330 }
3331
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003332 @Override
3333 public boolean releaseActivityInstance(IBinder token) {
3334 synchronized (mGlobalLock) {
3335 final long origId = Binder.clearCallingIdentity();
3336 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003337 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3338 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003339 return false;
3340 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003341 r.destroyImmediately(true /* removeFromApp */, "app-req");
3342 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003343 } finally {
3344 Binder.restoreCallingIdentity(origId);
3345 }
3346 }
3347 }
3348
3349 @Override
3350 public void releaseSomeActivities(IApplicationThread appInt) {
3351 synchronized (mGlobalLock) {
3352 final long origId = Binder.clearCallingIdentity();
3353 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003354 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003355 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003356 } finally {
3357 Binder.restoreCallingIdentity(origId);
3358 }
3359 }
3360 }
3361
3362 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003363 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003364 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003365 != PackageManager.PERMISSION_GRANTED) {
3366 throw new SecurityException("Requires permission "
3367 + android.Manifest.permission.DEVICE_POWER);
3368 }
3369
3370 synchronized (mGlobalLock) {
3371 long ident = Binder.clearCallingIdentity();
3372 if (mKeyguardShown != keyguardShowing) {
3373 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003374 final Message msg = PooledLambda.obtainMessage(
3375 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3376 keyguardShowing);
3377 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378 }
3379 try {
wilsonshih177261f2019-02-22 12:02:18 +08003380 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003381 } finally {
3382 Binder.restoreCallingIdentity(ident);
3383 }
3384 }
3385
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003386 mH.post(() -> {
3387 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3388 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3389 }
3390 });
3391 }
3392
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003393 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003394 mH.post(() -> {
3395 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3396 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3397 }
3398 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003399 }
3400
3401 @Override
3402 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003403 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3404 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003405
3406 final File passedIconFile = new File(filePath);
3407 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3408 passedIconFile.getName());
3409 if (!legitIconFile.getPath().equals(filePath)
3410 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3411 throw new IllegalArgumentException("Bad file path: " + filePath
3412 + " passed for userId " + userId);
3413 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003414 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003415 }
3416
3417 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003418 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003419 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003420 synchronized (mGlobalLock) {
3421 final long ident = Binder.clearCallingIdentity();
3422 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003423 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 if (stack == null) {
3425 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3426 return;
3427 }
3428 if (!stack.isActivityTypeStandardOrUndefined()) {
3429 throw new IllegalArgumentException(
3430 "Removing non-standard stack is not allowed.");
3431 }
3432 mStackSupervisor.removeStack(stack);
3433 } finally {
3434 Binder.restoreCallingIdentity(ident);
3435 }
3436 }
3437 }
3438
3439 @Override
3440 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003441 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003442
3443 synchronized (mGlobalLock) {
3444 final long ident = Binder.clearCallingIdentity();
3445 try {
3446 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3447 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003448 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003449 } finally {
3450 Binder.restoreCallingIdentity(ident);
3451 }
3452 }
3453 }
3454
3455 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003456 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003457 synchronized (mGlobalLock) {
3458 long ident = Binder.clearCallingIdentity();
3459 try {
3460 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3461 if (r == null) {
3462 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003463 "toggleFreeformWindowingMode: No activity record matching token="
3464 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003465 }
3466
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003467 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003468 if (stack == null) {
3469 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3470 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003471 }
3472
Yunfan Chend967af82019-01-17 18:30:18 +09003473 if (!stack.inFreeformWindowingMode()
3474 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3475 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3476 + "toggle between fullscreen and freeform.");
3477 }
3478
3479 if (stack.inFreeformWindowingMode()) {
3480 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003481 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003482 throw new IllegalStateException("Size-compat windows are currently not"
3483 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003484 } else if (stack.getParent().inFreeformWindowingMode()) {
3485 // If the window is on a freeform display, set it to undefined. It will be
3486 // resolved to freeform and it can adjust windowing mode when the display mode
3487 // changes in runtime.
3488 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003489 } else {
3490 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3491 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003492 } finally {
3493 Binder.restoreCallingIdentity(ident);
3494 }
3495 }
3496 }
3497
3498 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3499 @Override
3500 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003501 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003502 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003503 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003504 }
3505
3506 /** Unregister a task stack listener so that it stops receiving callbacks. */
3507 @Override
3508 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003509 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003510 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003511 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003512 }
3513
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003514 @Override
3515 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3516 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3517 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3518 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3519 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3520 }
3521
3522 @Override
3523 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3524 IBinder activityToken, int flags) {
3525 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3526 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3527 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3528 }
3529
3530 @Override
3531 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3532 Bundle args) {
3533 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3534 true /* focused */, true /* newSessionId */, userHandle, args,
3535 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3536 }
3537
3538 @Override
3539 public Bundle getAssistContextExtras(int requestType) {
3540 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3541 null, null, true /* focused */, true /* newSessionId */,
3542 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3543 if (pae == null) {
3544 return null;
3545 }
3546 synchronized (pae) {
3547 while (!pae.haveResult) {
3548 try {
3549 pae.wait();
3550 } catch (InterruptedException e) {
3551 }
3552 }
3553 }
3554 synchronized (mGlobalLock) {
3555 buildAssistBundleLocked(pae, pae.result);
3556 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003557 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003558 }
3559 return pae.extras;
3560 }
3561
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003562 /**
3563 * Binder IPC calls go through the public entry point.
3564 * This can be called with or without the global lock held.
3565 */
3566 private static int checkCallingPermission(String permission) {
3567 return checkPermission(
3568 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3569 }
3570
3571 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003572 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003573 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3574 mAmInternal.enforceCallingPermission(permission, func);
3575 }
3576 }
3577
3578 @VisibleForTesting
3579 int checkGetTasksPermission(String permission, int pid, int uid) {
3580 return checkPermission(permission, pid, uid);
3581 }
3582
3583 static int checkPermission(String permission, int pid, int uid) {
3584 if (permission == null) {
3585 return PackageManager.PERMISSION_DENIED;
3586 }
3587 return checkComponentPermission(permission, pid, uid, -1, true);
3588 }
3589
Wale Ogunwale214f3482018-10-04 11:00:47 -07003590 public static int checkComponentPermission(String permission, int pid, int uid,
3591 int owningUid, boolean exported) {
3592 return ActivityManagerService.checkComponentPermission(
3593 permission, pid, uid, owningUid, exported);
3594 }
3595
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003596 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3597 if (getRecentTasks().isCallerRecents(callingUid)) {
3598 // Always allow the recents component to get tasks
3599 return true;
3600 }
3601
3602 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3603 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3604 if (!allowed) {
3605 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3606 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3607 // Temporary compatibility: some existing apps on the system image may
3608 // still be requesting the old permission and not switched to the new
3609 // one; if so, we'll still allow them full access. This means we need
3610 // to see if they are holding the old permission and are a system app.
3611 try {
3612 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3613 allowed = true;
3614 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3615 + " is using old GET_TASKS but privileged; allowing");
3616 }
3617 } catch (RemoteException e) {
3618 }
3619 }
3620 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3621 + " does not hold REAL_GET_TASKS; limiting output");
3622 }
3623 return allowed;
3624 }
3625
Nicholas Sauer0259e532019-08-30 08:24:55 -07003626 boolean isCrossUserAllowed(int pid, int uid) {
3627 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3628 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3629 }
3630
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003631 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3632 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3633 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3634 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003635 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003636 "enqueueAssistContext()");
3637
3638 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003639 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003640 if (activity == null) {
3641 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3642 return null;
3643 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003644 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003645 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3646 return null;
3647 }
3648 if (focused) {
3649 if (activityToken != null) {
3650 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3651 if (activity != caller) {
3652 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3653 + " is not current top " + activity);
3654 return null;
3655 }
3656 }
3657 } else {
3658 activity = ActivityRecord.forTokenLocked(activityToken);
3659 if (activity == null) {
3660 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3661 + " couldn't be found");
3662 return null;
3663 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003664 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003665 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3666 return null;
3667 }
3668 }
3669
3670 PendingAssistExtras pae;
3671 Bundle extras = new Bundle();
3672 if (args != null) {
3673 extras.putAll(args);
3674 }
3675 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003676 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003677
3678 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3679 userHandle);
3680 pae.isHome = activity.isActivityTypeHome();
3681
3682 // Increment the sessionId if necessary
3683 if (newSessionId) {
3684 mViSessionId++;
3685 }
3686 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003687 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3688 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003689 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003690 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003691 } catch (RemoteException e) {
3692 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3693 return null;
3694 }
3695 return pae;
3696 }
3697 }
3698
3699 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3700 if (result != null) {
3701 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3702 }
3703 if (pae.hint != null) {
3704 pae.extras.putBoolean(pae.hint, true);
3705 }
3706 }
3707
3708 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3709 IAssistDataReceiver receiver;
3710 synchronized (mGlobalLock) {
3711 mPendingAssistExtras.remove(pae);
3712 receiver = pae.receiver;
3713 }
3714 if (receiver != null) {
3715 // Caller wants result sent back to them.
3716 Bundle sendBundle = new Bundle();
3717 // At least return the receiver extras
3718 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3719 try {
3720 pae.receiver.onHandleAssistData(sendBundle);
3721 } catch (RemoteException e) {
3722 }
3723 }
3724 }
3725
3726 public class PendingAssistExtras extends Binder implements Runnable {
3727 public final ActivityRecord activity;
3728 public boolean isHome;
3729 public final Bundle extras;
3730 public final Intent intent;
3731 public final String hint;
3732 public final IAssistDataReceiver receiver;
3733 public final int userHandle;
3734 public boolean haveResult = false;
3735 public Bundle result = null;
3736 public AssistStructure structure = null;
3737 public AssistContent content = null;
3738 public Bundle receiverExtras;
3739
3740 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3741 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3742 int _userHandle) {
3743 activity = _activity;
3744 extras = _extras;
3745 intent = _intent;
3746 hint = _hint;
3747 receiver = _receiver;
3748 receiverExtras = _receiverExtras;
3749 userHandle = _userHandle;
3750 }
3751
3752 @Override
3753 public void run() {
3754 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3755 synchronized (this) {
3756 haveResult = true;
3757 notifyAll();
3758 }
3759 pendingAssistExtrasTimedOut(this);
3760 }
3761 }
3762
3763 @Override
3764 public boolean isAssistDataAllowedOnCurrentActivity() {
3765 int userId;
3766 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003767 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003768 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3769 return false;
3770 }
3771
Wale Ogunwale21e06482019-11-18 05:14:15 -08003772 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003773 if (activity == null) {
3774 return false;
3775 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003776 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003777 }
3778 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3779 }
3780
3781 @Override
3782 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3783 long ident = Binder.clearCallingIdentity();
3784 try {
3785 synchronized (mGlobalLock) {
3786 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003787 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003788 if (top != caller) {
3789 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3790 + " is not current top " + top);
3791 return false;
3792 }
3793 if (!top.nowVisible) {
3794 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3795 + " is not visible");
3796 return false;
3797 }
3798 }
3799 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3800 token);
3801 } finally {
3802 Binder.restoreCallingIdentity(ident);
3803 }
3804 }
3805
3806 @Override
3807 public boolean isRootVoiceInteraction(IBinder token) {
3808 synchronized (mGlobalLock) {
3809 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3810 if (r == null) {
3811 return false;
3812 }
3813 return r.rootVoiceInteraction;
3814 }
3815 }
3816
Wale Ogunwalef6733932018-06-27 05:14:34 -07003817 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3818 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3819 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3820 if (activityToCallback == null) return;
3821 activityToCallback.setVoiceSessionLocked(voiceSession);
3822
3823 // Inform the activity
3824 try {
3825 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3826 voiceInteractor);
3827 long token = Binder.clearCallingIdentity();
3828 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003829 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003830 } finally {
3831 Binder.restoreCallingIdentity(token);
3832 }
3833 // TODO: VI Should we cache the activity so that it's easier to find later
3834 // rather than scan through all the stacks and activities?
3835 } catch (RemoteException re) {
3836 activityToCallback.clearVoiceSessionLocked();
3837 // TODO: VI Should this terminate the voice session?
3838 }
3839 }
3840
3841 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3842 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3843 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3844 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3845 boolean wasRunningVoice = mRunningVoice != null;
3846 mRunningVoice = session;
3847 if (!wasRunningVoice) {
3848 mVoiceWakeLock.acquire();
3849 updateSleepIfNeededLocked();
3850 }
3851 }
3852 }
3853
3854 void finishRunningVoiceLocked() {
3855 if (mRunningVoice != null) {
3856 mRunningVoice = null;
3857 mVoiceWakeLock.release();
3858 updateSleepIfNeededLocked();
3859 }
3860 }
3861
3862 @Override
3863 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3864 synchronized (mGlobalLock) {
3865 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3866 if (keepAwake) {
3867 mVoiceWakeLock.acquire();
3868 } else {
3869 mVoiceWakeLock.release();
3870 }
3871 }
3872 }
3873 }
3874
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003875 @Override
3876 public ComponentName getActivityClassForToken(IBinder token) {
3877 synchronized (mGlobalLock) {
3878 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3879 if (r == null) {
3880 return null;
3881 }
3882 return r.intent.getComponent();
3883 }
3884 }
3885
3886 @Override
3887 public String getPackageForToken(IBinder token) {
3888 synchronized (mGlobalLock) {
3889 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3890 if (r == null) {
3891 return null;
3892 }
3893 return r.packageName;
3894 }
3895 }
3896
3897 @Override
3898 public void showLockTaskEscapeMessage(IBinder token) {
3899 synchronized (mGlobalLock) {
3900 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3901 if (r == null) {
3902 return;
3903 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003904 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003905 }
3906 }
3907
3908 @Override
3909 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003910 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003911 final long token = Binder.clearCallingIdentity();
3912 try {
3913 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003914 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003915 }
3916 } finally {
3917 Binder.restoreCallingIdentity(token);
3918 }
3919 }
3920
3921 /**
3922 * Try to place task to provided position. The final position might be different depending on
3923 * current user and stacks state. The task will be moved to target stack if it's currently in
3924 * different stack.
3925 */
3926 @Override
3927 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003928 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003929 synchronized (mGlobalLock) {
3930 long ident = Binder.clearCallingIdentity();
3931 try {
3932 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3933 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Changcdec0802019-11-11 11:45:07 +08003934 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003935 if (task == null) {
3936 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3937 + taskId);
3938 }
3939
Wale Ogunwaled32da472018-11-16 07:19:28 -08003940 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003941
3942 if (stack == null) {
3943 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3944 + stackId);
3945 }
3946 if (!stack.isActivityTypeStandardOrUndefined()) {
3947 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3948 + " the position of task " + taskId + " in/to non-standard stack");
3949 }
3950
3951 // TODO: Have the callers of this API call a separate reparent method if that is
3952 // what they intended to do vs. having this method also do reparenting.
3953 if (task.getStack() == stack) {
3954 // Change position in current stack.
3955 stack.positionChildAt(task, position);
3956 } else {
3957 // Reparent to new stack.
3958 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3959 !DEFER_RESUME, "positionTaskInStack");
3960 }
3961 } finally {
3962 Binder.restoreCallingIdentity(ident);
3963 }
3964 }
3965 }
3966
3967 @Override
3968 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3969 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3970 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003971 + Arrays.toString(horizontalSizeConfiguration) + " "
3972 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003973 synchronized (mGlobalLock) {
3974 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3975 if (record == null) {
3976 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3977 + "found for: " + token);
3978 }
3979 record.setSizeConfigurations(horizontalSizeConfiguration,
3980 verticalSizeConfigurations, smallestSizeConfigurations);
3981 }
3982 }
3983
3984 /**
3985 * Dismisses split-screen multi-window mode.
3986 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3987 */
3988 @Override
3989 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003990 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003991 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3992 final long ident = Binder.clearCallingIdentity();
3993 try {
3994 synchronized (mGlobalLock) {
3995 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003996 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003997 if (stack == null) {
3998 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3999 return;
4000 }
4001
4002 if (toTop) {
4003 // Caller wants the current split-screen primary stack to be the top stack after
4004 // it goes fullscreen, so move it to the front.
4005 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004006 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004007 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004008 // stack after it goes fullscreen, so we move the focus to the top-most
4009 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004010 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
4011 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
4012 if (otherStack != null) {
4013 otherStack.moveToFront("dismissSplitScreenMode_other");
4014 }
4015 }
4016
Evan Rosky10475742018-09-05 19:02:48 -07004017 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004018 }
4019 } finally {
4020 Binder.restoreCallingIdentity(ident);
4021 }
4022 }
4023
4024 /**
4025 * Dismisses Pip
4026 * @param animate True if the dismissal should be animated.
4027 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4028 * default animation duration should be used.
4029 */
4030 @Override
4031 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004032 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004033 final long ident = Binder.clearCallingIdentity();
4034 try {
4035 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004036 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08004037 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004038 if (stack == null) {
4039 Slog.w(TAG, "dismissPip: pinned stack not found.");
4040 return;
4041 }
4042 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4043 throw new IllegalArgumentException("Stack: " + stack
4044 + " doesn't support animated resize.");
4045 }
4046 if (animate) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004047 stack.animateResizePinnedStack(null /* destBounds */,
4048 null /* sourceHintBounds */, animationDuration,
4049 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004050 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004051 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004052 }
4053 }
4054 } finally {
4055 Binder.restoreCallingIdentity(ident);
4056 }
4057 }
4058
4059 @Override
4060 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004061 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004062 synchronized (mGlobalLock) {
4063 mSuppressResizeConfigChanges = suppress;
4064 }
4065 }
4066
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004067 @Override
4068 // TODO: API should just be about changing windowing modes...
4069 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004070 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004071 "moveTasksToFullscreenStack()");
4072 synchronized (mGlobalLock) {
4073 final long origId = Binder.clearCallingIdentity();
4074 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004075 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004076 if (stack != null){
4077 if (!stack.isActivityTypeStandardOrUndefined()) {
4078 throw new IllegalArgumentException(
4079 "You can't move tasks from non-standard stacks.");
4080 }
4081 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4082 }
4083 } finally {
4084 Binder.restoreCallingIdentity(origId);
4085 }
4086 }
4087 }
4088
4089 /**
4090 * Moves the top activity in the input stackId to the pinned stack.
4091 *
4092 * @param stackId Id of stack to move the top activity to pinned stack.
4093 * @param bounds Bounds to use for pinned stack.
4094 *
4095 * @return True if the top activity of the input stack was successfully moved to the pinned
4096 * stack.
4097 */
4098 @Override
4099 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004100 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004101 "moveTopActivityToPinnedStack()");
4102 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004103 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004104 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4105 + "Device doesn't support picture-in-picture mode");
4106 }
4107
4108 long ident = Binder.clearCallingIdentity();
4109 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004110 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004111 } finally {
4112 Binder.restoreCallingIdentity(ident);
4113 }
4114 }
4115 }
4116
4117 @Override
4118 public boolean isInMultiWindowMode(IBinder token) {
4119 final long origId = Binder.clearCallingIdentity();
4120 try {
4121 synchronized (mGlobalLock) {
4122 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4123 if (r == null) {
4124 return false;
4125 }
4126 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4127 return r.inMultiWindowMode();
4128 }
4129 } finally {
4130 Binder.restoreCallingIdentity(origId);
4131 }
4132 }
4133
4134 @Override
4135 public boolean isInPictureInPictureMode(IBinder token) {
4136 final long origId = Binder.clearCallingIdentity();
4137 try {
4138 synchronized (mGlobalLock) {
4139 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4140 }
4141 } finally {
4142 Binder.restoreCallingIdentity(origId);
4143 }
4144 }
4145
4146 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004147 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4148 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004149 return false;
4150 }
4151
4152 // If we are animating to fullscreen then we have already dispatched the PIP mode
4153 // changed, so we should reflect that check here as well.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004154 final ActivityStack taskStack = r.getActivityStack();
Yunfan Chen279f5582018-12-12 15:24:50 -08004155 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004156 }
4157
4158 @Override
4159 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4160 final long origId = Binder.clearCallingIdentity();
4161 try {
4162 synchronized (mGlobalLock) {
4163 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4164 "enterPictureInPictureMode", token, params);
4165
4166 // If the activity is already in picture in picture mode, then just return early
4167 if (isInPictureInPictureMode(r)) {
4168 return true;
4169 }
4170
4171 // Activity supports picture-in-picture, now check that we can enter PiP at this
4172 // point, if it is
4173 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4174 false /* beforeStopping */)) {
4175 return false;
4176 }
4177
4178 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004179 synchronized (mGlobalLock) {
4180 // Only update the saved args from the args that are set
4181 r.pictureInPictureArgs.copyOnlySet(params);
4182 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4183 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4184 // Adjust the source bounds by the insets for the transition down
4185 final Rect sourceBounds = new Rect(
4186 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004187 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004188 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004189 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004190 stack.setPictureInPictureAspectRatio(aspectRatio);
4191 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004192 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4193 r.info.applicationInfo.uid, r.shortComponentName,
4194 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004195 logPictureInPictureArgs(params);
4196 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004197 };
4198
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004199 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004200 // If the keyguard is showing or occluded, then try and dismiss it before
4201 // entering picture-in-picture (this will prompt the user to authenticate if the
4202 // device is currently locked).
4203 dismissKeyguard(token, new KeyguardDismissCallback() {
4204 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004205 public void onDismissSucceeded() {
4206 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004207 }
4208 }, null /* message */);
4209 } else {
4210 // Enter picture in picture immediately otherwise
4211 enterPipRunnable.run();
4212 }
4213 return true;
4214 }
4215 } finally {
4216 Binder.restoreCallingIdentity(origId);
4217 }
4218 }
4219
4220 @Override
4221 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4222 final long origId = Binder.clearCallingIdentity();
4223 try {
4224 synchronized (mGlobalLock) {
4225 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4226 "setPictureInPictureParams", token, params);
4227
4228 // Only update the saved args from the args that are set
4229 r.pictureInPictureArgs.copyOnlySet(params);
4230 if (r.inPinnedWindowingMode()) {
4231 // If the activity is already in picture-in-picture, update the pinned stack now
4232 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4233 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004234 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004235 if (!stack.isAnimatingBoundsToFullscreen()) {
4236 stack.setPictureInPictureAspectRatio(
4237 r.pictureInPictureArgs.getAspectRatio());
4238 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4239 }
4240 }
4241 logPictureInPictureArgs(params);
4242 }
4243 } finally {
4244 Binder.restoreCallingIdentity(origId);
4245 }
4246 }
4247
4248 @Override
4249 public int getMaxNumPictureInPictureActions(IBinder token) {
4250 // Currently, this is a static constant, but later, we may change this to be dependent on
4251 // the context of the activity
4252 return 3;
4253 }
4254
4255 private void logPictureInPictureArgs(PictureInPictureParams params) {
4256 if (params.hasSetActions()) {
4257 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4258 params.getActions().size());
4259 }
4260 if (params.hasSetAspectRatio()) {
4261 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4262 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4263 MetricsLogger.action(lm);
4264 }
4265 }
4266
4267 /**
4268 * Checks the state of the system and the activity associated with the given {@param token} to
4269 * verify that picture-in-picture is supported for that activity.
4270 *
4271 * @return the activity record for the given {@param token} if all the checks pass.
4272 */
4273 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4274 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004275 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004276 throw new IllegalStateException(caller
4277 + ": Device doesn't support picture-in-picture mode.");
4278 }
4279
4280 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4281 if (r == null) {
4282 throw new IllegalStateException(caller
4283 + ": Can't find activity for token=" + token);
4284 }
4285
4286 if (!r.supportsPictureInPicture()) {
4287 throw new IllegalStateException(caller
4288 + ": Current activity does not support picture-in-picture.");
4289 }
4290
4291 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004292 && !mWindowManager.isValidPictureInPictureAspectRatio(
4293 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004294 final float minAspectRatio = mContext.getResources().getFloat(
4295 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4296 final float maxAspectRatio = mContext.getResources().getFloat(
4297 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4298 throw new IllegalArgumentException(String.format(caller
4299 + ": Aspect ratio is too extreme (must be between %f and %f).",
4300 minAspectRatio, maxAspectRatio));
4301 }
4302
4303 // Truncate the number of actions if necessary
4304 params.truncateActions(getMaxNumPictureInPictureActions(token));
4305
4306 return r;
4307 }
4308
4309 @Override
4310 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004311 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004312 synchronized (mGlobalLock) {
4313 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4314 if (r == null) {
4315 throw new IllegalArgumentException("Activity does not exist; token="
4316 + activityToken);
4317 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004318 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004319 }
4320 }
4321
4322 @Override
4323 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4324 Rect tempDockedTaskInsetBounds,
4325 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004326 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004327 long ident = Binder.clearCallingIdentity();
4328 try {
4329 synchronized (mGlobalLock) {
4330 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4331 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4332 PRESERVE_WINDOWS);
4333 }
4334 } finally {
4335 Binder.restoreCallingIdentity(ident);
4336 }
4337 }
4338
4339 @Override
4340 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004341 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004342 final long ident = Binder.clearCallingIdentity();
4343 try {
4344 synchronized (mGlobalLock) {
4345 mStackSupervisor.setSplitScreenResizing(resizing);
4346 }
4347 } finally {
4348 Binder.restoreCallingIdentity(ident);
4349 }
4350 }
4351
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004352 /**
4353 * Check that we have the features required for VR-related API calls, and throw an exception if
4354 * not.
4355 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004356 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004357 if (!mContext.getPackageManager().hasSystemFeature(
4358 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4359 throw new UnsupportedOperationException("VR mode not supported on this device!");
4360 }
4361 }
4362
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004363 @Override
4364 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004365 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004366
4367 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4368
4369 ActivityRecord r;
4370 synchronized (mGlobalLock) {
4371 r = ActivityRecord.isInStackLocked(token);
4372 }
4373
4374 if (r == null) {
4375 throw new IllegalArgumentException();
4376 }
4377
4378 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004379 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004380 VrManagerInternal.NO_ERROR) {
4381 return err;
4382 }
4383
4384 // Clear the binder calling uid since this path may call moveToTask().
4385 final long callingId = Binder.clearCallingIdentity();
4386 try {
4387 synchronized (mGlobalLock) {
4388 r.requestedVrComponent = (enabled) ? packageName : null;
4389
4390 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004391 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004392 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004393 }
4394 return 0;
4395 }
4396 } finally {
4397 Binder.restoreCallingIdentity(callingId);
4398 }
4399 }
4400
4401 @Override
4402 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4403 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4404 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004405 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004406 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4407 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4408 }
Louis Changcdec0802019-11-11 11:45:07 +08004409 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004410 || activity.voiceSession != null) {
4411 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4412 return;
4413 }
4414 if (activity.pendingVoiceInteractionStart) {
4415 Slog.w(TAG, "Pending start of voice interaction already.");
4416 return;
4417 }
4418 activity.pendingVoiceInteractionStart = true;
4419 }
4420 LocalServices.getService(VoiceInteractionManagerInternal.class)
4421 .startLocalVoiceInteraction(callingActivity, options);
4422 }
4423
4424 @Override
4425 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4426 LocalServices.getService(VoiceInteractionManagerInternal.class)
4427 .stopLocalVoiceInteraction(callingActivity);
4428 }
4429
4430 @Override
4431 public boolean supportsLocalVoiceInteraction() {
4432 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4433 .supportsLocalVoiceInteraction();
4434 }
4435
4436 /** Notifies all listeners when the pinned stack animation starts. */
4437 @Override
4438 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004439 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004440 }
4441
4442 /** Notifies all listeners when the pinned stack animation ends. */
4443 @Override
4444 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004445 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004446 }
4447
4448 @Override
4449 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004450 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004451 final long ident = Binder.clearCallingIdentity();
4452 try {
4453 synchronized (mGlobalLock) {
4454 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4455 }
4456 } finally {
4457 Binder.restoreCallingIdentity(ident);
4458 }
4459 }
4460
4461 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004462 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004463 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004464
4465 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004466 if (mWindowManager == null) {
4467 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4468 return false;
4469 }
4470
4471 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004472 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004473 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004474 }
4475
Riddle Hsua0022cd2019-09-09 21:12:41 +08004476 mH.sendMessage(PooledLambda.obtainMessage(
4477 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4478 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004479
4480 final long origId = Binder.clearCallingIdentity();
4481 try {
4482 if (values != null) {
4483 Settings.System.clearConfiguration(values);
4484 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004485 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004486 UserHandle.USER_NULL, false /* deferResume */,
4487 mTmpUpdateConfigurationResult);
4488 return mTmpUpdateConfigurationResult.changes != 0;
4489 } finally {
4490 Binder.restoreCallingIdentity(origId);
4491 }
4492 }
4493 }
4494
4495 @Override
4496 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4497 CharSequence message) {
4498 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004499 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004500 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4501 }
4502 final long callingId = Binder.clearCallingIdentity();
4503 try {
4504 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004505 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004506 }
4507 } finally {
4508 Binder.restoreCallingIdentity(callingId);
4509 }
4510 }
4511
4512 @Override
4513 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004514 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004515 "cancelTaskWindowTransition()");
4516 final long ident = Binder.clearCallingIdentity();
4517 try {
4518 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08004519 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004520 MATCH_TASK_IN_STACKS_ONLY);
4521 if (task == null) {
4522 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4523 return;
4524 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004525 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004526 }
4527 } finally {
4528 Binder.restoreCallingIdentity(ident);
4529 }
4530 }
4531
4532 @Override
4533 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004534 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004535 final long ident = Binder.clearCallingIdentity();
4536 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004537 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004538 } finally {
4539 Binder.restoreCallingIdentity(ident);
4540 }
4541 }
4542
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004543 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4544 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004545 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004546 synchronized (mGlobalLock) {
4547 task = mRootActivityContainer.anyTaskForId(taskId,
4548 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4549 if (task == null) {
4550 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4551 return null;
4552 }
4553 }
4554 // Don't call this while holding the lock as this operation might hit the disk.
4555 return task.getSnapshot(reducedResolution, restoreFromDisk);
4556 }
4557
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004558 @Override
4559 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4560 synchronized (mGlobalLock) {
4561 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4562 if (r == null) {
4563 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4564 + token);
4565 return;
4566 }
4567 final long origId = Binder.clearCallingIdentity();
4568 try {
4569 r.setDisablePreviewScreenshots(disable);
4570 } finally {
4571 Binder.restoreCallingIdentity(origId);
4572 }
4573 }
4574 }
4575
4576 /** Return the user id of the last resumed activity. */
4577 @Override
4578 public @UserIdInt
4579 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004580 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004581 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4582 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004583 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004584 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004585 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004586 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004587 }
4588 }
4589
4590 @Override
4591 public void updateLockTaskFeatures(int userId, int flags) {
4592 final int callingUid = Binder.getCallingUid();
4593 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004594 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004595 "updateLockTaskFeatures()");
4596 }
4597 synchronized (mGlobalLock) {
4598 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4599 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004600 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004601 }
4602 }
4603
4604 @Override
4605 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4606 synchronized (mGlobalLock) {
4607 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4608 if (r == null) {
4609 return;
4610 }
4611 final long origId = Binder.clearCallingIdentity();
4612 try {
4613 r.setShowWhenLocked(showWhenLocked);
4614 } finally {
4615 Binder.restoreCallingIdentity(origId);
4616 }
4617 }
4618 }
4619
4620 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004621 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4622 synchronized (mGlobalLock) {
4623 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4624 if (r == null) {
4625 return;
4626 }
4627 final long origId = Binder.clearCallingIdentity();
4628 try {
4629 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4630 } finally {
4631 Binder.restoreCallingIdentity(origId);
4632 }
4633 }
4634 }
4635
4636 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004637 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4638 synchronized (mGlobalLock) {
4639 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4640 if (r == null) {
4641 return;
4642 }
4643 final long origId = Binder.clearCallingIdentity();
4644 try {
4645 r.setTurnScreenOn(turnScreenOn);
4646 } finally {
4647 Binder.restoreCallingIdentity(origId);
4648 }
4649 }
4650 }
4651
4652 @Override
4653 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004654 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004655 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004656 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004657 synchronized (mGlobalLock) {
4658 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4659 if (r == null) {
4660 return;
4661 }
4662 final long origId = Binder.clearCallingIdentity();
4663 try {
4664 r.registerRemoteAnimations(definition);
4665 } finally {
4666 Binder.restoreCallingIdentity(origId);
4667 }
4668 }
4669 }
4670
4671 @Override
4672 public void registerRemoteAnimationForNextActivityStart(String packageName,
4673 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004674 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004675 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004676 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004677 synchronized (mGlobalLock) {
4678 final long origId = Binder.clearCallingIdentity();
4679 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004680 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004681 packageName, adapter);
4682 } finally {
4683 Binder.restoreCallingIdentity(origId);
4684 }
4685 }
4686 }
4687
Evan Rosky966759f2019-01-15 10:33:58 -08004688 @Override
4689 public void registerRemoteAnimationsForDisplay(int displayId,
4690 RemoteAnimationDefinition definition) {
4691 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4692 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004693 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004694 synchronized (mGlobalLock) {
4695 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4696 if (display == null) {
4697 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4698 return;
4699 }
4700 final long origId = Binder.clearCallingIdentity();
4701 try {
4702 display.mDisplayContent.registerRemoteAnimations(definition);
4703 } finally {
4704 Binder.restoreCallingIdentity(origId);
4705 }
4706 }
4707 }
4708
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004709 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4710 @Override
4711 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4712 synchronized (mGlobalLock) {
4713 final long origId = Binder.clearCallingIdentity();
4714 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004715 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004716 } finally {
4717 Binder.restoreCallingIdentity(origId);
4718 }
4719 }
4720 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004721
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004722 @Override
4723 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004724 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004725 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004726 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004727 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004728 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004729 }
4730 }
4731
4732 @Override
4733 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004734 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004735 != PERMISSION_GRANTED) {
4736 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4737 + Binder.getCallingPid()
4738 + ", uid=" + Binder.getCallingUid()
4739 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4740 Slog.w(TAG, msg);
4741 throw new SecurityException(msg);
4742 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004743 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004744 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004745 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004746 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004747 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004748 }
4749 }
4750
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004751 @Override
4752 public void stopAppSwitches() {
4753 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4754 synchronized (mGlobalLock) {
4755 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004756 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004757 mDidAppSwitch = false;
4758 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4759 }
4760 }
4761
4762 @Override
4763 public void resumeAppSwitches() {
4764 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4765 synchronized (mGlobalLock) {
4766 // Note that we don't execute any pending app switches... we will
4767 // let those wait until either the timeout, or the next start
4768 // activity request.
4769 mAppSwitchesAllowedTime = 0;
4770 }
4771 }
4772
Ricky Wai906af482019-06-03 17:25:28 +01004773 long getLastStopAppSwitchesTime() {
4774 return mLastStopAppSwitchesTime;
4775 }
4776
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004777 void onStartActivitySetDidAppSwitch() {
4778 if (mDidAppSwitch) {
4779 // This is the second allowed switch since we stopped switches, so now just generally
4780 // allow switches. Use case:
4781 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4782 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4783 // anyone to switch again).
4784 mAppSwitchesAllowedTime = 0;
4785 } else {
4786 mDidAppSwitch = true;
4787 }
4788 }
4789
4790 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004791 boolean shouldDisableNonVrUiLocked() {
4792 return mVrController.shouldDisableNonVrUiLocked();
4793 }
4794
Wale Ogunwale53783742018-09-16 10:21:51 -07004795 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004796 // 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 +00004797 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004798 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004799 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4800 + " to main display for VR");
4801 mRootActivityContainer.moveStackToDisplay(
4802 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004803 }
4804 mH.post(() -> {
4805 if (!mVrController.onVrModeChanged(r)) {
4806 return;
4807 }
4808 synchronized (mGlobalLock) {
4809 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4810 mWindowManager.disableNonVrUi(disableNonVrUi);
4811 if (disableNonVrUi) {
4812 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4813 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004814 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004815 }
4816 }
4817 });
4818 }
4819
Wale Ogunwale53783742018-09-16 10:21:51 -07004820 @Override
4821 public int getPackageScreenCompatMode(String packageName) {
4822 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4823 synchronized (mGlobalLock) {
4824 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4825 }
4826 }
4827
4828 @Override
4829 public void setPackageScreenCompatMode(String packageName, int mode) {
4830 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4831 "setPackageScreenCompatMode");
4832 synchronized (mGlobalLock) {
4833 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4834 }
4835 }
4836
4837 @Override
4838 public boolean getPackageAskScreenCompat(String packageName) {
4839 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4840 synchronized (mGlobalLock) {
4841 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4842 }
4843 }
4844
4845 @Override
4846 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4847 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4848 "setPackageAskScreenCompat");
4849 synchronized (mGlobalLock) {
4850 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4851 }
4852 }
4853
Wale Ogunwale64258362018-10-16 15:13:37 -07004854 public static String relaunchReasonToString(int relaunchReason) {
4855 switch (relaunchReason) {
4856 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4857 return "window_resize";
4858 case RELAUNCH_REASON_FREE_RESIZE:
4859 return "free_resize";
4860 default:
4861 return null;
4862 }
4863 }
4864
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004865 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004866 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004867 }
4868
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004869 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004870 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004871 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4872 }
4873
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004874 boolean isKeyguardLocked() {
4875 return mKeyguardController.isKeyguardLocked();
4876 }
4877
Garfield Tan01548632018-11-27 10:15:48 -08004878 /**
4879 * Clears launch params for the given package.
4880 * @param packageNames the names of the packages of which the launch params are to be cleared
4881 */
4882 @Override
4883 public void clearLaunchParamsForPackages(List<String> packageNames) {
4884 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4885 "clearLaunchParamsForPackages");
4886 synchronized (mGlobalLock) {
4887 for (int i = 0; i < packageNames.size(); ++i) {
4888 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4889 }
4890 }
4891 }
4892
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004893 /**
4894 * Makes the display with the given id a single task instance display. I.e the display can only
4895 * contain one task.
4896 */
4897 @Override
4898 public void setDisplayToSingleTaskInstance(int displayId) {
4899 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4900 "setDisplayToSingleTaskInstance");
4901 final long origId = Binder.clearCallingIdentity();
4902 try {
4903 final ActivityDisplay display =
4904 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4905 if (display != null) {
4906 display.setDisplayToSingleTaskInstance();
4907 }
4908 } finally {
4909 Binder.restoreCallingIdentity(origId);
4910 }
4911 }
4912
Wale Ogunwale31913b52018-10-13 08:29:31 -07004913 void dumpLastANRLocked(PrintWriter pw) {
4914 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4915 if (mLastANRState == null) {
4916 pw.println(" <no ANR has occurred since boot>");
4917 } else {
4918 pw.println(mLastANRState);
4919 }
4920 }
4921
4922 void dumpLastANRTracesLocked(PrintWriter pw) {
4923 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4924
4925 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4926 if (ArrayUtils.isEmpty(files)) {
4927 pw.println(" <no ANR has occurred since boot>");
4928 return;
4929 }
4930 // Find the latest file.
4931 File latest = null;
4932 for (File f : files) {
4933 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4934 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004935 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004936 }
4937 pw.print("File: ");
4938 pw.print(latest.getName());
4939 pw.println();
4940 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4941 String line;
4942 while ((line = in.readLine()) != null) {
4943 pw.println(line);
4944 }
4945 } catch (IOException e) {
4946 pw.print("Unable to read: ");
4947 pw.print(e);
4948 pw.println();
4949 }
4950 }
4951
4952 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4953 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4954 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4955 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4956 }
4957
4958 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4959 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4960 pw.println(header);
4961
Wale Ogunwaled32da472018-11-16 07:19:28 -08004962 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004963 dumpPackage);
4964 boolean needSep = printedAnything;
4965
4966 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004967 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004968 " ResumedActivity: ");
4969 if (printed) {
4970 printedAnything = true;
4971 needSep = false;
4972 }
4973
4974 if (dumpPackage == null) {
4975 if (needSep) {
4976 pw.println();
4977 }
4978 printedAnything = true;
4979 mStackSupervisor.dump(pw, " ");
4980 }
4981
4982 if (!printedAnything) {
4983 pw.println(" (nothing)");
4984 }
4985 }
4986
4987 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004988 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004989 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004990 pw.println(" ");
4991 }
4992
4993 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4994 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4995 getActivityStartController().dump(pw, "", dumpPackage);
4996 }
4997
4998 /**
4999 * There are three things that cmd can be:
5000 * - a flattened component name that matches an existing activity
5001 * - the cmd arg isn't the flattened component name of an existing activity:
5002 * dump all activity whose component contains the cmd as a substring
5003 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005004 * <p>
5005 * The caller should not hold lock when calling this method because it will wait for the
5006 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005007 *
5008 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5009 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5010 */
5011 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5012 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5013 ArrayList<ActivityRecord> activities;
5014
5015 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005016 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005017 dumpFocusedStackOnly);
5018 }
5019
5020 if (activities.size() <= 0) {
5021 return false;
5022 }
5023
5024 String[] newArgs = new String[args.length - opti];
5025 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5026
Louis Changcdec0802019-11-11 11:45:07 +08005027 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005028 boolean needSep = false;
5029 for (int i = activities.size() - 1; i >= 0; i--) {
5030 ActivityRecord r = activities.get(i);
5031 if (needSep) {
5032 pw.println();
5033 }
5034 needSep = true;
5035 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005036 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005037 if (lastTask != task) {
5038 lastTask = task;
5039 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005040 pw.print(" id="); pw.print(lastTask.mTaskId);
5041 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005042 if (dumpAll) {
5043 lastTask.dump(pw, " ");
5044 }
5045 }
5046 }
5047 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5048 }
5049 return true;
5050 }
5051
5052 /**
5053 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5054 * there is a thread associated with the activity.
5055 */
5056 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5057 final ActivityRecord r, String[] args, boolean dumpAll) {
5058 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005059 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005060 synchronized (mGlobalLock) {
5061 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5062 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5063 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005064 if (r.hasProcess()) {
5065 pw.println(r.app.getPid());
5066 appThread = r.app.getThread();
5067 } else {
5068 pw.println("(not running)");
5069 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005070 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005071 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005072 }
5073 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005074 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005075 // flush anything that is already in the PrintWriter since the thread is going
5076 // to write to the file descriptor directly
5077 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005078 try (TransferPipe tp = new TransferPipe()) {
5079 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5080 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005081 } catch (IOException e) {
5082 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5083 } catch (RemoteException e) {
5084 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5085 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005086 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005087 }
5088
sanryhuang498e77e2018-12-06 14:57:01 +08005089 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5090 boolean testPssMode) {
5091 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5092 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5093 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005094 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005095 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5096 st.toString());
5097 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005098 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5099 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5100 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005101 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5102 testPssMode);
5103 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005104 }
5105
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005106 int getCurrentUserId() {
5107 return mAmInternal.getCurrentUserId();
5108 }
5109
5110 private void enforceNotIsolatedCaller(String caller) {
5111 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5112 throw new SecurityException("Isolated process not allowed to call " + caller);
5113 }
5114 }
5115
Wale Ogunwalef6733932018-06-27 05:14:34 -07005116 public Configuration getConfiguration() {
5117 Configuration ci;
5118 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005119 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005120 ci.userSetLocale = false;
5121 }
5122 return ci;
5123 }
5124
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005125 /**
5126 * Current global configuration information. Contains general settings for the entire system,
5127 * also corresponds to the merged configuration of the default display.
5128 */
5129 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005130 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005131 }
5132
5133 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5134 boolean initLocale) {
5135 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5136 }
5137
5138 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5139 boolean initLocale, boolean deferResume) {
5140 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5141 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5142 UserHandle.USER_NULL, deferResume);
5143 }
5144
Wale Ogunwale59507092018-10-29 09:00:30 -07005145 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005146 final long origId = Binder.clearCallingIdentity();
5147 try {
5148 synchronized (mGlobalLock) {
5149 updateConfigurationLocked(values, null, false, true, userId,
5150 false /* deferResume */);
5151 }
5152 } finally {
5153 Binder.restoreCallingIdentity(origId);
5154 }
5155 }
5156
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005157 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5158 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5159 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5160 deferResume, null /* result */);
5161 }
5162
5163 /**
5164 * Do either or both things: (1) change the current configuration, and (2)
5165 * make sure the given activity is running with the (now) current
5166 * configuration. Returns true if the activity has been left running, or
5167 * false if <var>starting</var> is being destroyed to match the new
5168 * configuration.
5169 *
5170 * @param userId is only used when persistent parameter is set to true to persist configuration
5171 * for that particular user
5172 */
5173 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5174 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5175 ActivityTaskManagerService.UpdateConfigurationResult result) {
5176 int changes = 0;
5177 boolean kept = true;
5178
Riddle Hsua0022cd2019-09-09 21:12:41 +08005179 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005180 try {
5181 if (values != null) {
5182 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5183 deferResume);
5184 }
5185
5186 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5187 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005188 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005189 }
5190
5191 if (result != null) {
5192 result.changes = changes;
5193 result.activityRelaunched = !kept;
5194 }
5195 return kept;
5196 }
5197
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005198 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005199 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005200 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005201
5202 final ActivityDisplay defaultDisplay =
5203 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5204
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005205 mTempConfig.setTo(getGlobalConfiguration());
5206 final int changes = mTempConfig.updateFrom(values);
5207 if (changes == 0) {
5208 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5209 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5210 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5211 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005212 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005213 return 0;
5214 }
5215
5216 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5217 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005218 writeConfigurationChanged(changes);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005219 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5220 values.colorMode,
5221 values.densityDpi,
5222 values.fontScale,
5223 values.hardKeyboardHidden,
5224 values.keyboard,
5225 values.keyboardHidden,
5226 values.mcc,
5227 values.mnc,
5228 values.navigation,
5229 values.navigationHidden,
5230 values.orientation,
5231 values.screenHeightDp,
5232 values.screenLayout,
5233 values.screenWidthDp,
5234 values.smallestScreenWidthDp,
5235 values.touchscreen,
5236 values.uiMode);
5237
5238
5239 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5240 final LocaleList locales = values.getLocales();
5241 int bestLocaleIndex = 0;
5242 if (locales.size() > 1) {
5243 if (mSupportedSystemLocales == null) {
5244 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5245 }
5246 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5247 }
5248 SystemProperties.set("persist.sys.locale",
5249 locales.get(bestLocaleIndex).toLanguageTag());
5250 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005251
5252 final Message m = PooledLambda.obtainMessage(
5253 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5254 locales.get(bestLocaleIndex));
5255 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005256 }
5257
Yunfan Chen75157d72018-07-27 14:47:21 +09005258 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005259
5260 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005261 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005262
5263 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5264 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005265 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005266
5267 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005268 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005269
5270 AttributeCache ac = AttributeCache.instance();
5271 if (ac != null) {
5272 ac.updateConfiguration(mTempConfig);
5273 }
5274
5275 // Make sure all resources in our process are updated right now, so that anyone who is going
5276 // to retrieve resource values after we return will be sure to get the new ones. This is
5277 // especially important during boot, where the first config change needs to guarantee all
5278 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005279 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005280
5281 // We need another copy of global config because we're scheduling some calls instead of
5282 // running them in place. We need to be sure that object we send will be handled unchanged.
5283 final Configuration configCopy = new Configuration(mTempConfig);
5284 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005285 final Message msg = PooledLambda.obtainMessage(
5286 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5287 this, userId, configCopy);
5288 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005289 }
5290
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005291 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5292 for (int i = pidMap.size() - 1; i >= 0; i--) {
5293 final int pid = pidMap.keyAt(i);
5294 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005295 if (DEBUG_CONFIGURATION) {
5296 Slog.v(TAG_CONFIGURATION, "Update process config of "
5297 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005298 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005299 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005300 }
5301
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005302 final Message msg = PooledLambda.obtainMessage(
5303 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5304 mAmInternal, changes, initLocale);
5305 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005306
5307 // Override configuration of the default display duplicates global config, so we need to
5308 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005309 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5310 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005311
5312 return changes;
5313 }
5314
Riddle Hsua0022cd2019-09-09 21:12:41 +08005315 /** @see WindowSurfacePlacer#deferLayout */
5316 void deferWindowLayout() {
5317 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5318 // Reset the reasons at the first entrance because we only care about the changes in the
5319 // deferred scope.
5320 mLayoutReasons = 0;
5321 }
5322
5323 mWindowManager.mWindowPlacerLocked.deferLayout();
5324 }
5325
5326 /** @see WindowSurfacePlacer#continueLayout */
5327 void continueWindowLayout() {
5328 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5329 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5330 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5331 }
5332 }
5333
5334 /**
5335 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5336 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5337 * defer count is gone.
5338 */
5339 void addWindowLayoutReasons(@LayoutReason int reasons) {
5340 mLayoutReasons |= reasons;
5341 }
5342
Wale Ogunwalef6733932018-06-27 05:14:34 -07005343 private void updateEventDispatchingLocked(boolean booted) {
5344 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5345 }
5346
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005347 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5348 final ContentResolver resolver = mContext.getContentResolver();
5349 Settings.System.putConfigurationForUser(resolver, config, userId);
5350 }
5351
5352 private void sendLocaleToMountDaemonMsg(Locale l) {
5353 try {
5354 IBinder service = ServiceManager.getService("mount");
5355 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5356 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5357 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5358 } catch (RemoteException e) {
5359 Log.e(TAG, "Error storing locale for decryption UI", e);
5360 }
5361 }
5362
Alison Cichowlas3e340502018-08-07 17:15:01 -04005363 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5364 mStartActivitySources.remove(permissionToken);
5365 mExpiredStartAsCallerTokens.add(permissionToken);
5366 }
5367
5368 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5369 mExpiredStartAsCallerTokens.remove(permissionToken);
5370 }
5371
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005372 boolean isActivityStartsLoggingEnabled() {
5373 return mAmInternal.isActivityStartsLoggingEnabled();
5374 }
5375
Michal Karpinski8596ded2018-11-14 14:43:48 +00005376 boolean isBackgroundActivityStartsEnabled() {
5377 return mAmInternal.isBackgroundActivityStartsEnabled();
5378 }
5379
Wale Ogunwalef6733932018-06-27 05:14:34 -07005380 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005381 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005382 mWindowManager.enableScreenAfterBoot();
5383
5384 synchronized (mGlobalLock) {
5385 updateEventDispatchingLocked(booted);
5386 }
5387 }
5388
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005389 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5390 if (r == null || !r.hasProcess()) {
5391 return KEY_DISPATCHING_TIMEOUT_MS;
5392 }
5393 return getInputDispatchingTimeoutLocked(r.app);
5394 }
5395
5396 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005397 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005398 }
5399
Wale Ogunwalef6733932018-06-27 05:14:34 -07005400 /**
5401 * Decide based on the configuration whether we should show the ANR,
5402 * crash, etc dialogs. The idea is that if there is no affordance to
5403 * press the on-screen buttons, or the user experience would be more
5404 * greatly impacted than the crash itself, we shouldn't show the dialog.
5405 *
5406 * A thought: SystemUI might also want to get told about this, the Power
5407 * dialog / global actions also might want different behaviors.
5408 */
5409 private void updateShouldShowDialogsLocked(Configuration config) {
5410 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5411 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5412 && config.navigation == Configuration.NAVIGATION_NONAV);
5413 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5414 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5415 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5416 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5417 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5418 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5419 HIDE_ERROR_DIALOGS, 0) != 0;
5420 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5421 }
5422
5423 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5424 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5425 FONT_SCALE, 1.0f, userId);
5426
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005427 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005428 if (getGlobalConfiguration().fontScale == scaleFactor) {
5429 return;
5430 }
5431
5432 final Configuration configuration
5433 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5434 configuration.fontScale = scaleFactor;
5435 updatePersistentConfiguration(configuration, userId);
5436 }
5437 }
5438
5439 // Actually is sleeping or shutting down or whatever else in the future
5440 // is an inactive state.
5441 boolean isSleepingOrShuttingDownLocked() {
5442 return isSleepingLocked() || mShuttingDown;
5443 }
5444
5445 boolean isSleepingLocked() {
5446 return mSleeping;
5447 }
5448
Riddle Hsu16567132018-08-16 21:37:47 +08005449 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005450 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005451 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005452 if (task.isActivityTypeStandard()) {
5453 if (mCurAppTimeTracker != r.appTimeTracker) {
5454 // We are switching app tracking. Complete the current one.
5455 if (mCurAppTimeTracker != null) {
5456 mCurAppTimeTracker.stop();
5457 mH.obtainMessage(
5458 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005459 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005460 mCurAppTimeTracker = null;
5461 }
5462 if (r.appTimeTracker != null) {
5463 mCurAppTimeTracker = r.appTimeTracker;
5464 startTimeTrackingFocusedActivityLocked();
5465 }
5466 } else {
5467 startTimeTrackingFocusedActivityLocked();
5468 }
5469 } else {
5470 r.appTimeTracker = null;
5471 }
5472 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5473 // TODO: Probably not, because we don't want to resume voice on switching
5474 // back to this activity
5475 if (task.voiceInteractor != null) {
5476 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5477 } else {
5478 finishRunningVoiceLocked();
5479
5480 if (mLastResumedActivity != null) {
5481 final IVoiceInteractionSession session;
5482
Louis Changcdec0802019-11-11 11:45:07 +08005483 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005484 if (lastResumedActivityTask != null
5485 && lastResumedActivityTask.voiceSession != null) {
5486 session = lastResumedActivityTask.voiceSession;
5487 } else {
5488 session = mLastResumedActivity.voiceSession;
5489 }
5490
5491 if (session != null) {
5492 // We had been in a voice interaction session, but now focused has
5493 // move to something different. Just finish the session, we can't
5494 // return to it and retain the proper state and synchronization with
5495 // the voice interaction service.
5496 finishVoiceTask(session);
5497 }
5498 }
5499 }
5500
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005501 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5502 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005503 }
5504 updateResumedAppTrace(r);
5505 mLastResumedActivity = r;
5506
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005507 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005508
5509 applyUpdateLockStateLocked(r);
5510 applyUpdateVrModeLocked(r);
5511
Jeff Changd136e772019-11-05 20:33:52 +08005512 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005513 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005514 r == null ? "NULL" : r.shortComponentName,
5515 reason);
5516 }
5517
5518 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5519 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005520 final ActivityTaskManagerInternal.SleepToken token =
5521 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005522 updateSleepIfNeededLocked();
5523 return token;
5524 }
5525 }
5526
5527 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005528 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005529 final boolean wasSleeping = mSleeping;
5530 boolean updateOomAdj = false;
5531
5532 if (!shouldSleep) {
5533 // If wasSleeping is true, we need to wake up activity manager state from when
5534 // we started sleeping. In either case, we need to apply the sleep tokens, which
5535 // will wake up stacks or put them to sleep as appropriate.
5536 if (wasSleeping) {
5537 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005538 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5539 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005540 startTimeTrackingFocusedActivityLocked();
5541 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005542 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005543 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5544 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005545 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005546 if (wasSleeping) {
5547 updateOomAdj = true;
5548 }
5549 } else if (!mSleeping && shouldSleep) {
5550 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005551 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5552 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005553 if (mCurAppTimeTracker != null) {
5554 mCurAppTimeTracker.stop();
5555 }
5556 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005557 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005558 mStackSupervisor.goingToSleepLocked();
5559 updateResumedAppTrace(null /* resumed */);
5560 updateOomAdj = true;
5561 }
5562 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005563 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005564 }
5565 }
5566
5567 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005568 mH.removeCallbacks(mUpdateOomAdjRunnable);
5569 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005570 }
5571
Wale Ogunwale53783742018-09-16 10:21:51 -07005572 void updateCpuStats() {
5573 mH.post(mAmInternal::updateCpuStats);
5574 }
5575
Hui Yu03d12402018-12-06 18:00:37 -08005576 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5577 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005578 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5579 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005580 mH.sendMessage(m);
5581 }
5582
Hui Yu03d12402018-12-06 18:00:37 -08005583 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005584 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005585 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005586 if (task != null) {
5587 final ActivityRecord rootActivity = task.getRootActivity();
5588 if (rootActivity != null) {
5589 taskRoot = rootActivity.mActivityComponent;
5590 }
5591 }
5592
Hui Yu03d12402018-12-06 18:00:37 -08005593 final Message m = PooledLambda.obtainMessage(
5594 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005595 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005596 mH.sendMessage(m);
5597 }
5598
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005599 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5600 String hostingType) {
5601 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005602 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5603 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005604 + activity.processName);
5605 }
5606 // Post message to start process to avoid possible deadlock of calling into AMS with the
5607 // ATMS lock held.
5608 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5609 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5610 isTop, hostingType, activity.intent.getComponent());
5611 mH.sendMessage(m);
5612 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005613 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005614 }
5615 }
5616
Wale Ogunwale53783742018-09-16 10:21:51 -07005617 void setBooting(boolean booting) {
5618 mAmInternal.setBooting(booting);
5619 }
5620
5621 boolean isBooting() {
5622 return mAmInternal.isBooting();
5623 }
5624
5625 void setBooted(boolean booted) {
5626 mAmInternal.setBooted(booted);
5627 }
5628
5629 boolean isBooted() {
5630 return mAmInternal.isBooted();
5631 }
5632
5633 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5634 mH.post(() -> {
5635 if (finishBooting) {
5636 mAmInternal.finishBooting();
5637 }
5638 if (enableScreen) {
5639 mInternal.enableScreenAfterBoot(isBooted());
5640 }
5641 });
5642 }
5643
5644 void setHeavyWeightProcess(ActivityRecord root) {
5645 mHeavyWeightProcess = root.app;
5646 final Message m = PooledLambda.obtainMessage(
5647 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005648 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005649 mH.sendMessage(m);
5650 }
5651
5652 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5653 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5654 return;
5655 }
5656
5657 mHeavyWeightProcess = null;
5658 final Message m = PooledLambda.obtainMessage(
5659 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5660 proc.mUserId);
5661 mH.sendMessage(m);
5662 }
5663
5664 private void cancelHeavyWeightProcessNotification(int userId) {
5665 final INotificationManager inm = NotificationManager.getService();
5666 if (inm == null) {
5667 return;
5668 }
5669 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005670 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005671 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5672 } catch (RuntimeException e) {
5673 Slog.w(TAG, "Error canceling notification for service", e);
5674 } catch (RemoteException e) {
5675 }
5676
5677 }
5678
5679 private void postHeavyWeightProcessNotification(
5680 WindowProcessController proc, Intent intent, int userId) {
5681 if (proc == null) {
5682 return;
5683 }
5684
5685 final INotificationManager inm = NotificationManager.getService();
5686 if (inm == null) {
5687 return;
5688 }
5689
5690 try {
5691 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5692 String text = mContext.getString(R.string.heavy_weight_notification,
5693 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5694 Notification notification =
5695 new Notification.Builder(context,
5696 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5697 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5698 .setWhen(0)
5699 .setOngoing(true)
5700 .setTicker(text)
5701 .setColor(mContext.getColor(
5702 com.android.internal.R.color.system_notification_accent_color))
5703 .setContentTitle(text)
5704 .setContentText(
5705 mContext.getText(R.string.heavy_weight_notification_detail))
5706 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5707 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5708 new UserHandle(userId)))
5709 .build();
5710 try {
5711 inm.enqueueNotificationWithTag("android", "android", null,
5712 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5713 } catch (RuntimeException e) {
5714 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5715 } catch (RemoteException e) {
5716 }
5717 } catch (PackageManager.NameNotFoundException e) {
5718 Slog.w(TAG, "Unable to create context for heavy notification", e);
5719 }
5720
5721 }
5722
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005723 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5724 IBinder token, String resultWho, int requestCode, Intent[] intents,
5725 String[] resolvedTypes, int flags, Bundle bOptions) {
5726
5727 ActivityRecord activity = null;
5728 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5729 activity = ActivityRecord.isInStackLocked(token);
5730 if (activity == null) {
5731 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5732 return null;
5733 }
5734 if (activity.finishing) {
5735 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5736 return null;
5737 }
5738 }
5739
5740 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5741 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5742 bOptions);
5743 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5744 if (noCreate) {
5745 return rec;
5746 }
5747 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5748 if (activity.pendingResults == null) {
5749 activity.pendingResults = new HashSet<>();
5750 }
5751 activity.pendingResults.add(rec.ref);
5752 }
5753 return rec;
5754 }
5755
Andrii Kulian52d255c2018-07-13 11:32:19 -07005756 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005757 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005758 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005759 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5760 mCurAppTimeTracker.start(resumedActivity.packageName);
5761 }
5762 }
5763
5764 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5765 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005766 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005767 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5768 }
5769 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005770 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005771 constructResumedTraceName(resumed.packageName), 0);
5772 }
5773 mTracedResumedActivity = resumed;
5774 }
5775
5776 private String constructResumedTraceName(String packageName) {
5777 return "focused app: " + packageName;
5778 }
5779
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005780 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005781 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005782 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005783 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005784 // mainStack is null during startup.
5785 if (mainStack != null) {
5786 if (changes != 0 && starting == null) {
5787 // If the configuration changed, and the caller is not already
5788 // in the process of starting an activity, then find the top
5789 // activity to check if its configuration needs to change.
5790 starting = mainStack.topRunningActivityLocked();
5791 }
5792
5793 if (starting != null) {
5794 kept = starting.ensureActivityConfiguration(changes,
5795 false /* preserveWindow */);
5796 // And we need to make sure at this point that all other activities
5797 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005798 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005799 !PRESERVE_WINDOWS);
5800 }
5801 }
5802
5803 return kept;
5804 }
5805
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005806 void scheduleAppGcsLocked() {
5807 mH.post(() -> mAmInternal.scheduleAppGcs());
5808 }
5809
Wale Ogunwale53783742018-09-16 10:21:51 -07005810 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5811 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5812 }
5813
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005814 /**
5815 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5816 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5817 * on demand.
5818 */
5819 IPackageManager getPackageManager() {
5820 return AppGlobals.getPackageManager();
5821 }
5822
5823 PackageManagerInternal getPackageManagerInternalLocked() {
5824 if (mPmInternal == null) {
5825 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5826 }
5827 return mPmInternal;
5828 }
5829
Hai Zhangf4da9be2019-05-01 13:46:06 +08005830 PermissionPolicyInternal getPermissionPolicyInternal() {
5831 if (mPermissionPolicyInternal == null) {
5832 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5833 }
5834 return mPermissionPolicyInternal;
5835 }
5836
Wale Ogunwale008163e2018-07-23 23:11:08 -07005837 AppWarnings getAppWarningsLocked() {
5838 return mAppWarnings;
5839 }
5840
Wale Ogunwale214f3482018-10-04 11:00:47 -07005841 Intent getHomeIntent() {
5842 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5843 intent.setComponent(mTopComponent);
5844 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5845 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5846 intent.addCategory(Intent.CATEGORY_HOME);
5847 }
5848 return intent;
5849 }
5850
Chilun2ef71f72018-11-16 17:57:15 +08005851 /**
5852 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5853 * activities.
5854 *
5855 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5856 * component defined in config_secondaryHomeComponent.
5857 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5858 */
5859 Intent getSecondaryHomeIntent(String preferredPackage) {
5860 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005861 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5862 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5863 if (preferredPackage == null || useSystemProvidedLauncher) {
5864 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005865 final String secondaryHomeComponent = mContext.getResources().getString(
5866 com.android.internal.R.string.config_secondaryHomeComponent);
5867 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5868 } else {
5869 intent.setPackage(preferredPackage);
5870 }
5871 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5872 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5873 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5874 }
5875 return intent;
5876 }
5877
Wale Ogunwale214f3482018-10-04 11:00:47 -07005878 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5879 if (info == null) return null;
5880 ApplicationInfo newInfo = new ApplicationInfo(info);
5881 newInfo.initForUser(userId);
5882 return newInfo;
5883 }
5884
Wale Ogunwale9c103022018-10-18 07:44:54 -07005885 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005886 if (uid == SYSTEM_UID) {
5887 // The system gets to run in any process. If there are multiple processes with the same
5888 // uid, just pick the first (this should never happen).
5889 final SparseArray<WindowProcessController> procs =
5890 mProcessNames.getMap().get(processName);
5891 if (procs == null) return null;
5892 final int procCount = procs.size();
5893 for (int i = 0; i < procCount; i++) {
5894 final int procUid = procs.keyAt(i);
5895 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5896 // Don't use an app process or different user process for system component.
5897 continue;
5898 }
5899 return procs.valueAt(i);
5900 }
5901 }
5902
5903 return mProcessNames.get(processName, uid);
5904 }
5905
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005906 WindowProcessController getProcessController(IApplicationThread thread) {
5907 if (thread == null) {
5908 return null;
5909 }
5910
5911 final IBinder threadBinder = thread.asBinder();
5912 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5913 for (int i = pmap.size()-1; i >= 0; i--) {
5914 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5915 for (int j = procs.size() - 1; j >= 0; j--) {
5916 final WindowProcessController proc = procs.valueAt(j);
5917 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5918 return proc;
5919 }
5920 }
5921 }
5922
5923 return null;
5924 }
5925
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005926 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005927 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005928 if (proc == null) return null;
5929 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5930 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005931 }
5932 return null;
5933 }
5934
Riddle Hsua0536432019-02-16 00:38:59 +08005935 int getUidState(int uid) {
5936 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005937 }
5938
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005939 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005940 // A uid is considered to be foreground if it has a visible non-toast window.
5941 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005942 }
5943
Ricky Wai96f5c352019-04-10 18:40:17 +01005944 boolean isDeviceOwner(int uid) {
5945 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005946 }
5947
Ricky Wai96f5c352019-04-10 18:40:17 +01005948 void setDeviceOwnerUid(int uid) {
5949 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005950 }
5951
Wale Ogunwale9de19442018-10-18 19:05:03 -07005952 /**
5953 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5954 * the whitelist
5955 */
5956 String getPendingTempWhitelistTagForUidLocked(int uid) {
5957 return mPendingTempWhitelist.get(uid);
5958 }
5959
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005960 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5961 if (true || Build.IS_USER) {
5962 return;
5963 }
5964
5965 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5966 StrictMode.allowThreadDiskWrites();
5967 try {
5968 File tracesDir = new File("/data/anr");
5969 File tracesFile = null;
5970 try {
5971 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5972
5973 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005974 String timeString =
5975 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5976 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005977 sb.append(": ");
5978 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5979 sb.append(" since ");
5980 sb.append(msg);
5981 FileOutputStream fos = new FileOutputStream(tracesFile);
5982 fos.write(sb.toString().getBytes());
5983 if (app == null) {
5984 fos.write("\n*** No application process!".getBytes());
5985 }
5986 fos.close();
5987 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5988 } catch (IOException e) {
5989 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5990 return;
5991 }
5992
5993 if (app != null && app.getPid() > 0) {
5994 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5995 firstPids.add(app.getPid());
5996 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5997 }
5998
5999 File lastTracesFile = null;
6000 File curTracesFile = null;
6001 for (int i=9; i>=0; i--) {
6002 String name = String.format(Locale.US, "slow%02d.txt", i);
6003 curTracesFile = new File(tracesDir, name);
6004 if (curTracesFile.exists()) {
6005 if (lastTracesFile != null) {
6006 curTracesFile.renameTo(lastTracesFile);
6007 } else {
6008 curTracesFile.delete();
6009 }
6010 }
6011 lastTracesFile = curTracesFile;
6012 }
6013 tracesFile.renameTo(curTracesFile);
6014 } finally {
6015 StrictMode.setThreadPolicy(oldPolicy);
6016 }
6017 }
6018
Michal Karpinskida34cd42019-04-02 19:46:52 +01006019 boolean isAssociatedCompanionApp(int userId, int uid) {
6020 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6021 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006022 return false;
6023 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006024 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006025 }
6026
Issei Suzuki734bc942019-06-05 13:59:52 +02006027 void notifySingleTaskDisplayEmpty(int displayId) {
6028 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6029 }
6030
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006031 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006032 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006033
6034
Wale Ogunwale98875612018-10-12 07:53:02 -07006035 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6036 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006037
Riddle Hsud93a6c42018-11-29 21:50:06 +08006038 H(Looper looper) {
6039 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006040 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006041
6042 @Override
6043 public void handleMessage(Message msg) {
6044 switch (msg.what) {
6045 case REPORT_TIME_TRACKER_MSG: {
6046 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6047 tracker.deliverResult(mContext);
6048 } break;
6049 }
6050 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006051 }
6052
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006053 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006054 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006055
6056 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006057 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006058 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006059
6060 @Override
6061 public void handleMessage(Message msg) {
6062 switch (msg.what) {
6063 case DISMISS_DIALOG_UI_MSG: {
6064 final Dialog d = (Dialog) msg.obj;
6065 d.dismiss();
6066 break;
6067 }
6068 }
6069 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006070 }
6071
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006072 final class LocalService extends ActivityTaskManagerInternal {
6073 @Override
6074 public SleepToken acquireSleepToken(String tag, int displayId) {
6075 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006076 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006077 }
6078
6079 @Override
6080 public ComponentName getHomeActivityForUser(int userId) {
6081 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006082 final ActivityRecord homeActivity =
6083 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006084 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006085 }
6086 }
6087
6088 @Override
6089 public void onLocalVoiceInteractionStarted(IBinder activity,
6090 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6091 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006092 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006093 }
6094 }
6095
6096 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006097 public void notifySingleTaskDisplayDrawn(int displayId) {
6098 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6099 }
6100
6101 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006102 public void notifyAppTransitionFinished() {
6103 synchronized (mGlobalLock) {
6104 mStackSupervisor.notifyAppTransitionDone();
6105 }
6106 }
6107
6108 @Override
6109 public void notifyAppTransitionCancelled() {
6110 synchronized (mGlobalLock) {
6111 mStackSupervisor.notifyAppTransitionDone();
6112 }
6113 }
6114
6115 @Override
6116 public List<IBinder> getTopVisibleActivities() {
6117 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006118 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006119 }
6120 }
6121
6122 @Override
6123 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6124 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006125 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006126 }
6127 }
6128
6129 @Override
6130 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6131 Bundle bOptions) {
6132 Preconditions.checkNotNull(intents, "intents");
6133 final String[] resolvedTypes = new String[intents.length];
6134
6135 // UID of the package on user userId.
6136 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6137 // packageUid may not be initialized.
6138 int packageUid = 0;
6139 final long ident = Binder.clearCallingIdentity();
6140
6141 try {
6142 for (int i = 0; i < intents.length; i++) {
6143 resolvedTypes[i] =
6144 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6145 }
6146
6147 packageUid = AppGlobals.getPackageManager().getPackageUid(
6148 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6149 } catch (RemoteException e) {
6150 // Shouldn't happen.
6151 } finally {
6152 Binder.restoreCallingIdentity(ident);
6153 }
6154
Riddle Hsu591bf612019-02-14 17:55:31 +08006155 return getActivityStartController().startActivitiesInPackage(
6156 packageUid, packageName,
6157 intents, resolvedTypes, null /* resultTo */,
6158 SafeActivityOptions.fromBundle(bOptions), userId,
6159 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6160 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006161 }
6162
6163 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006164 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6165 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6166 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6167 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006168 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006169 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006170 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6171 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6172 userId, validateIncomingUser, originatingPendingIntent,
6173 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006174 }
6175 }
6176
6177 @Override
6178 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6179 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6180 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006181 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006182 PendingIntentRecord originatingPendingIntent,
6183 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006184 synchronized (mGlobalLock) {
6185 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6186 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6187 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006188 validateIncomingUser, originatingPendingIntent,
6189 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006190 }
6191 }
6192
6193 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006194 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6195 Intent intent, Bundle options, int userId) {
6196 return ActivityTaskManagerService.this.startActivityAsUser(
6197 caller, callerPacakge, intent,
6198 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6199 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6200 false /*validateIncomingUser*/);
6201 }
6202
6203 @Override
lumark588a3e82018-07-20 18:53:54 +08006204 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006205 synchronized (mGlobalLock) {
6206
6207 // We might change the visibilities here, so prepare an empty app transition which
6208 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006209 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006210 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006211 if (activityDisplay == null) {
6212 return;
6213 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006214 final DisplayContent dc = activityDisplay.mDisplayContent;
6215 final boolean wasTransitionSet =
6216 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006217 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006218 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006219 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006220 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006221
6222 // If there was a transition set already we don't want to interfere with it as we
6223 // might be starting it too early.
6224 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006225 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006226 }
6227 }
6228 if (callback != null) {
6229 callback.run();
6230 }
6231 }
6232
6233 @Override
6234 public void notifyKeyguardTrustedChanged() {
6235 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006236 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006237 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006238 }
6239 }
6240 }
6241
6242 /**
6243 * Called after virtual display Id is updated by
6244 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6245 * {@param vrVr2dDisplayId}.
6246 */
6247 @Override
6248 public void setVr2dDisplayId(int vr2dDisplayId) {
6249 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6250 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006251 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006252 }
6253 }
6254
6255 @Override
6256 public void setFocusedActivity(IBinder token) {
6257 synchronized (mGlobalLock) {
6258 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6259 if (r == null) {
6260 throw new IllegalArgumentException(
6261 "setFocusedActivity: No activity record matching token=" + token);
6262 }
Louis Chang19443452018-10-09 12:10:21 +08006263 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006264 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006265 }
6266 }
6267 }
6268
6269 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006270 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006271 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006272 }
6273
6274 @Override
6275 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006276 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006277 }
6278
6279 @Override
6280 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006281 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006282 }
6283
6284 @Override
6285 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6286 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6287 }
6288
6289 @Override
6290 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006291 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006292 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006293
6294 @Override
6295 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6296 synchronized (mGlobalLock) {
6297 mActiveVoiceInteractionServiceComponent = component;
6298 }
6299 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006300
6301 @Override
6302 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6303 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6304 return;
6305 }
6306 synchronized (mGlobalLock) {
6307 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6308 if (types == null) {
6309 if (uid < 0) {
6310 return;
6311 }
6312 types = new ArrayMap<>();
6313 mAllowAppSwitchUids.put(userId, types);
6314 }
6315 if (uid < 0) {
6316 types.remove(type);
6317 } else {
6318 types.put(type, uid);
6319 }
6320 }
6321 }
6322
6323 @Override
6324 public void onUserStopped(int userId) {
6325 synchronized (mGlobalLock) {
6326 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6327 mAllowAppSwitchUids.remove(userId);
6328 }
6329 }
6330
6331 @Override
6332 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6333 synchronized (mGlobalLock) {
6334 return ActivityTaskManagerService.this.isGetTasksAllowed(
6335 caller, callingPid, callingUid);
6336 }
6337 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006338
Riddle Hsua0536432019-02-16 00:38:59 +08006339 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006340 @Override
6341 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006342 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006343 mProcessNames.put(proc.mName, proc.mUid, proc);
6344 }
6345 }
6346
Riddle Hsua0536432019-02-16 00:38:59 +08006347 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006348 @Override
6349 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006350 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006351 mProcessNames.remove(name, uid);
6352 }
6353 }
6354
Riddle Hsua0536432019-02-16 00:38:59 +08006355 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006356 @Override
6357 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006358 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006359 if (proc == mHomeProcess) {
6360 mHomeProcess = null;
6361 }
6362 if (proc == mPreviousProcess) {
6363 mPreviousProcess = null;
6364 }
6365 }
6366 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006367
Riddle Hsua0536432019-02-16 00:38:59 +08006368 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006369 @Override
6370 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006371 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006372 return mTopProcessState;
6373 }
6374 }
6375
Riddle Hsua0536432019-02-16 00:38:59 +08006376 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006377 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006378 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006379 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006380 return proc == mHeavyWeightProcess;
6381 }
6382 }
6383
Riddle Hsua0536432019-02-16 00:38:59 +08006384 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006385 @Override
6386 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006387 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006388 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6389 }
6390 }
6391
6392 @Override
6393 public void finishHeavyWeightApp() {
6394 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006395 if (mHeavyWeightProcess != null) {
6396 mHeavyWeightProcess.finishActivities();
6397 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006398 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6399 mHeavyWeightProcess);
6400 }
6401 }
6402
Riddle Hsua0536432019-02-16 00:38:59 +08006403 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006404 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006405 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006406 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006407 return isSleepingLocked();
6408 }
6409 }
6410
6411 @Override
6412 public boolean isShuttingDown() {
6413 synchronized (mGlobalLock) {
6414 return mShuttingDown;
6415 }
6416 }
6417
6418 @Override
6419 public boolean shuttingDown(boolean booted, int timeout) {
6420 synchronized (mGlobalLock) {
6421 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006422 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006423 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006424 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006425 return mStackSupervisor.shutdownLocked(timeout);
6426 }
6427 }
6428
6429 @Override
6430 public void enableScreenAfterBoot(boolean booted) {
6431 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006432 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006433 mWindowManager.enableScreenAfterBoot();
6434 updateEventDispatchingLocked(booted);
6435 }
6436 }
6437
6438 @Override
6439 public boolean showStrictModeViolationDialog() {
6440 synchronized (mGlobalLock) {
6441 return mShowDialogs && !mSleeping && !mShuttingDown;
6442 }
6443 }
6444
6445 @Override
6446 public void showSystemReadyErrorDialogsIfNeeded() {
6447 synchronized (mGlobalLock) {
6448 try {
6449 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6450 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6451 + " data partition or your device will be unstable.");
6452 mUiHandler.post(() -> {
6453 if (mShowDialogs) {
6454 AlertDialog d = new BaseErrorDialog(mUiContext);
6455 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6456 d.setCancelable(false);
6457 d.setTitle(mUiContext.getText(R.string.android_system_label));
6458 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6459 d.setButton(DialogInterface.BUTTON_POSITIVE,
6460 mUiContext.getText(R.string.ok),
6461 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6462 d.show();
6463 }
6464 });
6465 }
6466 } catch (RemoteException e) {
6467 }
6468
6469 if (!Build.isBuildConsistent()) {
6470 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6471 mUiHandler.post(() -> {
6472 if (mShowDialogs) {
6473 AlertDialog d = new BaseErrorDialog(mUiContext);
6474 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6475 d.setCancelable(false);
6476 d.setTitle(mUiContext.getText(R.string.android_system_label));
6477 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6478 d.setButton(DialogInterface.BUTTON_POSITIVE,
6479 mUiContext.getText(R.string.ok),
6480 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6481 d.show();
6482 }
6483 });
6484 }
6485 }
6486 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006487
6488 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006489 public void onProcessMapped(int pid, WindowProcessController proc) {
6490 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006491 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006492 }
6493 }
6494
6495 @Override
6496 public void onProcessUnMapped(int pid) {
6497 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006498 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006499 }
6500 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006501
6502 @Override
6503 public void onPackageDataCleared(String name) {
6504 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006505 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006506 mAppWarnings.onPackageDataCleared(name);
6507 }
6508 }
6509
6510 @Override
6511 public void onPackageUninstalled(String name) {
6512 synchronized (mGlobalLock) {
6513 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006514 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006515 }
6516 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006517
6518 @Override
6519 public void onPackageAdded(String name, boolean replacing) {
6520 synchronized (mGlobalLock) {
6521 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6522 }
6523 }
6524
6525 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006526 public void onPackageReplaced(ApplicationInfo aInfo) {
6527 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006528 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006529 }
6530 }
6531
6532 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006533 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6534 synchronized (mGlobalLock) {
6535 return compatibilityInfoForPackageLocked(ai);
6536 }
6537 }
6538
Yunfan Chen75157d72018-07-27 14:47:21 +09006539 /**
6540 * Set the corresponding display information for the process global configuration. To be
6541 * called when we need to show IME on a different display.
6542 *
6543 * @param pid The process id associated with the IME window.
6544 * @param displayId The ID of the display showing the IME.
6545 */
6546 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006547 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006548 // Don't update process-level configuration for Multi-Client IME process since other
6549 // IMEs on other displays will also receive this configuration change due to IME
6550 // services use the same application config/context.
6551 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006552
Yunfan Chen75157d72018-07-27 14:47:21 +09006553 if (pid == MY_PID || pid < 0) {
6554 if (DEBUG_CONFIGURATION) {
6555 Slog.w(TAG,
6556 "Trying to update display configuration for system/invalid process.");
6557 }
6558 return;
6559 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006560 synchronized (mGlobalLock) {
6561 final ActivityDisplay activityDisplay =
6562 mRootActivityContainer.getActivityDisplay(displayId);
6563 if (activityDisplay == null) {
6564 // Call might come when display is not yet added or has been removed.
6565 if (DEBUG_CONFIGURATION) {
6566 Slog.w(TAG, "Trying to update display configuration for non-existing "
6567 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006568 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006569 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006570 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006571 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006572 if (process == null) {
6573 if (DEBUG_CONFIGURATION) {
6574 Slog.w(TAG, "Trying to update display configuration for invalid "
6575 + "process, pid=" + pid);
6576 }
6577 return;
6578 }
lumarkddc77fb2019-06-27 22:22:23 +08006579 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006580 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6581 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006582 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006583
6584 @Override
6585 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006586 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006587 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006588 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6589 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006590 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006591 }
6592 }
6593 }
6594
6595 @Override
6596 public void clearPendingResultForActivity(IBinder activityToken,
6597 WeakReference<PendingIntentRecord> pir) {
6598 synchronized (mGlobalLock) {
6599 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6600 if (r != null && r.pendingResults != null) {
6601 r.pendingResults.remove(pir);
6602 }
6603 }
6604 }
6605
6606 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006607 public ActivityTokens getTopActivityForTask(int taskId) {
6608 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08006609 final Task task = mRootActivityContainer.anyTaskForId(taskId);
6610 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006611 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6612 + " Requested task not found");
6613 return null;
6614 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006615 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006616 if (activity == null) {
6617 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6618 + " Requested activity not found");
6619 return null;
6620 }
6621 if (!activity.attachedToProcess()) {
6622 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6623 + activity);
6624 return null;
6625 }
6626 return new ActivityTokens(activity.appToken, activity.assistToken,
6627 activity.app.getThread());
6628 }
6629 }
6630
6631 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006632 public IIntentSender getIntentSender(int type, String packageName,
6633 int callingUid, int userId, IBinder token, String resultWho,
6634 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6635 Bundle bOptions) {
6636 synchronized (mGlobalLock) {
6637 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6638 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6639 }
6640 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006641
6642 @Override
6643 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6644 synchronized (mGlobalLock) {
6645 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6646 if (r == null) {
6647 return null;
6648 }
6649 if (r.mServiceConnectionsHolder == null) {
6650 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6651 ActivityTaskManagerService.this, r);
6652 }
6653
6654 return r.mServiceConnectionsHolder;
6655 }
6656 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006657
6658 @Override
6659 public Intent getHomeIntent() {
6660 synchronized (mGlobalLock) {
6661 return ActivityTaskManagerService.this.getHomeIntent();
6662 }
6663 }
6664
6665 @Override
6666 public boolean startHomeActivity(int userId, String reason) {
6667 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006668 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006669 }
6670 }
6671
6672 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006673 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006674 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006675 synchronized (mGlobalLock) {
6676 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006677 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006678 }
Chilun8b1f1be2019-03-13 17:14:36 +08006679 }
6680
6681 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006682 public boolean startHomeOnAllDisplays(int userId, String reason) {
6683 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006684 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006685 }
6686 }
6687
Riddle Hsua0536432019-02-16 00:38:59 +08006688 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006689 @Override
6690 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006691 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006692 if (mFactoryTest == FACTORY_TEST_OFF) {
6693 return false;
6694 }
6695 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6696 && wpc.mName.equals(mTopComponent.getPackageName())) {
6697 return true;
6698 }
6699 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6700 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6701 }
6702 }
6703
6704 @Override
6705 public void updateTopComponentForFactoryTest() {
6706 synchronized (mGlobalLock) {
6707 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6708 return;
6709 }
6710 final ResolveInfo ri = mContext.getPackageManager()
6711 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6712 final CharSequence errorMsg;
6713 if (ri != null) {
6714 final ActivityInfo ai = ri.activityInfo;
6715 final ApplicationInfo app = ai.applicationInfo;
6716 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6717 mTopAction = Intent.ACTION_FACTORY_TEST;
6718 mTopData = null;
6719 mTopComponent = new ComponentName(app.packageName, ai.name);
6720 errorMsg = null;
6721 } else {
6722 errorMsg = mContext.getResources().getText(
6723 com.android.internal.R.string.factorytest_not_system);
6724 }
6725 } else {
6726 errorMsg = mContext.getResources().getText(
6727 com.android.internal.R.string.factorytest_no_action);
6728 }
6729 if (errorMsg == null) {
6730 return;
6731 }
6732
6733 mTopAction = null;
6734 mTopData = null;
6735 mTopComponent = null;
6736 mUiHandler.post(() -> {
6737 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6738 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006739 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006740 });
6741 }
6742 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006743
Riddle Hsua0536432019-02-16 00:38:59 +08006744 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006745 @Override
6746 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6747 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006748 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006749 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006750 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006751
6752 wpc.clearRecentTasks();
6753 wpc.clearActivities();
6754
6755 if (wpc.isInstrumenting()) {
6756 finishInstrumentationCallback.run();
6757 }
6758
Jorim Jaggid0752812018-10-16 16:07:20 +02006759 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006760 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006761 try {
6762 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6763 // If there was nothing to resume, and we are not already restarting
6764 // this process, but there is a visible activity that is hosted by the
6765 // process...then make sure all visible activities are running, taking
6766 // care of restarting this process.
6767 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6768 !PRESERVE_WINDOWS);
6769 }
6770 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006771 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006772 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006773 }
6774 }
6775 }
6776
6777 @Override
6778 public void closeSystemDialogs(String reason) {
6779 enforceNotIsolatedCaller("closeSystemDialogs");
6780
6781 final int pid = Binder.getCallingPid();
6782 final int uid = Binder.getCallingUid();
6783 final long origId = Binder.clearCallingIdentity();
6784 try {
6785 synchronized (mGlobalLock) {
6786 // Only allow this from foreground processes, so that background
6787 // applications can't abuse it to prevent system UI from being shown.
6788 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006789 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006790 if (!proc.isPerceptible()) {
6791 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6792 + " from background process " + proc);
6793 return;
6794 }
6795 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006796 mWindowManager.closeSystemDialogs(reason);
6797
Wale Ogunwaled32da472018-11-16 07:19:28 -08006798 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006799 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006800 // Call into AM outside the synchronized block.
6801 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006802 } finally {
6803 Binder.restoreCallingIdentity(origId);
6804 }
6805 }
6806
6807 @Override
6808 public void cleanupDisabledPackageComponents(
6809 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6810 synchronized (mGlobalLock) {
6811 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006812 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006813 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006814 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006815 mStackSupervisor.scheduleIdleLocked();
6816 }
6817
6818 // Clean-up disabled tasks
6819 getRecentTasks().cleanupDisabledPackageTasksLocked(
6820 packageName, disabledClasses, userId);
6821 }
6822 }
6823
6824 @Override
6825 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6826 int userId) {
6827 synchronized (mGlobalLock) {
6828
6829 boolean didSomething =
6830 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006831 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006832 null, doit, evenPersistent, userId);
6833 return didSomething;
6834 }
6835 }
6836
6837 @Override
6838 public void resumeTopActivities(boolean scheduleIdle) {
6839 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006840 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006841 if (scheduleIdle) {
6842 mStackSupervisor.scheduleIdleLocked();
6843 }
6844 }
6845 }
6846
Riddle Hsua0536432019-02-16 00:38:59 +08006847 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006848 @Override
6849 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006850 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006851 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6852 }
6853 }
6854
Riddle Hsua0536432019-02-16 00:38:59 +08006855 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006856 @Override
6857 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006858 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006859 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6860 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6861 }
6862 try {
6863 return mRootActivityContainer.attachApplication(wpc);
6864 } finally {
6865 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6866 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006867 }
6868 }
6869
6870 @Override
6871 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6872 try {
6873 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6874 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6875 }
6876 } catch (RemoteException ex) {
6877 throw new SecurityException("Fail to check is caller a privileged app", ex);
6878 }
6879
6880 synchronized (mGlobalLock) {
6881 final long ident = Binder.clearCallingIdentity();
6882 try {
6883 if (mAmInternal.shouldConfirmCredentials(userId)) {
6884 if (mKeyguardController.isKeyguardLocked()) {
6885 // Showing launcher to avoid user entering credential twice.
6886 startHomeActivity(currentUserId, "notifyLockedProfile");
6887 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006888 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006889 }
6890 } finally {
6891 Binder.restoreCallingIdentity(ident);
6892 }
6893 }
6894 }
6895
6896 @Override
6897 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6898 mAmInternal.enforceCallingPermission(
6899 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6900
6901 synchronized (mGlobalLock) {
6902 final long ident = Binder.clearCallingIdentity();
6903 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006904 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6905 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006906 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006907 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6908 UserHandle.CURRENT);
6909 } finally {
6910 Binder.restoreCallingIdentity(ident);
6911 }
6912 }
6913 }
6914
6915 @Override
6916 public void writeActivitiesToProto(ProtoOutputStream proto) {
6917 synchronized (mGlobalLock) {
6918 // The output proto of "activity --proto activities"
6919 // is ActivityManagerServiceDumpActivitiesProto
Jeffrey Huangcb782852019-12-05 11:28:11 -08006920 mRootActivityContainer.dumpDebug(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006921 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6922 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006923 }
6924 }
6925
6926 @Override
6927 public void saveANRState(String reason) {
6928 synchronized (mGlobalLock) {
6929 final StringWriter sw = new StringWriter();
6930 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6931 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6932 if (reason != null) {
6933 pw.println(" Reason: " + reason);
6934 }
6935 pw.println();
6936 getActivityStartController().dump(pw, " ", null);
6937 pw.println();
6938 pw.println("-------------------------------------------------------------------------------");
6939 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6940 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6941 "" /* header */);
6942 pw.println();
6943 pw.close();
6944
6945 mLastANRState = sw.toString();
6946 }
6947 }
6948
6949 @Override
6950 public void clearSavedANRState() {
6951 synchronized (mGlobalLock) {
6952 mLastANRState = null;
6953 }
6954 }
6955
6956 @Override
6957 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6958 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6959 synchronized (mGlobalLock) {
6960 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6961 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6962 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6963 dumpLastANRLocked(pw);
6964 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6965 dumpLastANRTracesLocked(pw);
6966 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6967 dumpActivityStarterLocked(pw, dumpPackage);
6968 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6969 dumpActivityContainersLocked(pw);
6970 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6971 if (getRecentTasks() != null) {
6972 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6973 }
6974 }
6975 }
6976 }
6977
6978 @Override
6979 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6980 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6981 int wakefulness) {
6982 synchronized (mGlobalLock) {
6983 if (mHomeProcess != null && (dumpPackage == null
6984 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6985 if (needSep) {
6986 pw.println();
6987 needSep = false;
6988 }
6989 pw.println(" mHomeProcess: " + mHomeProcess);
6990 }
6991 if (mPreviousProcess != null && (dumpPackage == null
6992 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6993 if (needSep) {
6994 pw.println();
6995 needSep = false;
6996 }
6997 pw.println(" mPreviousProcess: " + mPreviousProcess);
6998 }
6999 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7000 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7001 StringBuilder sb = new StringBuilder(128);
7002 sb.append(" mPreviousProcessVisibleTime: ");
7003 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7004 pw.println(sb);
7005 }
7006 if (mHeavyWeightProcess != null && (dumpPackage == null
7007 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7008 if (needSep) {
7009 pw.println();
7010 needSep = false;
7011 }
7012 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7013 }
7014 if (dumpPackage == null) {
7015 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007016 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007017 }
7018 if (dumpAll) {
7019 if (dumpPackage == null) {
7020 pw.println(" mConfigWillChange: "
7021 + getTopDisplayFocusedStack().mConfigWillChange);
7022 }
7023 if (mCompatModePackages.getPackages().size() > 0) {
7024 boolean printed = false;
7025 for (Map.Entry<String, Integer> entry
7026 : mCompatModePackages.getPackages().entrySet()) {
7027 String pkg = entry.getKey();
7028 int mode = entry.getValue();
7029 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7030 continue;
7031 }
7032 if (!printed) {
7033 pw.println(" mScreenCompatPackages:");
7034 printed = true;
7035 }
7036 pw.println(" " + pkg + ": " + mode);
7037 }
7038 }
7039 }
7040
7041 if (dumpPackage == null) {
7042 pw.println(" mWakefulness="
7043 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007044 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007045 if (mRunningVoice != null) {
7046 pw.println(" mRunningVoice=" + mRunningVoice);
7047 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7048 }
7049 pw.println(" mSleeping=" + mSleeping);
7050 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7051 pw.println(" mVrController=" + mVrController);
7052 }
7053 if (mCurAppTimeTracker != null) {
7054 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7055 }
7056 if (mAllowAppSwitchUids.size() > 0) {
7057 boolean printed = false;
7058 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7059 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7060 for (int j = 0; j < types.size(); j++) {
7061 if (dumpPackage == null ||
7062 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7063 if (needSep) {
7064 pw.println();
7065 needSep = false;
7066 }
7067 if (!printed) {
7068 pw.println(" mAllowAppSwitchUids:");
7069 printed = true;
7070 }
7071 pw.print(" User ");
7072 pw.print(mAllowAppSwitchUids.keyAt(i));
7073 pw.print(": Type ");
7074 pw.print(types.keyAt(j));
7075 pw.print(" = ");
7076 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7077 pw.println();
7078 }
7079 }
7080 }
7081 }
7082 if (dumpPackage == null) {
7083 if (mController != null) {
7084 pw.println(" mController=" + mController
7085 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7086 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007087 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7088 pw.println(" mLaunchingActivityWakeLock="
7089 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007090 }
7091
7092 return needSep;
7093 }
7094 }
7095
7096 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007097 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7098 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007099 synchronized (mGlobalLock) {
7100 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007101 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007102 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007103 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7104 if (mRunningVoice != null) {
7105 final long vrToken = proto.start(
7106 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7107 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7108 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007109 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007110 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7111 proto.end(vrToken);
7112 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007113 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007114 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007115 if (mController != null) {
7116 final long token = proto.start(CONTROLLER);
7117 proto.write(CONTROLLER, mController.toString());
7118 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7119 proto.end(token);
7120 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007121 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7122 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007123 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007124 }
7125
7126 if (mHomeProcess != null && (dumpPackage == null
7127 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007128 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007129 }
7130
7131 if (mPreviousProcess != null && (dumpPackage == null
7132 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007133 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007134 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7135 }
7136
7137 if (mHeavyWeightProcess != null && (dumpPackage == null
7138 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007139 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007140 }
7141
7142 for (Map.Entry<String, Integer> entry
7143 : mCompatModePackages.getPackages().entrySet()) {
7144 String pkg = entry.getKey();
7145 int mode = entry.getValue();
7146 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7147 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7148 proto.write(PACKAGE, pkg);
7149 proto.write(MODE, mode);
7150 proto.end(compatToken);
7151 }
7152 }
7153
7154 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007155 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007156 }
7157
7158 }
7159 }
7160
7161 @Override
7162 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7163 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7164 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007165 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7166 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007167 }
7168
7169 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007170 public void dumpForOom(PrintWriter pw) {
7171 synchronized (mGlobalLock) {
7172 pw.println(" mHomeProcess: " + mHomeProcess);
7173 pw.println(" mPreviousProcess: " + mPreviousProcess);
7174 if (mHeavyWeightProcess != null) {
7175 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7176 }
7177 }
7178 }
7179
7180 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007181 public boolean canGcNow() {
7182 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007183 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007184 }
7185 }
7186
Riddle Hsua0536432019-02-16 00:38:59 +08007187 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007188 @Override
7189 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007190 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007191 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007192 return top != null ? top.app : null;
7193 }
7194 }
7195
Riddle Hsua0536432019-02-16 00:38:59 +08007196 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007197 @Override
7198 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007199 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007200 if (mRootActivityContainer != null) {
7201 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007202 }
7203 }
7204 }
7205
7206 @Override
7207 public void scheduleDestroyAllActivities(String reason) {
7208 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007209 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007210 }
7211 }
7212
7213 @Override
7214 public void removeUser(int userId) {
7215 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007216 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007217 }
7218 }
7219
7220 @Override
7221 public boolean switchUser(int userId, UserState userState) {
7222 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007223 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007224 }
7225 }
7226
7227 @Override
7228 public void onHandleAppCrash(WindowProcessController wpc) {
7229 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007230 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007231 }
7232 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007233
7234 @Override
7235 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7236 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007237 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007238 }
7239 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007240
Riddle Hsua0536432019-02-16 00:38:59 +08007241 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007242 @Override
7243 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007244 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007245 }
7246
Riddle Hsua0536432019-02-16 00:38:59 +08007247 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007248 @Override
7249 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007250 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007251 }
7252
Riddle Hsua0536432019-02-16 00:38:59 +08007253 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007254 @Override
7255 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007256 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007257 }
7258
Riddle Hsua0536432019-02-16 00:38:59 +08007259 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007260 @Override
7261 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007262 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007263 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007264
7265 @Override
7266 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007267 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007268 mPendingTempWhitelist.put(uid, tag);
7269 }
7270 }
7271
7272 @Override
7273 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007274 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007275 mPendingTempWhitelist.remove(uid);
7276 }
7277 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007278
7279 @Override
7280 public boolean handleAppCrashInActivityController(String processName, int pid,
7281 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7282 Runnable killCrashingAppCallback) {
7283 synchronized (mGlobalLock) {
7284 if (mController == null) {
7285 return false;
7286 }
7287
7288 try {
7289 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7290 stackTrace)) {
7291 killCrashingAppCallback.run();
7292 return true;
7293 }
7294 } catch (RemoteException e) {
7295 mController = null;
7296 Watchdog.getInstance().setActivityController(null);
7297 }
7298 return false;
7299 }
7300 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007301
7302 @Override
7303 public void removeRecentTasksByPackageName(String packageName, int userId) {
7304 synchronized (mGlobalLock) {
7305 mRecentTasks.removeTasksByPackageName(packageName, userId);
7306 }
7307 }
7308
7309 @Override
7310 public void cleanupRecentTasksForUser(int userId) {
7311 synchronized (mGlobalLock) {
7312 mRecentTasks.cleanupLocked(userId);
7313 }
7314 }
7315
7316 @Override
7317 public void loadRecentTasksForUser(int userId) {
7318 synchronized (mGlobalLock) {
7319 mRecentTasks.loadUserRecentsLocked(userId);
7320 }
7321 }
7322
7323 @Override
7324 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7325 synchronized (mGlobalLock) {
7326 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7327 }
7328 }
7329
7330 @Override
7331 public void flushRecentTasks() {
7332 mRecentTasks.flush();
7333 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007334
7335 @Override
7336 public WindowProcessController getHomeProcess() {
7337 synchronized (mGlobalLock) {
7338 return mHomeProcess;
7339 }
7340 }
7341
7342 @Override
7343 public WindowProcessController getPreviousProcess() {
7344 synchronized (mGlobalLock) {
7345 return mPreviousProcess;
7346 }
7347 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007348
7349 @Override
7350 public void clearLockedTasks(String reason) {
7351 synchronized (mGlobalLock) {
7352 getLockTaskController().clearLockedTasks(reason);
7353 }
7354 }
7355
7356 @Override
7357 public void updateUserConfiguration() {
7358 synchronized (mGlobalLock) {
7359 final Configuration configuration = new Configuration(getGlobalConfiguration());
7360 final int currentUserId = mAmInternal.getCurrentUserId();
7361 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7362 configuration, currentUserId, Settings.System.canWrite(mContext));
7363 updateConfigurationLocked(configuration, null /* starting */,
7364 false /* initLocale */, false /* persistent */, currentUserId,
7365 false /* deferResume */);
7366 }
7367 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007368
7369 @Override
7370 public boolean canShowErrorDialogs() {
7371 synchronized (mGlobalLock) {
7372 return mShowDialogs && !mSleeping && !mShuttingDown
7373 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7374 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7375 mAmInternal.getCurrentUserId())
7376 && !(UserManager.isDeviceInDemoMode(mContext)
7377 && mAmInternal.getCurrentUser().isDemo());
7378 }
7379 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007380
7381 @Override
7382 public void setProfileApp(String profileApp) {
7383 synchronized (mGlobalLock) {
7384 mProfileApp = profileApp;
7385 }
7386 }
7387
7388 @Override
7389 public void setProfileProc(WindowProcessController wpc) {
7390 synchronized (mGlobalLock) {
7391 mProfileProc = wpc;
7392 }
7393 }
7394
7395 @Override
7396 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7397 synchronized (mGlobalLock) {
7398 mProfilerInfo = profilerInfo;
7399 }
7400 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007401
7402 @Override
7403 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7404 synchronized (mGlobalLock) {
7405 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7406 }
7407 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007408
7409 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007410 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7411 boolean reducedResolution) {
7412 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7413 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007414 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007415
7416 @Override
7417 public boolean isUidForeground(int uid) {
7418 synchronized (mGlobalLock) {
7419 return ActivityTaskManagerService.this.isUidForeground(uid);
7420 }
7421 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007422
7423 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007424 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007425 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007426 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007427 }
7428 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007429
7430 @Override
7431 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007432 // Translate package names into UIDs
7433 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007434 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007435 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7436 if (uid >= 0) {
7437 result.add(uid);
7438 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007439 }
7440 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007441 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007442 }
7443 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007444 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007445}