blob: df03940412512bed8945c4057fbcd313a72dca8a [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 Ogunwale6767eae2018-05-03 15:52:51 -0700223import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700224import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700225import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700226import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700227import android.view.IRecentsAnimationRunner;
228import android.view.RemoteAnimationAdapter;
229import android.view.RemoteAnimationDefinition;
Evan Roskyddedfd42019-10-04 13:38:38 -0700230import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700231import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700232
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700234import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700236import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700238import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700241import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
242import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700244import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700245import com.android.internal.policy.IKeyguardDismissCallback;
246import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700247import com.android.internal.util.ArrayUtils;
248import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700249import com.android.internal.util.Preconditions;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800250import com.android.internal.util.function.pooled.PooledConsumer;
251import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700252import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700253import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.LocalServices;
255import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700256import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800257import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700258import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700259import com.android.server.am.ActivityManagerService;
260import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
261import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
262import com.android.server.am.AppTimeTracker;
263import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700264import com.android.server.am.PendingIntentController;
265import com.android.server.am.PendingIntentRecord;
266import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900267import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700268import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700269import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700270import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800271import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700272import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700276import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700278import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700280import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700281import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700282import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800283import java.lang.annotation.ElementType;
284import java.lang.annotation.Retention;
285import java.lang.annotation.RetentionPolicy;
286import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700287import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700288import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700290import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700291import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400292import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700293import java.util.HashSet;
Evan Roskyddedfd42019-10-04 13:38:38 -0700294import java.util.Iterator;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700295import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700296import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700297import java.util.Map;
298import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700299
300/**
301 * System service for managing activities and their containers (task, stacks, displays,... ).
302 *
303 * {@hide}
304 */
305public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700306 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700307 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700308 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
309 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
310 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
311 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
312 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700313 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700314
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700316 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700318 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100319 // How long we permit background activity starts after an activity in the process
320 // started or finished.
321 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700322
Wale Ogunwale98875612018-10-12 07:53:02 -0700323 /** Used to indicate that an app transition should be animated. */
324 static final boolean ANIMATE = true;
325
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700326 /** Hardware-reported OpenGLES version. */
327 final int GL_ES_VERSION;
328
Wale Ogunwale31913b52018-10-13 08:29:31 -0700329 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
330 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
331 public static final String DUMP_LASTANR_CMD = "lastanr" ;
332 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
333 public static final String DUMP_STARTER_CMD = "starter" ;
334 public static final String DUMP_CONTAINERS_CMD = "containers" ;
335 public static final String DUMP_RECENTS_CMD = "recents" ;
336 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
337
Wale Ogunwale64258362018-10-16 15:13:37 -0700338 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
339 public static final int RELAUNCH_REASON_NONE = 0;
340 /** This activity is being relaunched due to windowing mode change. */
341 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
342 /** This activity is being relaunched due to a free-resize operation. */
343 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
344
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700345 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700346
Wale Ogunwalef6733932018-06-27 05:14:34 -0700347 /**
348 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
349 * change at runtime. Use mContext for non-UI purposes.
350 */
351 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700352 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700353 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700354 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700355 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700356 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700357 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800358 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800359 @VisibleForTesting
360 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700361 PowerManagerInternal mPowerManagerInternal;
362 private UsageStatsManagerInternal mUsageStatsInternal;
363
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700364 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700365 IntentFirewall mIntentFirewall;
366
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700367 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800368 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800369 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700370 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800371 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
372 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
373 *
374 * @see WindowManagerThreadPriorityBooster
375 */
376 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700377 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800378 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700379 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700380 private UserManagerService mUserManager;
381 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700382 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800383 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700384 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700385 /** All processes currently running that might have a window organized by name. */
386 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100387 /** All processes we currently have running mapped by pid and uid */
388 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700389 /** This is the process holding what we currently consider to be the "home" activity. */
390 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700391 /** The currently running heavy-weight process, if any. */
392 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700393 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700394 /**
395 * This is the process holding the activity the user last visited that is in a different process
396 * from the one they are currently in.
397 */
398 WindowProcessController mPreviousProcess;
399 /** The time at which the previous process was last visible. */
400 long mPreviousProcessVisibleTime;
401
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700402 /** List of intents that were used to start the most recent tasks. */
403 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700404 /** State of external calls telling us if the device is awake or asleep. */
405 private boolean mKeyguardShown = false;
406
407 // Wrapper around VoiceInteractionServiceManager
408 private AssistUtils mAssistUtils;
409
410 // VoiceInteraction session ID that changes for each new request except when
411 // being called for multi-window assist in a single session.
412 private int mViSessionId = 1000;
413
414 // How long to wait in getAssistContextExtras for the activity and foreground services
415 // to respond with the result.
416 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
417
418 // How long top wait when going through the modern assist (which doesn't need to block
419 // on getting this result before starting to launch its UI).
420 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
421
422 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
423 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
424
Alison Cichowlas3e340502018-08-07 17:15:01 -0400425 // Permission tokens are used to temporarily granted a trusted app the ability to call
426 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
427 // showing any appropriate error messages to the user.
428 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
429 10 * MINUTE_IN_MILLIS;
430
431 // How long before the service actually expires a token. This is slightly longer than
432 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
433 // expiration exception.
434 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
435 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
436
437 // How long the service will remember expired tokens, for the purpose of providing error
438 // messaging when a client uses an expired token.
439 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
440 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
441
442 // Activity tokens of system activities that are delegating their call to
443 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
444 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
445
446 // Permission tokens that have expired, but we remember for error reporting.
447 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
448
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700449 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
450
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700451 // Keeps track of the active voice interaction service component, notified from
452 // VoiceInteractionManagerService
453 ComponentName mActiveVoiceInteractionServiceComponent;
454
Michal Karpinskida34cd42019-04-02 19:46:52 +0100455 // A map userId and all its companion app uids
456 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000457
Wale Ogunwalee2172292018-10-25 10:11:10 -0700458 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700459 KeyguardController mKeyguardController;
460 private final ClientLifecycleManager mLifecycleManager;
461 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700462 /** The controller for all operations related to locktask. */
463 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700464 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700465
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700466 boolean mSuppressResizeConfigChanges;
467
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700468 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700469 new UpdateConfigurationResult();
470
471 static final class UpdateConfigurationResult {
472 // Configuration changes that were updated.
473 int changes;
474 // If the activity was relaunched to match the new configuration.
475 boolean activityRelaunched;
476
477 void reset() {
478 changes = 0;
479 activityRelaunched = false;
480 }
481 }
482
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700483 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700484 private int mConfigurationSeq;
485 // To cache the list of supported system locales
486 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700487
488 /**
489 * Temp object used when global and/or display override configuration is updated. It is also
490 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
491 * anyone...
492 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700493 private Configuration mTempConfig = new Configuration();
494
Wale Ogunwalef6733932018-06-27 05:14:34 -0700495 /** Temporary to avoid allocations. */
496 final StringBuilder mStringBuilder = new StringBuilder(256);
497
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700498 // Amount of time after a call to stopAppSwitches() during which we will
499 // prevent further untrusted switches from happening.
500 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
501
502 /**
503 * The time at which we will allow normal application switches again,
504 * after a call to {@link #stopAppSwitches()}.
505 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700506 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700507 /**
508 * This is set to true after the first switch after mAppSwitchesAllowedTime
509 * is set; any switches after that will clear the time.
510 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700511 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700512
Ricky Wai906af482019-06-03 17:25:28 +0100513 /**
514 * Last stop app switches time, apps finished before this time cannot start background activity
515 * even if they are in grace period.
516 */
517 private long mLastStopAppSwitchesTime;
518
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700519 IActivityController mController = null;
520 boolean mControllerIsAMonkey = false;
521
Wale Ogunwale214f3482018-10-04 11:00:47 -0700522 final int mFactoryTest;
523
524 /** Used to control how we initialize the service. */
525 ComponentName mTopComponent;
526 String mTopAction = Intent.ACTION_MAIN;
527 String mTopData;
528
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800529 /** Profiling app information. */
530 String mProfileApp = null;
531 WindowProcessController mProfileProc = null;
532 ProfilerInfo mProfilerInfo = null;
533
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700534 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700535 * Dump of the activity state at the time of the last ANR. Cleared after
536 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
537 */
538 String mLastANRState;
539
540 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700541 * Used to retain an update lock when the foreground activity is in
542 * immersive mode.
543 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700544 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700545
546 /**
547 * Packages that are being allowed to perform unrestricted app switches. Mapping is
548 * User -> Type -> uid.
549 */
550 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
551
552 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700553 private int mThumbnailWidth;
554 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700555
556 /**
557 * Flag that indicates if multi-window is enabled.
558 *
559 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
560 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
561 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
562 * At least one of the forms of multi-window must be enabled in order for this flag to be
563 * initialized to 'true'.
564 *
565 * @see #mSupportsSplitScreenMultiWindow
566 * @see #mSupportsFreeformWindowManagement
567 * @see #mSupportsPictureInPicture
568 * @see #mSupportsMultiDisplay
569 */
570 boolean mSupportsMultiWindow;
571 boolean mSupportsSplitScreenMultiWindow;
572 boolean mSupportsFreeformWindowManagement;
573 boolean mSupportsPictureInPicture;
574 boolean mSupportsMultiDisplay;
575 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700576 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700577
578 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
579
580 // VR Vr2d Display Id.
581 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700582
Wale Ogunwalef6733932018-06-27 05:14:34 -0700583 /**
584 * Set while we are wanting to sleep, to prevent any
585 * activities from being started/resumed.
586 *
587 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
588 *
589 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
590 * while in the sleep state until there is a pending transition out of sleep, in which case
591 * mSleeping is set to false, and remains false while awake.
592 *
593 * Whether mSleeping can quickly toggled between true/false without the device actually
594 * display changing states is undefined.
595 */
596 private boolean mSleeping = false;
597
598 /**
599 * The process state used for processes that are running the top activities.
600 * This changes between TOP and TOP_SLEEPING to following mSleeping.
601 */
602 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
603
Riddle Hsua0022cd2019-09-09 21:12:41 +0800604 @Retention(RetentionPolicy.SOURCE)
605 @IntDef({
606 LAYOUT_REASON_CONFIG_CHANGED,
607 LAYOUT_REASON_VISIBILITY_CHANGED,
608 })
609 @interface LayoutReason {}
610 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
611 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
612
613 /** The reasons to perform surface placement. */
614 @LayoutReason
615 private int mLayoutReasons;
616
Wale Ogunwalef6733932018-06-27 05:14:34 -0700617 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
618 // automatically. Important for devices without direct input devices.
619 private boolean mShowDialogs = true;
620
621 /** Set if we are shutting down the system, similar to sleeping. */
622 boolean mShuttingDown = false;
623
624 /**
625 * We want to hold a wake lock while running a voice interaction session, since
626 * this may happen with the screen off and we need to keep the CPU running to
627 * be able to continue to interact with the user.
628 */
629 PowerManager.WakeLock mVoiceWakeLock;
630
631 /**
632 * Set while we are running a voice interaction. This overrides sleeping while it is active.
633 */
634 IVoiceInteractionSession mRunningVoice;
635
636 /**
637 * The last resumed activity. This is identical to the current resumed activity most
638 * of the time but could be different when we're pausing one activity before we resume
639 * another activity.
640 */
641 ActivityRecord mLastResumedActivity;
642
643 /**
644 * The activity that is currently being traced as the active resumed activity.
645 *
646 * @see #updateResumedAppTrace
647 */
648 private @Nullable ActivityRecord mTracedResumedActivity;
649
650 /** If non-null, we are tracking the time the user spends in the currently focused app. */
651 AppTimeTracker mCurAppTimeTracker;
652
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700653 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700654
Wale Ogunwale53783742018-09-16 10:21:51 -0700655 /**
656 * Packages that the user has asked to have run in screen size
657 * compatibility mode instead of filling the screen.
658 */
659 CompatModePackages mCompatModePackages;
660
Wale Ogunwalef6733932018-06-27 05:14:34 -0700661 private FontScaleSettingObserver mFontScaleSettingObserver;
662
Ricky Wai96f5c352019-04-10 18:40:17 +0100663 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000664
Wale Ogunwalef6733932018-06-27 05:14:34 -0700665 private final class FontScaleSettingObserver extends ContentObserver {
666 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
667 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
668
669 public FontScaleSettingObserver() {
670 super(mH);
671 final ContentResolver resolver = mContext.getContentResolver();
672 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
673 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
674 UserHandle.USER_ALL);
675 }
676
677 @Override
678 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
679 if (mFontScaleUri.equals(uri)) {
680 updateFontScaleIfNeeded(userId);
681 } else if (mHideErrorDialogsUri.equals(uri)) {
682 synchronized (mGlobalLock) {
683 updateShouldShowDialogsLocked(getGlobalConfiguration());
684 }
685 }
686 }
687 }
688
Riddle Hsua0536432019-02-16 00:38:59 +0800689 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
690 @Target(ElementType.METHOD)
691 @Retention(RetentionPolicy.SOURCE)
692 @interface HotPath {
693 int NONE = 0;
694 int OOM_ADJUSTMENT = 1;
695 int LRU_UPDATE = 2;
696 int PROCESS_CHANGE = 3;
697 int caller() default NONE;
698 }
699
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800700 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
701 @Override
702 public void run() {
703 mAmInternal.updateOomAdj();
704 }
705 };
706
Charles Chen8d98dd22018-12-26 17:36:54 +0800707 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
708 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700709 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700710 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700711 mSystemThread = ActivityThread.currentActivityThread();
712 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700713 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800714 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700715 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700716 }
717
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700718 public void onSystemReady() {
719 synchronized (mGlobalLock) {
720 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
721 PackageManager.FEATURE_CANT_SAVE_STATE);
722 mAssistUtils = new AssistUtils(mContext);
723 mVrController.onSystemReady();
724 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700725 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700726 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700727 }
728
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700729 public void onInitPowerManagement() {
730 synchronized (mGlobalLock) {
731 mStackSupervisor.initPowerManagement();
732 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
733 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
734 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
735 mVoiceWakeLock.setReferenceCounted(false);
736 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700737 }
738
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700739 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700740 mFontScaleSettingObserver = new FontScaleSettingObserver();
741 }
742
Wale Ogunwale59507092018-10-29 09:00:30 -0700743 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700744 final boolean freeformWindowManagement =
745 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
746 || Settings.Global.getInt(
747 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
748
749 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
750 final boolean supportsPictureInPicture = supportsMultiWindow &&
751 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
752 final boolean supportsSplitScreenMultiWindow =
753 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
754 final boolean supportsMultiDisplay = mContext.getPackageManager()
755 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700756 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
757 final boolean forceResizable = Settings.Global.getInt(
758 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700759 final boolean sizeCompatFreeform = Settings.Global.getInt(
760 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700761
762 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900763 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700764
765 final Configuration configuration = new Configuration();
766 Settings.System.getConfiguration(resolver, configuration);
767 if (forceRtl) {
768 // This will take care of setting the correct layout direction flags
769 configuration.setLayoutDirection(configuration.locale);
770 }
771
772 synchronized (mGlobalLock) {
773 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700774 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700775 final boolean multiWindowFormEnabled = freeformWindowManagement
776 || supportsSplitScreenMultiWindow
777 || supportsPictureInPicture
778 || supportsMultiDisplay;
779 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
780 mSupportsMultiWindow = true;
781 mSupportsFreeformWindowManagement = freeformWindowManagement;
782 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
783 mSupportsPictureInPicture = supportsPictureInPicture;
784 mSupportsMultiDisplay = supportsMultiDisplay;
785 } else {
786 mSupportsMultiWindow = false;
787 mSupportsFreeformWindowManagement = false;
788 mSupportsSplitScreenMultiWindow = false;
789 mSupportsPictureInPicture = false;
790 mSupportsMultiDisplay = false;
791 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700792 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700793 // This happens before any activities are started, so we can change global configuration
794 // in-place.
795 updateConfigurationLocked(configuration, null, true);
796 final Configuration globalConfig = getGlobalConfiguration();
797 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
798
799 // Load resources only after the current configuration has been set.
800 final Resources res = mContext.getResources();
801 mThumbnailWidth = res.getDimensionPixelSize(
802 com.android.internal.R.dimen.thumbnail_width);
803 mThumbnailHeight = res.getDimensionPixelSize(
804 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700805 }
806 }
807
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800808 public WindowManagerGlobalLock getGlobalLock() {
809 return mGlobalLock;
810 }
811
Yunfan Chen585f2932019-01-29 16:04:45 +0900812 /** For test purpose only. */
813 @VisibleForTesting
814 public ActivityTaskManagerInternal getAtmInternal() {
815 return mInternal;
816 }
817
Riddle Hsud93a6c42018-11-29 21:50:06 +0800818 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
819 Looper looper) {
820 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700821 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700822 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700823 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800824 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700825 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700826 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700827
828 mTempConfig.setToDefaults();
829 mTempConfig.setLocales(LocaleList.getDefault());
830 mConfigurationSeq = mTempConfig.seq = 1;
831 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800832 mRootActivityContainer = new RootActivityContainer(this);
833 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700834
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700835 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700836 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700837 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700838 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700839 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700840 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700841 mKeyguardController = mStackSupervisor.getKeyguardController();
842 }
843
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700844 public void onActivityManagerInternalAdded() {
845 synchronized (mGlobalLock) {
846 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
847 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
848 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700849 }
850
Yunfan Chen75157d72018-07-27 14:47:21 +0900851 int increaseConfigurationSeqLocked() {
852 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
853 return mConfigurationSeq;
854 }
855
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700856 protected ActivityStackSupervisor createStackSupervisor() {
857 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
858 supervisor.initialize();
859 return supervisor;
860 }
861
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800862 protected AppWarnings createAppWarnings(
863 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
864 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
865 }
866
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700867 public void setWindowManager(WindowManagerService wm) {
868 synchronized (mGlobalLock) {
869 mWindowManager = wm;
870 mLockTaskController.setWindowManager(wm);
871 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800872 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700873 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700874 }
875
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700876 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
877 synchronized (mGlobalLock) {
878 mUsageStatsInternal = usageStatsManager;
879 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700880 }
881
Wale Ogunwalef6733932018-06-27 05:14:34 -0700882 UserManagerService getUserManager() {
883 if (mUserManager == null) {
884 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
885 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
886 }
887 return mUserManager;
888 }
889
890 AppOpsService getAppOpsService() {
891 if (mAppOpsService == null) {
892 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
893 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
894 }
895 return mAppOpsService;
896 }
897
898 boolean hasUserRestriction(String restriction, int userId) {
899 return getUserManager().hasUserRestriction(restriction, userId);
900 }
901
Michal Karpinski15486842019-04-25 17:33:42 +0100902 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
903 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700904 callingUid, callingPackage, /* featureId */ null);
Michal Karpinski15486842019-04-25 17:33:42 +0100905 if (mode == AppOpsManager.MODE_DEFAULT) {
906 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
907 == PERMISSION_GRANTED;
908 }
909 return mode == AppOpsManager.MODE_ALLOWED;
910 }
911
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700912 @VisibleForTesting
913 protected void setRecentTasks(RecentTasks recentTasks) {
914 mRecentTasks = recentTasks;
915 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700916 }
917
918 RecentTasks getRecentTasks() {
919 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700920 }
921
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700922 ClientLifecycleManager getLifecycleManager() {
923 return mLifecycleManager;
924 }
925
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700926 ActivityStartController getActivityStartController() {
927 return mActivityStartController;
928 }
929
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700930 TaskChangeNotificationController getTaskChangeNotificationController() {
931 return mTaskChangeNotificationController;
932 }
933
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700934 LockTaskController getLockTaskController() {
935 return mLockTaskController;
936 }
937
Yunfan Chen75157d72018-07-27 14:47:21 +0900938 /**
939 * Return the global configuration used by the process corresponding to the input pid. This is
940 * usually the global configuration with some overrides specific to that process.
941 */
942 Configuration getGlobalConfigurationForCallingPid() {
943 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800944 return getGlobalConfigurationForPid(pid);
945 }
946
947 /**
948 * Return the global configuration used by the process corresponding to the given pid.
949 */
950 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900951 if (pid == MY_PID || pid < 0) {
952 return getGlobalConfiguration();
953 }
954 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100955 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900956 return app != null ? app.getConfiguration() : getGlobalConfiguration();
957 }
958 }
959
960 /**
961 * Return the device configuration info used by the process corresponding to the input pid.
962 * The value is consistent with the global configuration for the process.
963 */
964 @Override
965 public ConfigurationInfo getDeviceConfigurationInfo() {
966 ConfigurationInfo config = new ConfigurationInfo();
967 synchronized (mGlobalLock) {
968 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
969 config.reqTouchScreen = globalConfig.touchscreen;
970 config.reqKeyboardType = globalConfig.keyboard;
971 config.reqNavigation = globalConfig.navigation;
972 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
973 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
974 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
975 }
976 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
977 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
978 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
979 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700980 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900981 }
982 return config;
983 }
984
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700985 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700986 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700987 }
988
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700989 public static final class Lifecycle extends SystemService {
990 private final ActivityTaskManagerService mService;
991
992 public Lifecycle(Context context) {
993 super(context);
994 mService = new ActivityTaskManagerService(context);
995 }
996
997 @Override
998 public void onStart() {
999 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001000 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001001 }
1002
Garfield Tan891146c2018-10-09 12:14:00 -07001003 @Override
1004 public void onUnlockUser(int userId) {
1005 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001006 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001007 }
1008 }
1009
1010 @Override
1011 public void onCleanupUser(int userId) {
1012 synchronized (mService.getGlobalLock()) {
1013 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1014 }
1015 }
1016
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001017 public ActivityTaskManagerService getService() {
1018 return mService;
1019 }
1020 }
1021
1022 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001023 public final int startActivity(IApplicationThread caller, String callingPackage,
1024 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1025 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1026 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1027 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1028 UserHandle.getCallingUserId());
1029 }
1030
1031 @Override
1032 public final int startActivities(IApplicationThread caller, String callingPackage,
1033 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1034 int userId) {
1035 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001036 enforceNotIsolatedCaller(reason);
1037 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001039 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1040 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1041 reason, null /* originatingPendingIntent */,
1042 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 }
1044
1045 @Override
1046 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1047 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1048 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1049 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1050 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1051 true /*validateIncomingUser*/);
1052 }
1053
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001054 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001055 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1056 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1057 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001058 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001059
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001060 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001061 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1062
1063 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001064 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001065 .setCaller(caller)
1066 .setCallingPackage(callingPackage)
1067 .setResolvedType(resolvedType)
1068 .setResultTo(resultTo)
1069 .setResultWho(resultWho)
1070 .setRequestCode(requestCode)
1071 .setStartFlags(startFlags)
1072 .setProfilerInfo(profilerInfo)
1073 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001074 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001075 .execute();
1076
1077 }
1078
1079 @Override
1080 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1081 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001082 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1083 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001084 // Refuse possible leaked file descriptors
1085 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1086 throw new IllegalArgumentException("File descriptors passed in Intent");
1087 }
1088
1089 if (!(target instanceof PendingIntentRecord)) {
1090 throw new IllegalArgumentException("Bad PendingIntent object");
1091 }
1092
1093 PendingIntentRecord pir = (PendingIntentRecord)target;
1094
1095 synchronized (mGlobalLock) {
1096 // If this is coming from the currently resumed activity, it is
1097 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001098 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001099 if (stack.mResumedActivity != null &&
1100 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001101 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001102 }
1103 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001104 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001105 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001106 }
1107
1108 @Override
1109 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1110 Bundle bOptions) {
1111 // Refuse possible leaked file descriptors
1112 if (intent != null && intent.hasFileDescriptors()) {
1113 throw new IllegalArgumentException("File descriptors passed in Intent");
1114 }
1115 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1116
1117 synchronized (mGlobalLock) {
1118 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1119 if (r == null) {
1120 SafeActivityOptions.abort(options);
1121 return false;
1122 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001123 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001124 // The caller is not running... d'oh!
1125 SafeActivityOptions.abort(options);
1126 return false;
1127 }
1128 intent = new Intent(intent);
1129 // The caller is not allowed to change the data.
1130 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1131 // And we are resetting to find the next component...
1132 intent.setComponent(null);
1133
1134 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1135
1136 ActivityInfo aInfo = null;
1137 try {
1138 List<ResolveInfo> resolves =
1139 AppGlobals.getPackageManager().queryIntentActivities(
1140 intent, r.resolvedType,
1141 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1142 UserHandle.getCallingUserId()).getList();
1143
1144 // Look for the original activity in the list...
1145 final int N = resolves != null ? resolves.size() : 0;
1146 for (int i=0; i<N; i++) {
1147 ResolveInfo rInfo = resolves.get(i);
1148 if (rInfo.activityInfo.packageName.equals(r.packageName)
1149 && rInfo.activityInfo.name.equals(r.info.name)) {
1150 // We found the current one... the next matching is
1151 // after it.
1152 i++;
1153 if (i<N) {
1154 aInfo = resolves.get(i).activityInfo;
1155 }
1156 if (debug) {
1157 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1158 + "/" + r.info.name);
1159 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1160 ? "null" : aInfo.packageName + "/" + aInfo.name));
1161 }
1162 break;
1163 }
1164 }
1165 } catch (RemoteException e) {
1166 }
1167
1168 if (aInfo == null) {
1169 // Nobody who is next!
1170 SafeActivityOptions.abort(options);
1171 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1172 return false;
1173 }
1174
1175 intent.setComponent(new ComponentName(
1176 aInfo.applicationInfo.packageName, aInfo.name));
1177 intent.setFlags(intent.getFlags()&~(
1178 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1179 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1180 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1181 FLAG_ACTIVITY_NEW_TASK));
1182
1183 // Okay now we need to start the new activity, replacing the currently running activity.
1184 // This is a little tricky because we want to start the new one as if the current one is
1185 // finished, but not finish the current one first so that there is no flicker.
1186 // And thus...
1187 final boolean wasFinishing = r.finishing;
1188 r.finishing = true;
1189
1190 // Propagate reply information over to the new activity.
1191 final ActivityRecord resultTo = r.resultTo;
1192 final String resultWho = r.resultWho;
1193 final int requestCode = r.requestCode;
1194 r.resultTo = null;
1195 if (resultTo != null) {
1196 resultTo.removeResultsLocked(r, resultWho, requestCode);
1197 }
1198
1199 final long origId = Binder.clearCallingIdentity();
1200 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001201 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001202 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001203 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001204 .setResolvedType(r.resolvedType)
1205 .setActivityInfo(aInfo)
1206 .setResultTo(resultTo != null ? resultTo.appToken : null)
1207 .setResultWho(resultWho)
1208 .setRequestCode(requestCode)
1209 .setCallingPid(-1)
1210 .setCallingUid(r.launchedFromUid)
1211 .setCallingPackage(r.launchedFromPackage)
1212 .setRealCallingPid(-1)
1213 .setRealCallingUid(r.launchedFromUid)
1214 .setActivityOptions(options)
1215 .execute();
1216 Binder.restoreCallingIdentity(origId);
1217
1218 r.finishing = wasFinishing;
1219 if (res != ActivityManager.START_SUCCESS) {
1220 return false;
1221 }
1222 return true;
1223 }
1224 }
1225
1226 @Override
1227 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1228 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1229 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1230 final WaitResult res = new WaitResult();
1231 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001232 enforceNotIsolatedCaller("startActivityAndWait");
1233 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1234 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001235 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001236 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 .setCaller(caller)
1238 .setCallingPackage(callingPackage)
1239 .setResolvedType(resolvedType)
1240 .setResultTo(resultTo)
1241 .setResultWho(resultWho)
1242 .setRequestCode(requestCode)
1243 .setStartFlags(startFlags)
1244 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001245 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001246 .setProfilerInfo(profilerInfo)
1247 .setWaitResult(res)
1248 .execute();
1249 }
1250 return res;
1251 }
1252
1253 @Override
1254 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1255 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1256 int startFlags, Configuration config, Bundle bOptions, int userId) {
1257 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001258 enforceNotIsolatedCaller("startActivityWithConfig");
1259 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1260 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001261 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001262 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001263 .setCaller(caller)
1264 .setCallingPackage(callingPackage)
1265 .setResolvedType(resolvedType)
1266 .setResultTo(resultTo)
1267 .setResultWho(resultWho)
1268 .setRequestCode(requestCode)
1269 .setStartFlags(startFlags)
1270 .setGlobalConfiguration(config)
1271 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001272 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001273 .execute();
1274 }
1275 }
1276
Alison Cichowlas3e340502018-08-07 17:15:01 -04001277
1278 @Override
1279 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1280 int callingUid = Binder.getCallingUid();
1281 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1282 throw new SecurityException("Only the system process can request a permission token, "
1283 + "received request from uid: " + callingUid);
1284 }
1285 IBinder permissionToken = new Binder();
1286 synchronized (mGlobalLock) {
1287 mStartActivitySources.put(permissionToken, delegatorToken);
1288 }
1289
1290 Message expireMsg = PooledLambda.obtainMessage(
1291 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1292 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1293
1294 Message forgetMsg = PooledLambda.obtainMessage(
1295 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1296 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1297
1298 return permissionToken;
1299 }
1300
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001301 @Override
1302 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1303 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001304 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1305 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001306 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001307 // permission grants) as any app that may launch one of your own activities. So we only
1308 // allow this in two cases:
1309 // 1) The caller is an activity that is part of the core framework, and then only when it
1310 // is running as the system.
1311 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1312 // can only be requested by a system activity, which may then delegate this call to
1313 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001314 final ActivityRecord sourceRecord;
1315 final int targetUid;
1316 final String targetPackage;
1317 final boolean isResolver;
1318 synchronized (mGlobalLock) {
1319 if (resultTo == null) {
1320 throw new SecurityException("Must be called from an activity");
1321 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001322 final IBinder sourceToken;
1323 if (permissionToken != null) {
1324 // To even attempt to use a permissionToken, an app must also have this signature
1325 // permission.
1326 mAmInternal.enforceCallingPermission(
1327 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1328 "startActivityAsCaller");
1329 // If called with a permissionToken, we want the sourceRecord from the delegator
1330 // activity that requested this token.
1331 sourceToken = mStartActivitySources.remove(permissionToken);
1332 if (sourceToken == null) {
1333 // Invalid permissionToken, check if it recently expired.
1334 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1335 throw new SecurityException("Called with expired permission token: "
1336 + permissionToken);
1337 } else {
1338 throw new SecurityException("Called with invalid permission token: "
1339 + permissionToken);
1340 }
1341 }
1342 } else {
1343 // This method was called directly by the source.
1344 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001345 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001346
Wale Ogunwaled32da472018-11-16 07:19:28 -08001347 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001348 if (sourceRecord == null) {
1349 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001350 }
1351 if (sourceRecord.app == null) {
1352 throw new SecurityException("Called without a process attached to activity");
1353 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001354
1355 // Whether called directly or from a delegate, the source activity must be from the
1356 // android package.
1357 if (!sourceRecord.info.packageName.equals("android")) {
1358 throw new SecurityException("Must be called from an activity that is "
1359 + "declared in the android package");
1360 }
1361
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001362 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001363 // This is still okay, as long as this activity is running under the
1364 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001365 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001366 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001367 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 + " must be system uid or original calling uid "
1369 + sourceRecord.launchedFromUid);
1370 }
1371 }
1372 if (ignoreTargetSecurity) {
1373 if (intent.getComponent() == null) {
1374 throw new SecurityException(
1375 "Component must be specified with ignoreTargetSecurity");
1376 }
1377 if (intent.getSelector() != null) {
1378 throw new SecurityException(
1379 "Selector not allowed with ignoreTargetSecurity");
1380 }
1381 }
1382 targetUid = sourceRecord.launchedFromUid;
1383 targetPackage = sourceRecord.launchedFromPackage;
1384 isResolver = sourceRecord.isResolverOrChildActivity();
1385 }
1386
1387 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001388 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001389 }
1390
1391 // TODO: Switch to user app stacks here.
1392 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001393 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394 .setCallingUid(targetUid)
1395 .setCallingPackage(targetPackage)
1396 .setResolvedType(resolvedType)
1397 .setResultTo(resultTo)
1398 .setResultWho(resultWho)
1399 .setRequestCode(requestCode)
1400 .setStartFlags(startFlags)
1401 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001402 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001403 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1404 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001405 // The target may well be in the background, which would normally prevent it
1406 // from starting an activity. Here we definitely want the start to succeed.
1407 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001408 .execute();
1409 } catch (SecurityException e) {
1410 // XXX need to figure out how to propagate to original app.
1411 // A SecurityException here is generally actually a fault of the original
1412 // calling activity (such as a fairly granting permissions), so propagate it
1413 // back to them.
1414 /*
1415 StringBuilder msg = new StringBuilder();
1416 msg.append("While launching");
1417 msg.append(intent.toString());
1418 msg.append(": ");
1419 msg.append(e.getMessage());
1420 */
1421 throw e;
1422 }
1423 }
1424
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001425 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1426 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1427 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1428 }
1429
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001430 @Override
1431 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1432 Intent intent, String resolvedType, IVoiceInteractionSession session,
1433 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1434 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001435 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001436 if (session == null || interactor == null) {
1437 throw new NullPointerException("null session or interactor");
1438 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001439 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001440 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001441 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001442 .setCallingUid(callingUid)
1443 .setCallingPackage(callingPackage)
1444 .setResolvedType(resolvedType)
1445 .setVoiceSession(session)
1446 .setVoiceInteractor(interactor)
1447 .setStartFlags(startFlags)
1448 .setProfilerInfo(profilerInfo)
1449 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001450 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001451 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452 .execute();
1453 }
1454
1455 @Override
1456 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1457 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001458 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1459 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001460
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001461 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001462 .setCallingUid(callingUid)
1463 .setCallingPackage(callingPackage)
1464 .setResolvedType(resolvedType)
1465 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001466 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001467 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001468 .execute();
1469 }
1470
Riddle Hsu609a8e22019-06-27 16:46:29 -06001471 /**
1472 * Start the recents activity to perform the recents animation.
1473 *
1474 * @param intent The intent to start the recents activity.
1475 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1476 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001477 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001478 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1479 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001480 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001481 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001482 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001483 final long origId = Binder.clearCallingIdentity();
1484 try {
1485 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001486 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1487 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001488 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001489
1490 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001491 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001492 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001493 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001494 if (recentsAnimationRunner == null) {
1495 anim.preloadRecentsActivity();
1496 } else {
1497 anim.startRecentsActivity(recentsAnimationRunner);
1498 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001499 }
1500 } finally {
1501 Binder.restoreCallingIdentity(origId);
1502 }
1503 }
1504
1505 @Override
1506 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001507 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001508 "startActivityFromRecents()");
1509
1510 final int callingPid = Binder.getCallingPid();
1511 final int callingUid = Binder.getCallingUid();
1512 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1513 final long origId = Binder.clearCallingIdentity();
1514 try {
1515 synchronized (mGlobalLock) {
1516 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1517 safeOptions);
1518 }
1519 } finally {
1520 Binder.restoreCallingIdentity(origId);
1521 }
1522 }
1523
1524 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001525 * Public API to check if the client is allowed to start an activity on specified display.
1526 *
1527 * If the target display is private or virtual, some restrictions will apply.
1528 *
1529 * @param displayId Target display id.
1530 * @param intent Intent used to launch the activity.
1531 * @param resolvedType The MIME type of the intent.
1532 * @param userId The id of the user for whom the call is made.
1533 * @return {@code true} if a call to start an activity on the target display should succeed and
1534 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1535 */
1536 @Override
1537 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1538 String resolvedType, int userId) {
1539 final int callingUid = Binder.getCallingUid();
1540 final int callingPid = Binder.getCallingPid();
1541 final long origId = Binder.clearCallingIdentity();
1542
1543 try {
1544 // Collect information about the target of the Intent.
1545 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1546 0 /* startFlags */, null /* profilerInfo */, userId,
1547 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1548 UserHandle.USER_NULL));
1549 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1550
1551 synchronized (mGlobalLock) {
1552 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1553 aInfo);
1554 }
1555 } finally {
1556 Binder.restoreCallingIdentity(origId);
1557 }
1558 }
1559
1560 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001561 * This is the internal entry point for handling Activity.finish().
1562 *
1563 * @param token The Binder token referencing the Activity we want to finish.
1564 * @param resultCode Result code, if any, from this Activity.
1565 * @param resultData Result data (Intent), if any, from this Activity.
1566 * @param finishTask Whether to finish the task associated with this Activity.
1567 *
1568 * @return Returns true if the activity successfully finished, or false if it is still running.
1569 */
1570 @Override
1571 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1572 int finishTask) {
1573 // Refuse possible leaked file descriptors
1574 if (resultData != null && resultData.hasFileDescriptors()) {
1575 throw new IllegalArgumentException("File descriptors passed in Intent");
1576 }
1577
1578 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001579 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001580 if (r == null) {
1581 return true;
1582 }
1583 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001584 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001585 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001586 if (rootR == null) {
1587 Slog.w(TAG, "Finishing task with all activities already finished");
1588 }
1589 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1590 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001591 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001592 return false;
1593 }
1594
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001595 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1596 // We should consolidate.
1597 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001598 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001599 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001600 if (next != null) {
1601 // ask watcher if this is allowed
1602 boolean resumeOK = true;
1603 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001604 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001605 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001606 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001607 Watchdog.getInstance().setActivityController(null);
1608 }
1609
1610 if (!resumeOK) {
1611 Slog.i(TAG, "Not finishing activity because controller resumed");
1612 return false;
1613 }
1614 }
1615 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001616
1617 // note down that the process has finished an activity and is in background activity
1618 // starts grace period
1619 if (r.app != null) {
1620 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1621 }
1622
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001623 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001624 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001625 try {
1626 boolean res;
1627 final boolean finishWithRootActivity =
1628 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1629 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1630 || (finishWithRootActivity && r == rootR)) {
1631 // If requested, remove the task that is associated to this activity only if it
1632 // was the root activity in the task. The result code and data is ignored
1633 // because we don't support returning them across task boundaries. Also, to
1634 // keep backwards compatibility we remove the task from recents when finishing
1635 // task with root activity.
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001636 res = mStackSupervisor.removeTaskByIdLocked(tr.mTaskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001637 finishWithRootActivity, "finish-activity");
1638 if (!res) {
1639 Slog.i(TAG, "Removing task failed to finish activity");
1640 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001641 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001642 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001643 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001644 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001645 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001646 if (!res) {
1647 Slog.i(TAG, "Failed to finish by app-request");
1648 }
1649 }
1650 return res;
1651 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001652 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001653 Binder.restoreCallingIdentity(origId);
1654 }
1655 }
1656 }
1657
1658 @Override
1659 public boolean finishActivityAffinity(IBinder token) {
1660 synchronized (mGlobalLock) {
1661 final long origId = Binder.clearCallingIdentity();
1662 try {
1663 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1664 if (r == null) {
1665 return false;
1666 }
1667
1668 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1669 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001670 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001671 return false;
1672 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001673
1674 final PooledFunction p = PooledLambda.obtainFunction(
1675 ActivityRecord::finishIfSameAffinity, r,
1676 PooledLambda.__(ActivityRecord.class));
1677 r.getTask().forAllActivities(
1678 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1679 p.recycle();
1680
Andrii Kuliande93eff2019-07-12 12:21:27 -07001681 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001682 } finally {
1683 Binder.restoreCallingIdentity(origId);
1684 }
1685 }
1686 }
1687
1688 @Override
1689 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1690 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001691 try {
1692 WindowProcessController proc = null;
1693 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001694 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001695 ActivityStack stack = ActivityRecord.getStackLocked(token);
1696 if (stack == null) {
1697 return;
1698 }
1699 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1700 false /* fromTimeout */, false /* processPausingActivities */, config);
1701 if (r != null) {
1702 proc = r.app;
1703 }
1704 if (stopProfiling && proc != null) {
1705 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001706 }
1707 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001708 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001709 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001710 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001711 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001712 }
1713
1714 @Override
1715 public final void activityResumed(IBinder token) {
1716 final long origId = Binder.clearCallingIdentity();
1717 synchronized (mGlobalLock) {
1718 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001719 }
1720 Binder.restoreCallingIdentity(origId);
1721 }
1722
1723 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001724 public final void activityTopResumedStateLost() {
1725 final long origId = Binder.clearCallingIdentity();
1726 synchronized (mGlobalLock) {
1727 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1728 }
1729 Binder.restoreCallingIdentity(origId);
1730 }
1731
1732 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001733 public final void activityPaused(IBinder token) {
1734 final long origId = Binder.clearCallingIdentity();
1735 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001736 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001737 ActivityStack stack = ActivityRecord.getStackLocked(token);
1738 if (stack != null) {
1739 stack.activityPausedLocked(token, false);
1740 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001741 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001742 }
1743 Binder.restoreCallingIdentity(origId);
1744 }
1745
1746 @Override
1747 public final void activityStopped(IBinder token, Bundle icicle,
1748 PersistableBundle persistentState, CharSequence description) {
1749 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1750
1751 // Refuse possible leaked file descriptors
1752 if (icicle != null && icicle.hasFileDescriptors()) {
1753 throw new IllegalArgumentException("File descriptors passed in Bundle");
1754 }
1755
1756 final long origId = Binder.clearCallingIdentity();
1757
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001758 String restartingName = null;
1759 int restartingUid = 0;
1760 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001761 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001762 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001763 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001764 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001765 if (r.attachedToProcess()
1766 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1767 // The activity was requested to restart from
1768 // {@link #restartActivityProcessIfVisible}.
1769 restartingName = r.app.mName;
1770 restartingUid = r.app.mUid;
1771 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001772 r.activityStoppedLocked(icicle, persistentState, description);
1773 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001774 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001775 }
1776
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001777 if (restartingName != null) {
1778 // In order to let the foreground activity can be restarted with its saved state from
1779 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1780 // until the activity reports stopped with the state. And the activity record will be
1781 // kept because the record state is restarting, then the activity will be restarted
1782 // immediately if it is still the top one.
1783 mStackSupervisor.removeRestartTimeouts(r);
1784 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1785 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001786 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001787
1788 Binder.restoreCallingIdentity(origId);
1789 }
1790
1791 @Override
1792 public final void activityDestroyed(IBinder token) {
1793 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1794 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001795 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001796 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001797 try {
1798 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1799 if (activity != null) {
1800 activity.destroyed("activityDestroyed");
1801 }
1802 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001803 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001804 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001805 }
1806 }
1807 }
1808
1809 @Override
1810 public final void activityRelaunched(IBinder token) {
1811 final long origId = Binder.clearCallingIdentity();
1812 synchronized (mGlobalLock) {
1813 mStackSupervisor.activityRelaunchedLocked(token);
1814 }
1815 Binder.restoreCallingIdentity(origId);
1816 }
1817
1818 public final void activitySlept(IBinder token) {
1819 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1820
1821 final long origId = Binder.clearCallingIdentity();
1822
1823 synchronized (mGlobalLock) {
1824 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1825 if (r != null) {
1826 mStackSupervisor.activitySleptLocked(r);
1827 }
1828 }
1829
1830 Binder.restoreCallingIdentity(origId);
1831 }
1832
1833 @Override
1834 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1835 synchronized (mGlobalLock) {
1836 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1837 if (r == null) {
1838 return;
1839 }
1840 final long origId = Binder.clearCallingIdentity();
1841 try {
1842 r.setRequestedOrientation(requestedOrientation);
1843 } finally {
1844 Binder.restoreCallingIdentity(origId);
1845 }
1846 }
1847 }
1848
1849 @Override
1850 public int getRequestedOrientation(IBinder token) {
1851 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001852 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1853 return (r != null)
1854 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001855 }
1856 }
1857
1858 @Override
1859 public void setImmersive(IBinder token, boolean immersive) {
1860 synchronized (mGlobalLock) {
1861 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1862 if (r == null) {
1863 throw new IllegalArgumentException();
1864 }
1865 r.immersive = immersive;
1866
1867 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001868 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001869 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001870 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001871 }
1872 }
1873 }
1874
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001875 void applyUpdateLockStateLocked(ActivityRecord r) {
1876 // Modifications to the UpdateLock state are done on our handler, outside
1877 // the activity manager's locks. The new state is determined based on the
1878 // state *now* of the relevant activity record. The object is passed to
1879 // the handler solely for logging detail, not to be consulted/modified.
1880 final boolean nextState = r != null && r.immersive;
1881 mH.post(() -> {
1882 if (mUpdateLock.isHeld() != nextState) {
1883 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1884 "Applying new update lock state '" + nextState + "' for " + r);
1885 if (nextState) {
1886 mUpdateLock.acquire();
1887 } else {
1888 mUpdateLock.release();
1889 }
1890 }
1891 });
1892 }
1893
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001894 @Override
1895 public boolean isImmersive(IBinder token) {
1896 synchronized (mGlobalLock) {
1897 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1898 if (r == null) {
1899 throw new IllegalArgumentException();
1900 }
1901 return r.immersive;
1902 }
1903 }
1904
1905 @Override
1906 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001907 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001908 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001909 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001910 return (r != null) ? r.immersive : false;
1911 }
1912 }
1913
1914 @Override
1915 public void overridePendingTransition(IBinder token, String packageName,
1916 int enterAnim, int exitAnim) {
1917 synchronized (mGlobalLock) {
1918 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1919 if (self == null) {
1920 return;
1921 }
1922
1923 final long origId = Binder.clearCallingIdentity();
1924
1925 if (self.isState(
1926 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001927 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001928 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001929 }
1930
1931 Binder.restoreCallingIdentity(origId);
1932 }
1933 }
1934
1935 @Override
1936 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001937 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001938 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001939 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001940 if (r == null) {
1941 return ActivityManager.COMPAT_MODE_UNKNOWN;
1942 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001943 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001944 }
1945 }
1946
1947 @Override
1948 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001949 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001950 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001951 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001952 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001953 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001954 if (r == null) {
1955 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1956 return;
1957 }
1958 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001959 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001960 }
1961 }
1962
1963 @Override
1964 public int getLaunchedFromUid(IBinder activityToken) {
1965 ActivityRecord srec;
1966 synchronized (mGlobalLock) {
1967 srec = ActivityRecord.forTokenLocked(activityToken);
1968 }
1969 if (srec == null) {
1970 return -1;
1971 }
1972 return srec.launchedFromUid;
1973 }
1974
1975 @Override
1976 public String getLaunchedFromPackage(IBinder activityToken) {
1977 ActivityRecord srec;
1978 synchronized (mGlobalLock) {
1979 srec = ActivityRecord.forTokenLocked(activityToken);
1980 }
1981 if (srec == null) {
1982 return null;
1983 }
1984 return srec.launchedFromPackage;
1985 }
1986
1987 @Override
1988 public boolean convertFromTranslucent(IBinder token) {
1989 final long origId = Binder.clearCallingIdentity();
1990 try {
1991 synchronized (mGlobalLock) {
1992 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1993 if (r == null) {
1994 return false;
1995 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001996 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001997 }
1998 } finally {
1999 Binder.restoreCallingIdentity(origId);
2000 }
2001 }
2002
2003 @Override
2004 public boolean convertToTranslucent(IBinder token, Bundle options) {
2005 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2006 final long origId = Binder.clearCallingIdentity();
2007 try {
2008 synchronized (mGlobalLock) {
2009 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2010 if (r == null) {
2011 return false;
2012 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002013 final ActivityRecord under = r.getTask().getActivityBelow(r);
2014 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002015 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2016 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002017 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002018 }
2019 } finally {
2020 Binder.restoreCallingIdentity(origId);
2021 }
2022 }
2023
2024 @Override
2025 public void notifyActivityDrawn(IBinder token) {
2026 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2027 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002028 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002029 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002030 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002031 }
2032 }
2033 }
2034
2035 @Override
2036 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2037 synchronized (mGlobalLock) {
2038 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2039 if (r == null) {
2040 return;
2041 }
2042 r.reportFullyDrawnLocked(restoredFromBundle);
2043 }
2044 }
2045
2046 @Override
2047 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2048 synchronized (mGlobalLock) {
2049 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2050 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2051 return stack.mDisplayId;
2052 }
2053 return DEFAULT_DISPLAY;
2054 }
2055 }
2056
2057 @Override
2058 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002059 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 long ident = Binder.clearCallingIdentity();
2061 try {
2062 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002063 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002064 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002065 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002066 }
2067 return null;
2068 }
2069 } finally {
2070 Binder.restoreCallingIdentity(ident);
2071 }
2072 }
2073
2074 @Override
2075 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002076 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002077 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2078 final long callingId = Binder.clearCallingIdentity();
2079 try {
2080 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002081 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002082 if (stack == null) {
2083 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2084 return;
2085 }
2086 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002087 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002088 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002089 }
2090 }
2091 } finally {
2092 Binder.restoreCallingIdentity(callingId);
2093 }
2094 }
2095
2096 @Override
2097 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002098 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002099 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2100 final long callingId = Binder.clearCallingIdentity();
2101 try {
2102 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002103 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002104 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002105 if (task == null) {
2106 return;
2107 }
2108 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002109 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002110 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002111 }
2112 }
2113 } finally {
2114 Binder.restoreCallingIdentity(callingId);
2115 }
2116 }
2117
2118 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002119 public void restartActivityProcessIfVisible(IBinder activityToken) {
2120 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2121 final long callingId = Binder.clearCallingIdentity();
2122 try {
2123 synchronized (mGlobalLock) {
2124 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2125 if (r == null) {
2126 return;
2127 }
2128 r.restartProcessIfVisible();
2129 }
2130 } finally {
2131 Binder.restoreCallingIdentity(callingId);
2132 }
2133 }
2134
2135 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002136 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002137 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002138 synchronized (mGlobalLock) {
2139 final long ident = Binder.clearCallingIdentity();
2140 try {
2141 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2142 "remove-task");
2143 } finally {
2144 Binder.restoreCallingIdentity(ident);
2145 }
2146 }
2147 }
2148
2149 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002150 public void removeAllVisibleRecentTasks() {
2151 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2152 synchronized (mGlobalLock) {
2153 final long ident = Binder.clearCallingIdentity();
2154 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002155 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002156 } finally {
2157 Binder.restoreCallingIdentity(ident);
2158 }
2159 }
2160 }
2161
2162 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002163 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2164 synchronized (mGlobalLock) {
2165 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2166 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002167 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002168 }
2169 }
2170 return false;
2171 }
2172
2173 @Override
2174 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2175 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002176
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002177 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002178 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2179 if (r != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002180 return r.getActivityStack().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002181 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002182 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002183 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002184 }
2185 }
2186
2187 /**
2188 * Attempts to move a task backwards in z-order (the order of activities within the task is
2189 * unchanged).
2190 *
2191 * There are several possible results of this call:
2192 * - if the task is locked, then we will show the lock toast
2193 * - if there is a task behind the provided task, then that task is made visible and resumed as
2194 * this task is moved to the back
2195 * - otherwise, if there are no other tasks in the stack:
2196 * - if this task is in the pinned stack, then we remove the stack completely, which will
2197 * have the effect of moving the task to the top or bottom of the fullscreen stack
2198 * (depending on whether it is visible)
2199 * - otherwise, we simply return home and hide this task
2200 *
2201 * @param token A reference to the activity we wish to move
2202 * @param nonRoot If false then this only works if the activity is the root
2203 * of a task; if true it will work for any activity in a task.
2204 * @return Returns true if the move completed, false if not.
2205 */
2206 @Override
2207 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002208 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002209 synchronized (mGlobalLock) {
2210 final long origId = Binder.clearCallingIdentity();
2211 try {
2212 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Changcdec0802019-11-11 11:45:07 +08002213 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002214 if (task != null) {
2215 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2216 }
2217 } finally {
2218 Binder.restoreCallingIdentity(origId);
2219 }
2220 }
2221 return false;
2222 }
2223
2224 @Override
2225 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002226 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 long ident = Binder.clearCallingIdentity();
2228 Rect rect = new Rect();
2229 try {
2230 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002231 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002232 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2233 if (task == null) {
2234 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2235 return rect;
2236 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002237 if (task.getParent() != null) {
2238 rect.set(task.getBounds());
2239 } else if (task.mLastNonFullscreenBounds != null) {
2240 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002241 }
2242 }
2243 } finally {
2244 Binder.restoreCallingIdentity(ident);
2245 }
2246 return rect;
2247 }
2248
2249 @Override
2250 public ActivityManager.TaskDescription getTaskDescription(int id) {
2251 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002252 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002253 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Changcdec0802019-11-11 11:45:07 +08002254 final Task tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002255 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2256 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002257 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002258 }
2259 }
2260 return null;
2261 }
2262
2263 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002264 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2265 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2266 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2267 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2268 return;
2269 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002270 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002271 synchronized (mGlobalLock) {
2272 final long ident = Binder.clearCallingIdentity();
2273 try {
Louis Changcdec0802019-11-11 11:45:07 +08002274 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002275 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002276 if (task == null) {
2277 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2278 return;
2279 }
2280
2281 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2282 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2283
2284 if (!task.isActivityTypeStandardOrUndefined()) {
2285 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2286 + " non-standard task " + taskId + " to windowing mode="
2287 + windowingMode);
2288 }
2289
2290 final ActivityStack stack = task.getStack();
2291 if (toTop) {
2292 stack.moveToFront("setTaskWindowingMode", task);
2293 }
2294 stack.setWindowingMode(windowingMode);
2295 } finally {
2296 Binder.restoreCallingIdentity(ident);
2297 }
2298 }
2299 }
2300
2301 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002302 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002303 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002304 ActivityRecord r = getCallingRecordLocked(token);
2305 return r != null ? r.info.packageName : null;
2306 }
2307 }
2308
2309 @Override
2310 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002311 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002312 ActivityRecord r = getCallingRecordLocked(token);
2313 return r != null ? r.intent.getComponent() : null;
2314 }
2315 }
2316
2317 private ActivityRecord getCallingRecordLocked(IBinder token) {
2318 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2319 if (r == null) {
2320 return null;
2321 }
2322 return r.resultTo;
2323 }
2324
2325 @Override
2326 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002327 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002328
2329 synchronized (mGlobalLock) {
2330 final long origId = Binder.clearCallingIdentity();
2331 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002332 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002333 } finally {
2334 Binder.restoreCallingIdentity(origId);
2335 }
2336 }
2337 }
2338
Mark Renouf446251d2019-04-26 10:22:41 -04002339 @Override
2340 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2341 synchronized (mGlobalLock) {
2342 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2343 if (r == null) {
2344 return;
2345 }
2346 ActivityStack stack = r.getActivityStack();
2347 if (stack != null && stack.isSingleTaskInstance()) {
2348 // Single-task stacks are used for activities which are presented in floating
2349 // windows above full screen activities. Instead of directly finishing the
2350 // task, a task change listener is used to notify SystemUI so the action can be
2351 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002352 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002353 mTaskChangeNotificationController
2354 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2355 } else {
2356 try {
2357 callback.requestFinish();
2358 } catch (RemoteException e) {
2359 Slog.e(TAG, "Failed to invoke request finish callback", e);
2360 }
2361 }
2362 }
2363 }
2364
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002365 /**
2366 * TODO: Add mController hook
2367 */
2368 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002369 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2370 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002371 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002372
2373 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2374 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002375 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2376 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002377 }
2378 }
2379
Ricky Waiaca8a772019-04-04 16:01:06 +01002380 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2381 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002382 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002383
Ricky Waiaca8a772019-04-04 16:01:06 +01002384 final int callingPid = Binder.getCallingPid();
2385 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002386 if (!isSameApp(callingUid, callingPackage)) {
2387 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2388 + Binder.getCallingPid() + " as package " + callingPackage;
2389 Slog.w(TAG, msg);
2390 throw new SecurityException(msg);
2391 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002392 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002393 SafeActivityOptions.abort(options);
2394 return;
2395 }
2396 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002397 WindowProcessController callerApp = null;
2398 if (appThread != null) {
2399 callerApp = getProcessController(appThread);
2400 }
2401 final ActivityStarter starter = getActivityStartController().obtainStarter(
2402 null /* intent */, "moveTaskToFront");
2403 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2404 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002405 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002406 return;
2407 }
2408 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002409 try {
Louis Changcdec0802019-11-11 11:45:07 +08002410 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002411 if (task == null) {
2412 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002413 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002414 return;
2415 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002416 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002417 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002418 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002419 return;
2420 }
2421 ActivityOptions realOptions = options != null
2422 ? options.getOptions(mStackSupervisor)
2423 : null;
2424 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2425 false /* forceNonResizable */);
2426
Wale Ogunwale21e06482019-11-18 05:14:15 -08002427 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002428 if (topActivity != null) {
2429
2430 // We are reshowing a task, use a starting window to hide the initial draw delay
2431 // so the transition can start earlier.
2432 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2433 true /* taskSwitch */, fromRecents);
2434 }
2435 } finally {
2436 Binder.restoreCallingIdentity(origId);
2437 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002438 }
2439
Ricky Waiaca8a772019-04-04 16:01:06 +01002440 /**
2441 * Return true if callingUid is system, or packageName belongs to that callingUid.
2442 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002443 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002444 try {
2445 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2446 if (packageName == null) {
2447 return false;
2448 }
2449 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2450 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2451 UserHandle.getUserId(callingUid));
2452 return UserHandle.isSameApp(callingUid, uid);
2453 }
2454 } catch (RemoteException e) {
2455 // Should not happen
2456 }
2457 return true;
2458 }
2459
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002460 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2461 int callingPid, int callingUid, String name) {
2462 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2463 return true;
2464 }
2465
2466 if (getRecentTasks().isCallerRecents(sourceUid)) {
2467 return true;
2468 }
2469
2470 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2471 if (perm == PackageManager.PERMISSION_GRANTED) {
2472 return true;
2473 }
2474 if (checkAllowAppSwitchUid(sourceUid)) {
2475 return true;
2476 }
2477
2478 // If the actual IPC caller is different from the logical source, then
2479 // also see if they are allowed to control app switches.
2480 if (callingUid != -1 && callingUid != sourceUid) {
2481 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2482 if (perm == PackageManager.PERMISSION_GRANTED) {
2483 return true;
2484 }
2485 if (checkAllowAppSwitchUid(callingUid)) {
2486 return true;
2487 }
2488 }
2489
2490 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2491 return false;
2492 }
2493
2494 private boolean checkAllowAppSwitchUid(int uid) {
2495 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2496 if (types != null) {
2497 for (int i = types.size() - 1; i >= 0; i--) {
2498 if (types.valueAt(i).intValue() == uid) {
2499 return true;
2500 }
2501 }
2502 }
2503 return false;
2504 }
2505
2506 @Override
2507 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2508 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2509 "setActivityController()");
2510 synchronized (mGlobalLock) {
2511 mController = controller;
2512 mControllerIsAMonkey = imAMonkey;
2513 Watchdog.getInstance().setActivityController(controller);
2514 }
2515 }
2516
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002517 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002518 synchronized (mGlobalLock) {
2519 return mController != null && mControllerIsAMonkey;
2520 }
2521 }
2522
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002523 @Override
2524 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2525 synchronized (mGlobalLock) {
2526 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2527 }
2528 }
2529
2530 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002531 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2532 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2533 }
2534
2535 @Override
2536 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2537 @WindowConfiguration.ActivityType int ignoreActivityType,
2538 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2539 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002540 final int callingPid = Binder.getCallingPid();
2541 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002542 final int[] profileIds = getUserManager().getProfileIds(
2543 UserHandle.getUserId(callingUid), true);
2544 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2545 for (int i = 0; i < profileIds.length; i++) {
2546 callingProfileIds.add(profileIds[i]);
2547 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002548 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2549
2550 synchronized (mGlobalLock) {
2551 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2552
Nicholas Sauer0259e532019-08-30 08:24:55 -07002553 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002554 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002555 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002556 }
2557
2558 return list;
2559 }
2560
2561 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002562 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2563 synchronized (mGlobalLock) {
2564 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002565 try {
2566 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2567 if (r == null) return;
2568
2569 final PooledConsumer c = PooledLambda.obtainConsumer(
2570 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2571 r, resultWho, requestCode);
2572 // TODO: This should probably only loop over the task since you need to be in the
2573 // same task to return results.
2574 r.getActivityStack().forAllActivities(c);
2575 c.recycle();
2576
2577 updateOomAdj();
2578 } finally {
2579 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002580 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002581 }
2582 }
2583
2584 @Override
2585 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002586 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002587 ActivityStack stack = ActivityRecord.getStackLocked(token);
2588 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002589 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002590 }
2591 return false;
2592 }
2593 }
2594
2595 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002596 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002597 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002598 synchronized (mGlobalLock) {
2599 final long ident = Binder.clearCallingIdentity();
2600 try {
Louis Changcdec0802019-11-11 11:45:07 +08002601 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002602 if (task == null) {
2603 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2604 return;
2605 }
2606
2607 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2608 + " to stackId=" + stackId + " toTop=" + toTop);
2609
Wale Ogunwaled32da472018-11-16 07:19:28 -08002610 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002611 if (stack == null) {
2612 throw new IllegalStateException(
2613 "moveTaskToStack: No stack for stackId=" + stackId);
2614 }
2615 if (!stack.isActivityTypeStandardOrUndefined()) {
2616 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2617 + taskId + " to stack " + stackId);
2618 }
2619 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002620 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002621 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2622 }
2623 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2624 "moveTaskToStack");
2625 } finally {
2626 Binder.restoreCallingIdentity(ident);
2627 }
2628 }
2629 }
2630
2631 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002632 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2633 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002634
2635 final long ident = Binder.clearCallingIdentity();
2636 try {
2637 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002638 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2639 if (stack == null) {
2640 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2641 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002642 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002643 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2644 throw new IllegalArgumentException("Stack: " + stackId
2645 + " doesn't support animated resize.");
2646 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002647 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002648 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002649 }
2650 } finally {
2651 Binder.restoreCallingIdentity(ident);
2652 }
2653 }
2654
wilsonshih5c4cf522019-01-25 09:03:47 +08002655 @Override
2656 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2657 int animationDuration) {
2658 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2659
2660 final long ident = Binder.clearCallingIdentity();
2661 try {
2662 synchronized (mGlobalLock) {
2663 if (xOffset == 0 && yOffset == 0) {
2664 return;
2665 }
2666 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2667 if (stack == null) {
2668 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2669 return;
2670 }
2671 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2672 throw new IllegalArgumentException("Stack: " + stackId
2673 + " doesn't support animated resize.");
2674 }
2675 final Rect destBounds = new Rect();
2676 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002677 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002678 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2679 return;
2680 }
2681 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002682 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002683 animationDuration, false /* fromFullscreen */);
2684 }
2685 } finally {
2686 Binder.restoreCallingIdentity(ident);
2687 }
2688 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002689 /**
2690 * Moves the specified task to the primary-split-screen stack.
2691 *
2692 * @param taskId Id of task to move.
2693 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2694 * exist already. See
2695 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2696 * and
2697 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2698 * @param toTop If the task and stack should be moved to the top.
2699 * @param animate Whether we should play an animation for the moving the task.
2700 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2701 * stack. Pass {@code null} to use default bounds.
2702 * @param showRecents If the recents activity should be shown on the other side of the task
2703 * going into split-screen mode.
2704 */
2705 @Override
2706 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2707 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002708 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002709 "setTaskWindowingModeSplitScreenPrimary()");
2710 synchronized (mGlobalLock) {
2711 final long ident = Binder.clearCallingIdentity();
2712 try {
Louis Changcdec0802019-11-11 11:45:07 +08002713 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002714 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002715 if (task == null) {
2716 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2717 return false;
2718 }
2719 if (DEBUG_STACK) Slog.d(TAG_STACK,
2720 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2721 + " to createMode=" + createMode + " toTop=" + toTop);
2722 if (!task.isActivityTypeStandardOrUndefined()) {
2723 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2724 + " non-standard task " + taskId + " to split-screen windowing mode");
2725 }
2726
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002727 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002728 final int windowingMode = task.getWindowingMode();
2729 final ActivityStack stack = task.getStack();
2730 if (toTop) {
2731 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2732 }
2733 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002734 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2735 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002736 return windowingMode != task.getWindowingMode();
2737 } finally {
2738 Binder.restoreCallingIdentity(ident);
2739 }
2740 }
2741 }
2742
2743 /**
2744 * Removes stacks in the input windowing modes from the system if they are of activity type
2745 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2746 */
2747 @Override
2748 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002749 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002750 "removeStacksInWindowingModes()");
2751
2752 synchronized (mGlobalLock) {
2753 final long ident = Binder.clearCallingIdentity();
2754 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002755 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002756 } finally {
2757 Binder.restoreCallingIdentity(ident);
2758 }
2759 }
2760 }
2761
2762 @Override
2763 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002764 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002765 "removeStacksWithActivityTypes()");
2766
2767 synchronized (mGlobalLock) {
2768 final long ident = Binder.clearCallingIdentity();
2769 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002770 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002771 } finally {
2772 Binder.restoreCallingIdentity(ident);
2773 }
2774 }
2775 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002776
2777 @Override
2778 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2779 int userId) {
2780 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002781 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2782 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002783 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002784 final boolean detailed = checkGetTasksPermission(
2785 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2786 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002787 == PackageManager.PERMISSION_GRANTED;
2788
2789 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002790 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002791 callingUid);
2792 }
2793 }
2794
2795 @Override
2796 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002797 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002798 long ident = Binder.clearCallingIdentity();
2799 try {
2800 synchronized (mGlobalLock) {
Evan Roskyfd439692019-11-06 16:12:59 -08002801 return mRootActivityContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002802 }
2803 } finally {
2804 Binder.restoreCallingIdentity(ident);
2805 }
2806 }
2807
2808 @Override
2809 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002810 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002811 long ident = Binder.clearCallingIdentity();
2812 try {
2813 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002814 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002815 }
2816 } finally {
2817 Binder.restoreCallingIdentity(ident);
2818 }
2819 }
2820
2821 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002822 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2823 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2824 long ident = Binder.clearCallingIdentity();
2825 try {
2826 synchronized (mGlobalLock) {
2827 return mRootActivityContainer.getAllStackInfos(displayId);
2828 }
2829 } finally {
2830 Binder.restoreCallingIdentity(ident);
2831 }
2832 }
2833
2834 @Override
2835 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2836 int displayId) {
2837 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2838 long ident = Binder.clearCallingIdentity();
2839 try {
2840 synchronized (mGlobalLock) {
2841 return mRootActivityContainer.getStackInfo(windowingMode, activityType, displayId);
2842 }
2843 } finally {
2844 Binder.restoreCallingIdentity(ident);
2845 }
2846 }
2847
2848 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002849 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002850 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002851 final long callingUid = Binder.getCallingUid();
2852 final long origId = Binder.clearCallingIdentity();
2853 try {
2854 synchronized (mGlobalLock) {
2855 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002856 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002857 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2858 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2859 }
2860 } finally {
2861 Binder.restoreCallingIdentity(origId);
2862 }
2863 }
2864
2865 @Override
2866 public void startLockTaskModeByToken(IBinder token) {
2867 synchronized (mGlobalLock) {
2868 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2869 if (r == null) {
2870 return;
2871 }
Louis Changcdec0802019-11-11 11:45:07 +08002872 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002873 }
2874 }
2875
2876 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002877 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002878 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002879 // This makes inner call to look as if it was initiated by system.
2880 long ident = Binder.clearCallingIdentity();
2881 try {
2882 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002883 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002884 MATCH_TASK_IN_STACKS_ONLY);
2885 if (task == null) {
2886 return;
2887 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002888
2889 // When starting lock task mode the stack must be in front and focused
2890 task.getStack().moveToFront("startSystemLockTaskMode");
2891 startLockTaskModeLocked(task, true /* isSystemCaller */);
2892 }
2893 } finally {
2894 Binder.restoreCallingIdentity(ident);
2895 }
2896 }
2897
2898 @Override
2899 public void stopLockTaskModeByToken(IBinder token) {
2900 synchronized (mGlobalLock) {
2901 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2902 if (r == null) {
2903 return;
2904 }
Louis Changcdec0802019-11-11 11:45:07 +08002905 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002906 }
2907 }
2908
2909 /**
2910 * This API should be called by SystemUI only when user perform certain action to dismiss
2911 * lock task mode. We should only dismiss pinned lock task mode in this case.
2912 */
2913 @Override
2914 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002915 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002916 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2917 }
2918
Louis Changcdec0802019-11-11 11:45:07 +08002919 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002920 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2921 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2922 return;
2923 }
2924
Wale Ogunwaled32da472018-11-16 07:19:28 -08002925 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002926 if (stack == null || task != stack.topTask()) {
2927 throw new IllegalArgumentException("Invalid task, not in foreground");
2928 }
2929
2930 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2931 // system or a specific app.
2932 // * System-initiated requests will only start the pinned mode (screen pinning)
2933 // * App-initiated requests
2934 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2935 // - will start the pinned mode, otherwise
2936 final int callingUid = Binder.getCallingUid();
2937 long ident = Binder.clearCallingIdentity();
2938 try {
2939 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002940 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002941
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002942 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002943 } finally {
2944 Binder.restoreCallingIdentity(ident);
2945 }
2946 }
2947
Louis Changcdec0802019-11-11 11:45:07 +08002948 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002949 final int callingUid = Binder.getCallingUid();
2950 long ident = Binder.clearCallingIdentity();
2951 try {
2952 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002953 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002954 }
2955 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2956 // task and jumping straight into a call in the case of emergency call back.
2957 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2958 if (tm != null) {
2959 tm.showInCallScreen(false);
2960 }
2961 } finally {
2962 Binder.restoreCallingIdentity(ident);
2963 }
2964 }
2965
2966 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002967 public void updateLockTaskPackages(int userId, String[] packages) {
2968 final int callingUid = Binder.getCallingUid();
2969 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2970 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2971 "updateLockTaskPackages()");
2972 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002973 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002974 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2975 + Arrays.toString(packages));
2976 getLockTaskController().updateLockTaskPackages(userId, packages);
2977 }
2978 }
2979
2980 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002981 public boolean isInLockTaskMode() {
2982 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2983 }
2984
2985 @Override
2986 public int getLockTaskModeState() {
2987 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002988 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002989 }
2990 }
2991
2992 @Override
2993 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2994 synchronized (mGlobalLock) {
2995 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2996 if (r != null) {
2997 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08002998 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002999 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003000 }
3001 }
3002 }
3003
3004 @Override
3005 public Bundle getActivityOptions(IBinder token) {
3006 final long origId = Binder.clearCallingIdentity();
3007 try {
3008 synchronized (mGlobalLock) {
3009 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3010 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003011 final ActivityOptions activityOptions = r.takeOptionsLocked(
3012 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003013 return activityOptions == null ? null : activityOptions.toBundle();
3014 }
3015 return null;
3016 }
3017 } finally {
3018 Binder.restoreCallingIdentity(origId);
3019 }
3020 }
3021
3022 @Override
3023 public List<IBinder> getAppTasks(String callingPackage) {
3024 int callingUid = Binder.getCallingUid();
3025 long ident = Binder.clearCallingIdentity();
3026 try {
3027 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003028 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003029 }
3030 } finally {
3031 Binder.restoreCallingIdentity(ident);
3032 }
3033 }
3034
3035 @Override
3036 public void finishVoiceTask(IVoiceInteractionSession session) {
3037 synchronized (mGlobalLock) {
3038 final long origId = Binder.clearCallingIdentity();
3039 try {
3040 // TODO: VI Consider treating local voice interactions and voice tasks
3041 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08003042 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003043 } finally {
3044 Binder.restoreCallingIdentity(origId);
3045 }
3046 }
3047
3048 }
3049
3050 @Override
3051 public boolean isTopOfTask(IBinder token) {
3052 synchronized (mGlobalLock) {
3053 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003054 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003055 }
3056 }
3057
3058 @Override
3059 public void notifyLaunchTaskBehindComplete(IBinder token) {
3060 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3061 }
3062
3063 @Override
3064 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003065 mH.post(() -> {
3066 synchronized (mGlobalLock) {
3067 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003068 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003069 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003070 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003071 } catch (RemoteException e) {
3072 }
3073 }
3074 }
3075
3076 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003077 }
3078
3079 /** Called from an app when assist data is ready. */
3080 @Override
3081 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3082 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003083 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003084 synchronized (pae) {
3085 pae.result = extras;
3086 pae.structure = structure;
3087 pae.content = content;
3088 if (referrer != null) {
3089 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3090 }
3091 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003092 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003093 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003094 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003095 structure.setHomeActivity(pae.isHome);
3096 }
3097 pae.haveResult = true;
3098 pae.notifyAll();
3099 if (pae.intent == null && pae.receiver == null) {
3100 // Caller is just waiting for the result.
3101 return;
3102 }
3103 }
3104 // We are now ready to launch the assist activity.
3105 IAssistDataReceiver sendReceiver = null;
3106 Bundle sendBundle = null;
3107 synchronized (mGlobalLock) {
3108 buildAssistBundleLocked(pae, extras);
3109 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003110 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003111 if (!exists) {
3112 // Timed out.
3113 return;
3114 }
3115
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003116 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003117 // Caller wants result sent back to them.
3118 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003119 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003120 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003121 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3122 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003123 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3124 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3125 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3126 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3127 }
3128 }
3129 if (sendReceiver != null) {
3130 try {
3131 sendReceiver.onHandleAssistData(sendBundle);
3132 } catch (RemoteException e) {
3133 }
3134 return;
3135 }
3136
3137 final long ident = Binder.clearCallingIdentity();
3138 try {
3139 if (TextUtils.equals(pae.intent.getAction(),
3140 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003141 // Start voice interaction through VoiceInteractionManagerService.
3142 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3143 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003144 } else {
3145 pae.intent.replaceExtras(pae.extras);
3146 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3147 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3148 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003149 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003150
3151 try {
3152 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3153 } catch (ActivityNotFoundException e) {
3154 Slog.w(TAG, "No activity to handle assist action.", e);
3155 }
3156 }
3157 } finally {
3158 Binder.restoreCallingIdentity(ident);
3159 }
3160 }
3161
3162 @Override
3163 public int addAppTask(IBinder activityToken, Intent intent,
3164 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3165 final int callingUid = Binder.getCallingUid();
3166 final long callingIdent = Binder.clearCallingIdentity();
3167
3168 try {
3169 synchronized (mGlobalLock) {
3170 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3171 if (r == null) {
3172 throw new IllegalArgumentException("Activity does not exist; token="
3173 + activityToken);
3174 }
3175 ComponentName comp = intent.getComponent();
3176 if (comp == null) {
3177 throw new IllegalArgumentException("Intent " + intent
3178 + " must specify explicit component");
3179 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003180 if (thumbnail.getWidth() != mThumbnailWidth
3181 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003182 throw new IllegalArgumentException("Bad thumbnail size: got "
3183 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003184 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003185 }
3186 if (intent.getSelector() != null) {
3187 intent.setSelector(null);
3188 }
3189 if (intent.getSourceBounds() != null) {
3190 intent.setSourceBounds(null);
3191 }
3192 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3193 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3194 // The caller has added this as an auto-remove task... that makes no
3195 // sense, so turn off auto-remove.
3196 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3197 }
3198 }
3199 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3200 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3201 if (ainfo.applicationInfo.uid != callingUid) {
3202 throw new SecurityException(
3203 "Can't add task for another application: target uid="
3204 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3205 }
3206
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003207 final ActivityStack stack = r.getActivityStack();
Louis Changcdec0802019-11-11 11:45:07 +08003208 final Task task = stack.createTask(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003209 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003210 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003211 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003212 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003213 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003214 return INVALID_TASK_ID;
3215 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003216 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003217
3218 // TODO: Send the thumbnail to WM to store it.
3219
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003220 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003221 }
3222 } finally {
3223 Binder.restoreCallingIdentity(callingIdent);
3224 }
3225 }
3226
3227 @Override
3228 public Point getAppTaskThumbnailSize() {
3229 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003230 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003231 }
3232 }
3233
3234 @Override
3235 public void setTaskResizeable(int taskId, int resizeableMode) {
3236 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08003237 final Task task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003238 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3239 if (task == null) {
3240 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3241 return;
3242 }
3243 task.setResizeMode(resizeableMode);
3244 }
3245 }
3246
3247 @Override
3248 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003249 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003250 long ident = Binder.clearCallingIdentity();
3251 try {
3252 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08003253 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003254 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003255 if (task == null) {
3256 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3257 return;
3258 }
3259 // Place the task in the right stack if it isn't there already based on
3260 // the requested bounds.
3261 // The stack transition logic is:
3262 // - a null bounds on a freeform task moves that task to fullscreen
3263 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3264 // that task to freeform
3265 // - otherwise the task is not moved
3266 ActivityStack stack = task.getStack();
3267 if (!task.getWindowConfiguration().canResizeTask()) {
3268 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3269 }
3270 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3271 stack = stack.getDisplay().getOrCreateStack(
3272 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3273 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3274 stack = stack.getDisplay().getOrCreateStack(
3275 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3276 }
3277
3278 // Reparent the task to the right stack if necessary
3279 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3280 if (stack != task.getStack()) {
3281 // Defer resume until the task is resized below
3282 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3283 DEFER_RESUME, "resizeTask");
3284 preserveWindow = false;
3285 }
3286
3287 // After reparenting (which only resizes the task to the stack bounds), resize the
3288 // task to the actual bounds provided
3289 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3290 }
3291 } finally {
3292 Binder.restoreCallingIdentity(ident);
3293 }
3294 }
3295
Evan Roskyddedfd42019-10-04 13:38:38 -07003296 private void sanitizeAndApplyConfigChange(ConfigurationContainer container,
3297 WindowContainerTransaction.Change change) {
Evan Rosky282ee672019-11-13 15:50:46 -08003298 if (!(container instanceof Task || container instanceof ActivityStack)) {
Evan Roskyddedfd42019-10-04 13:38:38 -07003299 throw new RuntimeException("Invalid token in task transaction");
3300 }
3301 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3302 // masks here.
3303 int configMask = change.getConfigSetMask();
3304 int windowMask = change.getWindowSetMask();
3305 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3306 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3307 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
3308 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3309 c.setTo(change.getConfiguration(), configMask, windowMask);
3310 container.onRequestedOverrideConfigurationChanged(c);
3311 }
3312
3313 @Override
3314 public void applyContainerTransaction(WindowContainerTransaction t) {
3315 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
3316 long ident = Binder.clearCallingIdentity();
3317 try {
3318 if (t == null) {
3319 return;
3320 }
3321 synchronized (mGlobalLock) {
3322 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3323 t.getChanges().entrySet().iterator();
3324 while (entries.hasNext()) {
3325 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3326 entries.next();
3327 final ConfigurationContainer cc = ConfigurationContainer.RemoteToken.fromBinder(
3328 entry.getKey()).getContainer();
3329 sanitizeAndApplyConfigChange(cc, entry.getValue());
3330 }
3331 }
3332 } finally {
3333 Binder.restoreCallingIdentity(ident);
3334 }
3335 }
3336
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003337 @Override
3338 public boolean releaseActivityInstance(IBinder token) {
3339 synchronized (mGlobalLock) {
3340 final long origId = Binder.clearCallingIdentity();
3341 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003342 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3343 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003344 return false;
3345 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003346 r.destroyImmediately(true /* removeFromApp */, "app-req");
3347 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003348 } finally {
3349 Binder.restoreCallingIdentity(origId);
3350 }
3351 }
3352 }
3353
3354 @Override
3355 public void releaseSomeActivities(IApplicationThread appInt) {
3356 synchronized (mGlobalLock) {
3357 final long origId = Binder.clearCallingIdentity();
3358 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003359 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003360 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003361 } finally {
3362 Binder.restoreCallingIdentity(origId);
3363 }
3364 }
3365 }
3366
3367 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003368 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003369 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 != PackageManager.PERMISSION_GRANTED) {
3371 throw new SecurityException("Requires permission "
3372 + android.Manifest.permission.DEVICE_POWER);
3373 }
3374
3375 synchronized (mGlobalLock) {
3376 long ident = Binder.clearCallingIdentity();
3377 if (mKeyguardShown != keyguardShowing) {
3378 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003379 final Message msg = PooledLambda.obtainMessage(
3380 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3381 keyguardShowing);
3382 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383 }
3384 try {
wilsonshih177261f2019-02-22 12:02:18 +08003385 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003386 } finally {
3387 Binder.restoreCallingIdentity(ident);
3388 }
3389 }
3390
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003391 mH.post(() -> {
3392 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3393 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3394 }
3395 });
3396 }
3397
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003398 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003399 mH.post(() -> {
3400 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3401 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3402 }
3403 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 }
3405
3406 @Override
3407 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003408 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3409 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003410
3411 final File passedIconFile = new File(filePath);
3412 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3413 passedIconFile.getName());
3414 if (!legitIconFile.getPath().equals(filePath)
3415 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3416 throw new IllegalArgumentException("Bad file path: " + filePath
3417 + " passed for userId " + userId);
3418 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003419 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003420 }
3421
3422 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003423 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003424 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003425 synchronized (mGlobalLock) {
3426 final long ident = Binder.clearCallingIdentity();
3427 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003428 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003429 if (stack == null) {
3430 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3431 return;
3432 }
3433 if (!stack.isActivityTypeStandardOrUndefined()) {
3434 throw new IllegalArgumentException(
3435 "Removing non-standard stack is not allowed.");
3436 }
3437 mStackSupervisor.removeStack(stack);
3438 } finally {
3439 Binder.restoreCallingIdentity(ident);
3440 }
3441 }
3442 }
3443
3444 @Override
3445 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003446 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003447
3448 synchronized (mGlobalLock) {
3449 final long ident = Binder.clearCallingIdentity();
3450 try {
3451 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3452 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003453 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003454 } finally {
3455 Binder.restoreCallingIdentity(ident);
3456 }
3457 }
3458 }
3459
3460 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003461 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003462 synchronized (mGlobalLock) {
3463 long ident = Binder.clearCallingIdentity();
3464 try {
3465 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3466 if (r == null) {
3467 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003468 "toggleFreeformWindowingMode: No activity record matching token="
3469 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003470 }
3471
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003472 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003473 if (stack == null) {
3474 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3475 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003476 }
3477
Yunfan Chend967af82019-01-17 18:30:18 +09003478 if (!stack.inFreeformWindowingMode()
3479 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3480 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3481 + "toggle between fullscreen and freeform.");
3482 }
3483
3484 if (stack.inFreeformWindowingMode()) {
3485 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003486 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003487 throw new IllegalStateException("Size-compat windows are currently not"
3488 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003489 } else if (stack.getParent().inFreeformWindowingMode()) {
3490 // If the window is on a freeform display, set it to undefined. It will be
3491 // resolved to freeform and it can adjust windowing mode when the display mode
3492 // changes in runtime.
3493 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003494 } else {
3495 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3496 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003497 } finally {
3498 Binder.restoreCallingIdentity(ident);
3499 }
3500 }
3501 }
3502
3503 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3504 @Override
3505 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003506 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003507 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003508 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003509 }
3510
3511 /** Unregister a task stack listener so that it stops receiving callbacks. */
3512 @Override
3513 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003514 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003515 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003516 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003517 }
3518
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003519 @Override
3520 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3521 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3522 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3523 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3524 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3525 }
3526
3527 @Override
3528 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3529 IBinder activityToken, int flags) {
3530 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3531 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3532 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3533 }
3534
3535 @Override
3536 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3537 Bundle args) {
3538 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3539 true /* focused */, true /* newSessionId */, userHandle, args,
3540 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3541 }
3542
3543 @Override
3544 public Bundle getAssistContextExtras(int requestType) {
3545 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3546 null, null, true /* focused */, true /* newSessionId */,
3547 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3548 if (pae == null) {
3549 return null;
3550 }
3551 synchronized (pae) {
3552 while (!pae.haveResult) {
3553 try {
3554 pae.wait();
3555 } catch (InterruptedException e) {
3556 }
3557 }
3558 }
3559 synchronized (mGlobalLock) {
3560 buildAssistBundleLocked(pae, pae.result);
3561 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003562 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003563 }
3564 return pae.extras;
3565 }
3566
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003567 /**
3568 * Binder IPC calls go through the public entry point.
3569 * This can be called with or without the global lock held.
3570 */
3571 private static int checkCallingPermission(String permission) {
3572 return checkPermission(
3573 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3574 }
3575
3576 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003577 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003578 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3579 mAmInternal.enforceCallingPermission(permission, func);
3580 }
3581 }
3582
3583 @VisibleForTesting
3584 int checkGetTasksPermission(String permission, int pid, int uid) {
3585 return checkPermission(permission, pid, uid);
3586 }
3587
3588 static int checkPermission(String permission, int pid, int uid) {
3589 if (permission == null) {
3590 return PackageManager.PERMISSION_DENIED;
3591 }
3592 return checkComponentPermission(permission, pid, uid, -1, true);
3593 }
3594
Wale Ogunwale214f3482018-10-04 11:00:47 -07003595 public static int checkComponentPermission(String permission, int pid, int uid,
3596 int owningUid, boolean exported) {
3597 return ActivityManagerService.checkComponentPermission(
3598 permission, pid, uid, owningUid, exported);
3599 }
3600
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003601 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3602 if (getRecentTasks().isCallerRecents(callingUid)) {
3603 // Always allow the recents component to get tasks
3604 return true;
3605 }
3606
3607 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3608 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3609 if (!allowed) {
3610 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3611 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3612 // Temporary compatibility: some existing apps on the system image may
3613 // still be requesting the old permission and not switched to the new
3614 // one; if so, we'll still allow them full access. This means we need
3615 // to see if they are holding the old permission and are a system app.
3616 try {
3617 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3618 allowed = true;
3619 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3620 + " is using old GET_TASKS but privileged; allowing");
3621 }
3622 } catch (RemoteException e) {
3623 }
3624 }
3625 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3626 + " does not hold REAL_GET_TASKS; limiting output");
3627 }
3628 return allowed;
3629 }
3630
Nicholas Sauer0259e532019-08-30 08:24:55 -07003631 boolean isCrossUserAllowed(int pid, int uid) {
3632 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3633 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3634 }
3635
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003636 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3637 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3638 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3639 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003640 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003641 "enqueueAssistContext()");
3642
3643 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003644 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003645 if (activity == null) {
3646 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3647 return null;
3648 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003649 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003650 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3651 return null;
3652 }
3653 if (focused) {
3654 if (activityToken != null) {
3655 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3656 if (activity != caller) {
3657 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3658 + " is not current top " + activity);
3659 return null;
3660 }
3661 }
3662 } else {
3663 activity = ActivityRecord.forTokenLocked(activityToken);
3664 if (activity == null) {
3665 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3666 + " couldn't be found");
3667 return null;
3668 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003669 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003670 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3671 return null;
3672 }
3673 }
3674
3675 PendingAssistExtras pae;
3676 Bundle extras = new Bundle();
3677 if (args != null) {
3678 extras.putAll(args);
3679 }
3680 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003681 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003682
3683 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3684 userHandle);
3685 pae.isHome = activity.isActivityTypeHome();
3686
3687 // Increment the sessionId if necessary
3688 if (newSessionId) {
3689 mViSessionId++;
3690 }
3691 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003692 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3693 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003694 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003695 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003696 } catch (RemoteException e) {
3697 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3698 return null;
3699 }
3700 return pae;
3701 }
3702 }
3703
3704 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3705 if (result != null) {
3706 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3707 }
3708 if (pae.hint != null) {
3709 pae.extras.putBoolean(pae.hint, true);
3710 }
3711 }
3712
3713 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3714 IAssistDataReceiver receiver;
3715 synchronized (mGlobalLock) {
3716 mPendingAssistExtras.remove(pae);
3717 receiver = pae.receiver;
3718 }
3719 if (receiver != null) {
3720 // Caller wants result sent back to them.
3721 Bundle sendBundle = new Bundle();
3722 // At least return the receiver extras
3723 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3724 try {
3725 pae.receiver.onHandleAssistData(sendBundle);
3726 } catch (RemoteException e) {
3727 }
3728 }
3729 }
3730
3731 public class PendingAssistExtras extends Binder implements Runnable {
3732 public final ActivityRecord activity;
3733 public boolean isHome;
3734 public final Bundle extras;
3735 public final Intent intent;
3736 public final String hint;
3737 public final IAssistDataReceiver receiver;
3738 public final int userHandle;
3739 public boolean haveResult = false;
3740 public Bundle result = null;
3741 public AssistStructure structure = null;
3742 public AssistContent content = null;
3743 public Bundle receiverExtras;
3744
3745 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3746 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3747 int _userHandle) {
3748 activity = _activity;
3749 extras = _extras;
3750 intent = _intent;
3751 hint = _hint;
3752 receiver = _receiver;
3753 receiverExtras = _receiverExtras;
3754 userHandle = _userHandle;
3755 }
3756
3757 @Override
3758 public void run() {
3759 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3760 synchronized (this) {
3761 haveResult = true;
3762 notifyAll();
3763 }
3764 pendingAssistExtrasTimedOut(this);
3765 }
3766 }
3767
3768 @Override
3769 public boolean isAssistDataAllowedOnCurrentActivity() {
3770 int userId;
3771 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003772 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003773 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3774 return false;
3775 }
3776
Wale Ogunwale21e06482019-11-18 05:14:15 -08003777 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003778 if (activity == null) {
3779 return false;
3780 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003781 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003782 }
3783 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3784 }
3785
3786 @Override
3787 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3788 long ident = Binder.clearCallingIdentity();
3789 try {
3790 synchronized (mGlobalLock) {
3791 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003792 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003793 if (top != caller) {
3794 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3795 + " is not current top " + top);
3796 return false;
3797 }
3798 if (!top.nowVisible) {
3799 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3800 + " is not visible");
3801 return false;
3802 }
3803 }
3804 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3805 token);
3806 } finally {
3807 Binder.restoreCallingIdentity(ident);
3808 }
3809 }
3810
3811 @Override
3812 public boolean isRootVoiceInteraction(IBinder token) {
3813 synchronized (mGlobalLock) {
3814 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3815 if (r == null) {
3816 return false;
3817 }
3818 return r.rootVoiceInteraction;
3819 }
3820 }
3821
Wale Ogunwalef6733932018-06-27 05:14:34 -07003822 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3823 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3824 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3825 if (activityToCallback == null) return;
3826 activityToCallback.setVoiceSessionLocked(voiceSession);
3827
3828 // Inform the activity
3829 try {
3830 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3831 voiceInteractor);
3832 long token = Binder.clearCallingIdentity();
3833 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003834 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003835 } finally {
3836 Binder.restoreCallingIdentity(token);
3837 }
3838 // TODO: VI Should we cache the activity so that it's easier to find later
3839 // rather than scan through all the stacks and activities?
3840 } catch (RemoteException re) {
3841 activityToCallback.clearVoiceSessionLocked();
3842 // TODO: VI Should this terminate the voice session?
3843 }
3844 }
3845
3846 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3847 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3848 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3849 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3850 boolean wasRunningVoice = mRunningVoice != null;
3851 mRunningVoice = session;
3852 if (!wasRunningVoice) {
3853 mVoiceWakeLock.acquire();
3854 updateSleepIfNeededLocked();
3855 }
3856 }
3857 }
3858
3859 void finishRunningVoiceLocked() {
3860 if (mRunningVoice != null) {
3861 mRunningVoice = null;
3862 mVoiceWakeLock.release();
3863 updateSleepIfNeededLocked();
3864 }
3865 }
3866
3867 @Override
3868 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3869 synchronized (mGlobalLock) {
3870 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3871 if (keepAwake) {
3872 mVoiceWakeLock.acquire();
3873 } else {
3874 mVoiceWakeLock.release();
3875 }
3876 }
3877 }
3878 }
3879
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003880 @Override
3881 public ComponentName getActivityClassForToken(IBinder token) {
3882 synchronized (mGlobalLock) {
3883 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3884 if (r == null) {
3885 return null;
3886 }
3887 return r.intent.getComponent();
3888 }
3889 }
3890
3891 @Override
3892 public String getPackageForToken(IBinder token) {
3893 synchronized (mGlobalLock) {
3894 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3895 if (r == null) {
3896 return null;
3897 }
3898 return r.packageName;
3899 }
3900 }
3901
3902 @Override
3903 public void showLockTaskEscapeMessage(IBinder token) {
3904 synchronized (mGlobalLock) {
3905 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3906 if (r == null) {
3907 return;
3908 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003909 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003910 }
3911 }
3912
3913 @Override
3914 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003915 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003916 final long token = Binder.clearCallingIdentity();
3917 try {
3918 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003919 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003920 }
3921 } finally {
3922 Binder.restoreCallingIdentity(token);
3923 }
3924 }
3925
3926 /**
3927 * Try to place task to provided position. The final position might be different depending on
3928 * current user and stacks state. The task will be moved to target stack if it's currently in
3929 * different stack.
3930 */
3931 @Override
3932 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003933 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003934 synchronized (mGlobalLock) {
3935 long ident = Binder.clearCallingIdentity();
3936 try {
3937 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3938 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Changcdec0802019-11-11 11:45:07 +08003939 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003940 if (task == null) {
3941 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3942 + taskId);
3943 }
3944
Wale Ogunwaled32da472018-11-16 07:19:28 -08003945 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003946
3947 if (stack == null) {
3948 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3949 + stackId);
3950 }
3951 if (!stack.isActivityTypeStandardOrUndefined()) {
3952 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3953 + " the position of task " + taskId + " in/to non-standard stack");
3954 }
3955
3956 // TODO: Have the callers of this API call a separate reparent method if that is
3957 // what they intended to do vs. having this method also do reparenting.
3958 if (task.getStack() == stack) {
3959 // Change position in current stack.
3960 stack.positionChildAt(task, position);
3961 } else {
3962 // Reparent to new stack.
3963 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3964 !DEFER_RESUME, "positionTaskInStack");
3965 }
3966 } finally {
3967 Binder.restoreCallingIdentity(ident);
3968 }
3969 }
3970 }
3971
3972 @Override
3973 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3974 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3975 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003976 + Arrays.toString(horizontalSizeConfiguration) + " "
3977 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003978 synchronized (mGlobalLock) {
3979 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3980 if (record == null) {
3981 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3982 + "found for: " + token);
3983 }
3984 record.setSizeConfigurations(horizontalSizeConfiguration,
3985 verticalSizeConfigurations, smallestSizeConfigurations);
3986 }
3987 }
3988
3989 /**
3990 * Dismisses split-screen multi-window mode.
3991 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3992 */
3993 @Override
3994 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003995 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003996 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3997 final long ident = Binder.clearCallingIdentity();
3998 try {
3999 synchronized (mGlobalLock) {
4000 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08004001 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004002 if (stack == null) {
4003 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
4004 return;
4005 }
4006
4007 if (toTop) {
4008 // Caller wants the current split-screen primary stack to be the top stack after
4009 // it goes fullscreen, so move it to the front.
4010 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004011 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004012 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004013 // stack after it goes fullscreen, so we move the focus to the top-most
4014 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004015 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
4016 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
4017 if (otherStack != null) {
4018 otherStack.moveToFront("dismissSplitScreenMode_other");
4019 }
4020 }
4021
Evan Rosky10475742018-09-05 19:02:48 -07004022 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004023 }
4024 } finally {
4025 Binder.restoreCallingIdentity(ident);
4026 }
4027 }
4028
4029 /**
4030 * Dismisses Pip
4031 * @param animate True if the dismissal should be animated.
4032 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4033 * default animation duration should be used.
4034 */
4035 @Override
4036 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004037 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004038 final long ident = Binder.clearCallingIdentity();
4039 try {
4040 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004041 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08004042 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004043 if (stack == null) {
4044 Slog.w(TAG, "dismissPip: pinned stack not found.");
4045 return;
4046 }
4047 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4048 throw new IllegalArgumentException("Stack: " + stack
4049 + " doesn't support animated resize.");
4050 }
4051 if (animate) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004052 stack.animateResizePinnedStack(null /* destBounds */,
4053 null /* sourceHintBounds */, animationDuration,
4054 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004055 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004056 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004057 }
4058 }
4059 } finally {
4060 Binder.restoreCallingIdentity(ident);
4061 }
4062 }
4063
4064 @Override
4065 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004066 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004067 synchronized (mGlobalLock) {
4068 mSuppressResizeConfigChanges = suppress;
4069 }
4070 }
4071
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004072 @Override
4073 // TODO: API should just be about changing windowing modes...
4074 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004075 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004076 "moveTasksToFullscreenStack()");
4077 synchronized (mGlobalLock) {
4078 final long origId = Binder.clearCallingIdentity();
4079 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004080 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004081 if (stack != null){
4082 if (!stack.isActivityTypeStandardOrUndefined()) {
4083 throw new IllegalArgumentException(
4084 "You can't move tasks from non-standard stacks.");
4085 }
4086 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4087 }
4088 } finally {
4089 Binder.restoreCallingIdentity(origId);
4090 }
4091 }
4092 }
4093
4094 /**
4095 * Moves the top activity in the input stackId to the pinned stack.
4096 *
4097 * @param stackId Id of stack to move the top activity to pinned stack.
4098 * @param bounds Bounds to use for pinned stack.
4099 *
4100 * @return True if the top activity of the input stack was successfully moved to the pinned
4101 * stack.
4102 */
4103 @Override
4104 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004105 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004106 "moveTopActivityToPinnedStack()");
4107 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004108 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004109 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4110 + "Device doesn't support picture-in-picture mode");
4111 }
4112
4113 long ident = Binder.clearCallingIdentity();
4114 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004115 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004116 } finally {
4117 Binder.restoreCallingIdentity(ident);
4118 }
4119 }
4120 }
4121
4122 @Override
4123 public boolean isInMultiWindowMode(IBinder token) {
4124 final long origId = Binder.clearCallingIdentity();
4125 try {
4126 synchronized (mGlobalLock) {
4127 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4128 if (r == null) {
4129 return false;
4130 }
4131 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4132 return r.inMultiWindowMode();
4133 }
4134 } finally {
4135 Binder.restoreCallingIdentity(origId);
4136 }
4137 }
4138
4139 @Override
4140 public boolean isInPictureInPictureMode(IBinder token) {
4141 final long origId = Binder.clearCallingIdentity();
4142 try {
4143 synchronized (mGlobalLock) {
4144 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4145 }
4146 } finally {
4147 Binder.restoreCallingIdentity(origId);
4148 }
4149 }
4150
4151 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004152 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4153 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004154 return false;
4155 }
4156
4157 // If we are animating to fullscreen then we have already dispatched the PIP mode
4158 // changed, so we should reflect that check here as well.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004159 final ActivityStack taskStack = r.getActivityStack();
Yunfan Chen279f5582018-12-12 15:24:50 -08004160 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004161 }
4162
4163 @Override
4164 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4165 final long origId = Binder.clearCallingIdentity();
4166 try {
4167 synchronized (mGlobalLock) {
4168 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4169 "enterPictureInPictureMode", token, params);
4170
4171 // If the activity is already in picture in picture mode, then just return early
4172 if (isInPictureInPictureMode(r)) {
4173 return true;
4174 }
4175
4176 // Activity supports picture-in-picture, now check that we can enter PiP at this
4177 // point, if it is
4178 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4179 false /* beforeStopping */)) {
4180 return false;
4181 }
4182
4183 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004184 synchronized (mGlobalLock) {
4185 // Only update the saved args from the args that are set
4186 r.pictureInPictureArgs.copyOnlySet(params);
4187 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4188 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4189 // Adjust the source bounds by the insets for the transition down
4190 final Rect sourceBounds = new Rect(
4191 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004192 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004193 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004194 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004195 stack.setPictureInPictureAspectRatio(aspectRatio);
4196 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004197 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4198 r.info.applicationInfo.uid, r.shortComponentName,
4199 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004200 logPictureInPictureArgs(params);
4201 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004202 };
4203
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004204 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004205 // If the keyguard is showing or occluded, then try and dismiss it before
4206 // entering picture-in-picture (this will prompt the user to authenticate if the
4207 // device is currently locked).
4208 dismissKeyguard(token, new KeyguardDismissCallback() {
4209 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004210 public void onDismissSucceeded() {
4211 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004212 }
4213 }, null /* message */);
4214 } else {
4215 // Enter picture in picture immediately otherwise
4216 enterPipRunnable.run();
4217 }
4218 return true;
4219 }
4220 } finally {
4221 Binder.restoreCallingIdentity(origId);
4222 }
4223 }
4224
4225 @Override
4226 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4227 final long origId = Binder.clearCallingIdentity();
4228 try {
4229 synchronized (mGlobalLock) {
4230 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4231 "setPictureInPictureParams", token, params);
4232
4233 // Only update the saved args from the args that are set
4234 r.pictureInPictureArgs.copyOnlySet(params);
4235 if (r.inPinnedWindowingMode()) {
4236 // If the activity is already in picture-in-picture, update the pinned stack now
4237 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4238 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004239 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004240 if (!stack.isAnimatingBoundsToFullscreen()) {
4241 stack.setPictureInPictureAspectRatio(
4242 r.pictureInPictureArgs.getAspectRatio());
4243 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4244 }
4245 }
4246 logPictureInPictureArgs(params);
4247 }
4248 } finally {
4249 Binder.restoreCallingIdentity(origId);
4250 }
4251 }
4252
4253 @Override
4254 public int getMaxNumPictureInPictureActions(IBinder token) {
4255 // Currently, this is a static constant, but later, we may change this to be dependent on
4256 // the context of the activity
4257 return 3;
4258 }
4259
4260 private void logPictureInPictureArgs(PictureInPictureParams params) {
4261 if (params.hasSetActions()) {
4262 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4263 params.getActions().size());
4264 }
4265 if (params.hasSetAspectRatio()) {
4266 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4267 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4268 MetricsLogger.action(lm);
4269 }
4270 }
4271
4272 /**
4273 * Checks the state of the system and the activity associated with the given {@param token} to
4274 * verify that picture-in-picture is supported for that activity.
4275 *
4276 * @return the activity record for the given {@param token} if all the checks pass.
4277 */
4278 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4279 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004280 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004281 throw new IllegalStateException(caller
4282 + ": Device doesn't support picture-in-picture mode.");
4283 }
4284
4285 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4286 if (r == null) {
4287 throw new IllegalStateException(caller
4288 + ": Can't find activity for token=" + token);
4289 }
4290
4291 if (!r.supportsPictureInPicture()) {
4292 throw new IllegalStateException(caller
4293 + ": Current activity does not support picture-in-picture.");
4294 }
4295
4296 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004297 && !mWindowManager.isValidPictureInPictureAspectRatio(
4298 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004299 final float minAspectRatio = mContext.getResources().getFloat(
4300 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4301 final float maxAspectRatio = mContext.getResources().getFloat(
4302 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4303 throw new IllegalArgumentException(String.format(caller
4304 + ": Aspect ratio is too extreme (must be between %f and %f).",
4305 minAspectRatio, maxAspectRatio));
4306 }
4307
4308 // Truncate the number of actions if necessary
4309 params.truncateActions(getMaxNumPictureInPictureActions(token));
4310
4311 return r;
4312 }
4313
4314 @Override
4315 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004316 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004317 synchronized (mGlobalLock) {
4318 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4319 if (r == null) {
4320 throw new IllegalArgumentException("Activity does not exist; token="
4321 + activityToken);
4322 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004323 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004324 }
4325 }
4326
4327 @Override
4328 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4329 Rect tempDockedTaskInsetBounds,
4330 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004331 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004332 long ident = Binder.clearCallingIdentity();
4333 try {
4334 synchronized (mGlobalLock) {
4335 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4336 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4337 PRESERVE_WINDOWS);
4338 }
4339 } finally {
4340 Binder.restoreCallingIdentity(ident);
4341 }
4342 }
4343
4344 @Override
4345 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004346 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004347 final long ident = Binder.clearCallingIdentity();
4348 try {
4349 synchronized (mGlobalLock) {
4350 mStackSupervisor.setSplitScreenResizing(resizing);
4351 }
4352 } finally {
4353 Binder.restoreCallingIdentity(ident);
4354 }
4355 }
4356
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004357 /**
4358 * Check that we have the features required for VR-related API calls, and throw an exception if
4359 * not.
4360 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004361 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004362 if (!mContext.getPackageManager().hasSystemFeature(
4363 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4364 throw new UnsupportedOperationException("VR mode not supported on this device!");
4365 }
4366 }
4367
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004368 @Override
4369 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004370 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004371
4372 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4373
4374 ActivityRecord r;
4375 synchronized (mGlobalLock) {
4376 r = ActivityRecord.isInStackLocked(token);
4377 }
4378
4379 if (r == null) {
4380 throw new IllegalArgumentException();
4381 }
4382
4383 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004384 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004385 VrManagerInternal.NO_ERROR) {
4386 return err;
4387 }
4388
4389 // Clear the binder calling uid since this path may call moveToTask().
4390 final long callingId = Binder.clearCallingIdentity();
4391 try {
4392 synchronized (mGlobalLock) {
4393 r.requestedVrComponent = (enabled) ? packageName : null;
4394
4395 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004396 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004397 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004398 }
4399 return 0;
4400 }
4401 } finally {
4402 Binder.restoreCallingIdentity(callingId);
4403 }
4404 }
4405
4406 @Override
4407 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4408 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4409 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004410 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004411 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4412 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4413 }
Louis Changcdec0802019-11-11 11:45:07 +08004414 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004415 || activity.voiceSession != null) {
4416 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4417 return;
4418 }
4419 if (activity.pendingVoiceInteractionStart) {
4420 Slog.w(TAG, "Pending start of voice interaction already.");
4421 return;
4422 }
4423 activity.pendingVoiceInteractionStart = true;
4424 }
4425 LocalServices.getService(VoiceInteractionManagerInternal.class)
4426 .startLocalVoiceInteraction(callingActivity, options);
4427 }
4428
4429 @Override
4430 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4431 LocalServices.getService(VoiceInteractionManagerInternal.class)
4432 .stopLocalVoiceInteraction(callingActivity);
4433 }
4434
4435 @Override
4436 public boolean supportsLocalVoiceInteraction() {
4437 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4438 .supportsLocalVoiceInteraction();
4439 }
4440
4441 /** Notifies all listeners when the pinned stack animation starts. */
4442 @Override
4443 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004444 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004445 }
4446
4447 /** Notifies all listeners when the pinned stack animation ends. */
4448 @Override
4449 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004450 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004451 }
4452
4453 @Override
4454 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004455 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004456 final long ident = Binder.clearCallingIdentity();
4457 try {
4458 synchronized (mGlobalLock) {
4459 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4460 }
4461 } finally {
4462 Binder.restoreCallingIdentity(ident);
4463 }
4464 }
4465
4466 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004467 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004468 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004469
4470 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004471 if (mWindowManager == null) {
4472 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4473 return false;
4474 }
4475
4476 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004477 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004478 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004479 }
4480
Riddle Hsua0022cd2019-09-09 21:12:41 +08004481 mH.sendMessage(PooledLambda.obtainMessage(
4482 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4483 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004484
4485 final long origId = Binder.clearCallingIdentity();
4486 try {
4487 if (values != null) {
4488 Settings.System.clearConfiguration(values);
4489 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004490 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004491 UserHandle.USER_NULL, false /* deferResume */,
4492 mTmpUpdateConfigurationResult);
4493 return mTmpUpdateConfigurationResult.changes != 0;
4494 } finally {
4495 Binder.restoreCallingIdentity(origId);
4496 }
4497 }
4498 }
4499
4500 @Override
4501 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4502 CharSequence message) {
4503 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004504 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004505 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4506 }
4507 final long callingId = Binder.clearCallingIdentity();
4508 try {
4509 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004510 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004511 }
4512 } finally {
4513 Binder.restoreCallingIdentity(callingId);
4514 }
4515 }
4516
4517 @Override
4518 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004519 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004520 "cancelTaskWindowTransition()");
4521 final long ident = Binder.clearCallingIdentity();
4522 try {
4523 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08004524 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004525 MATCH_TASK_IN_STACKS_ONLY);
4526 if (task == null) {
4527 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4528 return;
4529 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004530 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004531 }
4532 } finally {
4533 Binder.restoreCallingIdentity(ident);
4534 }
4535 }
4536
4537 @Override
4538 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004539 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004540 final long ident = Binder.clearCallingIdentity();
4541 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004542 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004543 } finally {
4544 Binder.restoreCallingIdentity(ident);
4545 }
4546 }
4547
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004548 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4549 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004550 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004551 synchronized (mGlobalLock) {
4552 task = mRootActivityContainer.anyTaskForId(taskId,
4553 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4554 if (task == null) {
4555 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4556 return null;
4557 }
4558 }
4559 // Don't call this while holding the lock as this operation might hit the disk.
4560 return task.getSnapshot(reducedResolution, restoreFromDisk);
4561 }
4562
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004563 @Override
4564 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4565 synchronized (mGlobalLock) {
4566 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4567 if (r == null) {
4568 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4569 + token);
4570 return;
4571 }
4572 final long origId = Binder.clearCallingIdentity();
4573 try {
4574 r.setDisablePreviewScreenshots(disable);
4575 } finally {
4576 Binder.restoreCallingIdentity(origId);
4577 }
4578 }
4579 }
4580
4581 /** Return the user id of the last resumed activity. */
4582 @Override
4583 public @UserIdInt
4584 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004585 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004586 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4587 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004588 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004589 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004590 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004591 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004592 }
4593 }
4594
4595 @Override
4596 public void updateLockTaskFeatures(int userId, int flags) {
4597 final int callingUid = Binder.getCallingUid();
4598 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004599 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004600 "updateLockTaskFeatures()");
4601 }
4602 synchronized (mGlobalLock) {
4603 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4604 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004605 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004606 }
4607 }
4608
4609 @Override
4610 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4611 synchronized (mGlobalLock) {
4612 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4613 if (r == null) {
4614 return;
4615 }
4616 final long origId = Binder.clearCallingIdentity();
4617 try {
4618 r.setShowWhenLocked(showWhenLocked);
4619 } finally {
4620 Binder.restoreCallingIdentity(origId);
4621 }
4622 }
4623 }
4624
4625 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004626 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4627 synchronized (mGlobalLock) {
4628 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4629 if (r == null) {
4630 return;
4631 }
4632 final long origId = Binder.clearCallingIdentity();
4633 try {
4634 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4635 } finally {
4636 Binder.restoreCallingIdentity(origId);
4637 }
4638 }
4639 }
4640
4641 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004642 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4643 synchronized (mGlobalLock) {
4644 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4645 if (r == null) {
4646 return;
4647 }
4648 final long origId = Binder.clearCallingIdentity();
4649 try {
4650 r.setTurnScreenOn(turnScreenOn);
4651 } finally {
4652 Binder.restoreCallingIdentity(origId);
4653 }
4654 }
4655 }
4656
4657 @Override
4658 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004659 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004660 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004661 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004662 synchronized (mGlobalLock) {
4663 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4664 if (r == null) {
4665 return;
4666 }
4667 final long origId = Binder.clearCallingIdentity();
4668 try {
4669 r.registerRemoteAnimations(definition);
4670 } finally {
4671 Binder.restoreCallingIdentity(origId);
4672 }
4673 }
4674 }
4675
4676 @Override
4677 public void registerRemoteAnimationForNextActivityStart(String packageName,
4678 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004679 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004680 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004681 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004682 synchronized (mGlobalLock) {
4683 final long origId = Binder.clearCallingIdentity();
4684 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004685 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004686 packageName, adapter);
4687 } finally {
4688 Binder.restoreCallingIdentity(origId);
4689 }
4690 }
4691 }
4692
Evan Rosky966759f2019-01-15 10:33:58 -08004693 @Override
4694 public void registerRemoteAnimationsForDisplay(int displayId,
4695 RemoteAnimationDefinition definition) {
4696 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4697 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004698 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004699 synchronized (mGlobalLock) {
4700 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4701 if (display == null) {
4702 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4703 return;
4704 }
4705 final long origId = Binder.clearCallingIdentity();
4706 try {
4707 display.mDisplayContent.registerRemoteAnimations(definition);
4708 } finally {
4709 Binder.restoreCallingIdentity(origId);
4710 }
4711 }
4712 }
4713
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004714 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4715 @Override
4716 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4717 synchronized (mGlobalLock) {
4718 final long origId = Binder.clearCallingIdentity();
4719 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004720 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004721 } finally {
4722 Binder.restoreCallingIdentity(origId);
4723 }
4724 }
4725 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004726
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004727 @Override
4728 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004729 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004730 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004731 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004732 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004733 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004734 }
4735 }
4736
4737 @Override
4738 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004739 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004740 != PERMISSION_GRANTED) {
4741 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4742 + Binder.getCallingPid()
4743 + ", uid=" + Binder.getCallingUid()
4744 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4745 Slog.w(TAG, msg);
4746 throw new SecurityException(msg);
4747 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004748 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004749 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004750 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004751 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004752 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004753 }
4754 }
4755
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004756 @Override
4757 public void stopAppSwitches() {
4758 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4759 synchronized (mGlobalLock) {
4760 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004761 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004762 mDidAppSwitch = false;
4763 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4764 }
4765 }
4766
4767 @Override
4768 public void resumeAppSwitches() {
4769 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4770 synchronized (mGlobalLock) {
4771 // Note that we don't execute any pending app switches... we will
4772 // let those wait until either the timeout, or the next start
4773 // activity request.
4774 mAppSwitchesAllowedTime = 0;
4775 }
4776 }
4777
Ricky Wai906af482019-06-03 17:25:28 +01004778 long getLastStopAppSwitchesTime() {
4779 return mLastStopAppSwitchesTime;
4780 }
4781
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004782 void onStartActivitySetDidAppSwitch() {
4783 if (mDidAppSwitch) {
4784 // This is the second allowed switch since we stopped switches, so now just generally
4785 // allow switches. Use case:
4786 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4787 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4788 // anyone to switch again).
4789 mAppSwitchesAllowedTime = 0;
4790 } else {
4791 mDidAppSwitch = true;
4792 }
4793 }
4794
4795 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004796 boolean shouldDisableNonVrUiLocked() {
4797 return mVrController.shouldDisableNonVrUiLocked();
4798 }
4799
Wale Ogunwale53783742018-09-16 10:21:51 -07004800 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004801 // 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 +00004802 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004803 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004804 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4805 + " to main display for VR");
4806 mRootActivityContainer.moveStackToDisplay(
4807 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004808 }
4809 mH.post(() -> {
4810 if (!mVrController.onVrModeChanged(r)) {
4811 return;
4812 }
4813 synchronized (mGlobalLock) {
4814 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4815 mWindowManager.disableNonVrUi(disableNonVrUi);
4816 if (disableNonVrUi) {
4817 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4818 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004819 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004820 }
4821 }
4822 });
4823 }
4824
Wale Ogunwale53783742018-09-16 10:21:51 -07004825 @Override
4826 public int getPackageScreenCompatMode(String packageName) {
4827 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4828 synchronized (mGlobalLock) {
4829 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4830 }
4831 }
4832
4833 @Override
4834 public void setPackageScreenCompatMode(String packageName, int mode) {
4835 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4836 "setPackageScreenCompatMode");
4837 synchronized (mGlobalLock) {
4838 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4839 }
4840 }
4841
4842 @Override
4843 public boolean getPackageAskScreenCompat(String packageName) {
4844 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4845 synchronized (mGlobalLock) {
4846 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4847 }
4848 }
4849
4850 @Override
4851 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4852 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4853 "setPackageAskScreenCompat");
4854 synchronized (mGlobalLock) {
4855 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4856 }
4857 }
4858
Wale Ogunwale64258362018-10-16 15:13:37 -07004859 public static String relaunchReasonToString(int relaunchReason) {
4860 switch (relaunchReason) {
4861 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4862 return "window_resize";
4863 case RELAUNCH_REASON_FREE_RESIZE:
4864 return "free_resize";
4865 default:
4866 return null;
4867 }
4868 }
4869
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004870 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004871 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004872 }
4873
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004874 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004875 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004876 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4877 }
4878
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004879 boolean isKeyguardLocked() {
4880 return mKeyguardController.isKeyguardLocked();
4881 }
4882
Garfield Tan01548632018-11-27 10:15:48 -08004883 /**
4884 * Clears launch params for the given package.
4885 * @param packageNames the names of the packages of which the launch params are to be cleared
4886 */
4887 @Override
4888 public void clearLaunchParamsForPackages(List<String> packageNames) {
4889 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4890 "clearLaunchParamsForPackages");
4891 synchronized (mGlobalLock) {
4892 for (int i = 0; i < packageNames.size(); ++i) {
4893 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4894 }
4895 }
4896 }
4897
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004898 /**
4899 * Makes the display with the given id a single task instance display. I.e the display can only
4900 * contain one task.
4901 */
4902 @Override
4903 public void setDisplayToSingleTaskInstance(int displayId) {
4904 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4905 "setDisplayToSingleTaskInstance");
4906 final long origId = Binder.clearCallingIdentity();
4907 try {
4908 final ActivityDisplay display =
4909 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4910 if (display != null) {
4911 display.setDisplayToSingleTaskInstance();
4912 }
4913 } finally {
4914 Binder.restoreCallingIdentity(origId);
4915 }
4916 }
4917
Wale Ogunwale31913b52018-10-13 08:29:31 -07004918 void dumpLastANRLocked(PrintWriter pw) {
4919 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4920 if (mLastANRState == null) {
4921 pw.println(" <no ANR has occurred since boot>");
4922 } else {
4923 pw.println(mLastANRState);
4924 }
4925 }
4926
4927 void dumpLastANRTracesLocked(PrintWriter pw) {
4928 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4929
4930 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4931 if (ArrayUtils.isEmpty(files)) {
4932 pw.println(" <no ANR has occurred since boot>");
4933 return;
4934 }
4935 // Find the latest file.
4936 File latest = null;
4937 for (File f : files) {
4938 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4939 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004940 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004941 }
4942 pw.print("File: ");
4943 pw.print(latest.getName());
4944 pw.println();
4945 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4946 String line;
4947 while ((line = in.readLine()) != null) {
4948 pw.println(line);
4949 }
4950 } catch (IOException e) {
4951 pw.print("Unable to read: ");
4952 pw.print(e);
4953 pw.println();
4954 }
4955 }
4956
4957 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4958 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4959 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4960 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4961 }
4962
4963 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4964 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4965 pw.println(header);
4966
Wale Ogunwaled32da472018-11-16 07:19:28 -08004967 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004968 dumpPackage);
4969 boolean needSep = printedAnything;
4970
4971 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004972 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004973 " ResumedActivity: ");
4974 if (printed) {
4975 printedAnything = true;
4976 needSep = false;
4977 }
4978
4979 if (dumpPackage == null) {
4980 if (needSep) {
4981 pw.println();
4982 }
4983 printedAnything = true;
4984 mStackSupervisor.dump(pw, " ");
4985 }
4986
4987 if (!printedAnything) {
4988 pw.println(" (nothing)");
4989 }
4990 }
4991
4992 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004993 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004994 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004995 pw.println(" ");
4996 }
4997
4998 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4999 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5000 getActivityStartController().dump(pw, "", dumpPackage);
5001 }
5002
5003 /**
5004 * There are three things that cmd can be:
5005 * - a flattened component name that matches an existing activity
5006 * - the cmd arg isn't the flattened component name of an existing activity:
5007 * dump all activity whose component contains the cmd as a substring
5008 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005009 * <p>
5010 * The caller should not hold lock when calling this method because it will wait for the
5011 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005012 *
5013 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5014 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5015 */
5016 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5017 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5018 ArrayList<ActivityRecord> activities;
5019
5020 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005021 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005022 dumpFocusedStackOnly);
5023 }
5024
5025 if (activities.size() <= 0) {
5026 return false;
5027 }
5028
5029 String[] newArgs = new String[args.length - opti];
5030 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5031
Louis Changcdec0802019-11-11 11:45:07 +08005032 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005033 boolean needSep = false;
5034 for (int i = activities.size() - 1; i >= 0; i--) {
5035 ActivityRecord r = activities.get(i);
5036 if (needSep) {
5037 pw.println();
5038 }
5039 needSep = true;
5040 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005041 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005042 if (lastTask != task) {
5043 lastTask = task;
5044 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005045 pw.print(" id="); pw.print(lastTask.mTaskId);
5046 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005047 if (dumpAll) {
5048 lastTask.dump(pw, " ");
5049 }
5050 }
5051 }
5052 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5053 }
5054 return true;
5055 }
5056
5057 /**
5058 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5059 * there is a thread associated with the activity.
5060 */
5061 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5062 final ActivityRecord r, String[] args, boolean dumpAll) {
5063 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005064 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005065 synchronized (mGlobalLock) {
5066 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5067 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5068 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005069 if (r.hasProcess()) {
5070 pw.println(r.app.getPid());
5071 appThread = r.app.getThread();
5072 } else {
5073 pw.println("(not running)");
5074 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005075 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005076 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005077 }
5078 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005079 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005080 // flush anything that is already in the PrintWriter since the thread is going
5081 // to write to the file descriptor directly
5082 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005083 try (TransferPipe tp = new TransferPipe()) {
5084 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5085 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005086 } catch (IOException e) {
5087 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5088 } catch (RemoteException e) {
5089 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5090 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005091 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005092 }
5093
sanryhuang498e77e2018-12-06 14:57:01 +08005094 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5095 boolean testPssMode) {
5096 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5097 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5098 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005099 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005100 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5101 st.toString());
5102 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005103 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5104 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5105 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005106 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5107 testPssMode);
5108 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005109 }
5110
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005111 int getCurrentUserId() {
5112 return mAmInternal.getCurrentUserId();
5113 }
5114
5115 private void enforceNotIsolatedCaller(String caller) {
5116 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5117 throw new SecurityException("Isolated process not allowed to call " + caller);
5118 }
5119 }
5120
Wale Ogunwalef6733932018-06-27 05:14:34 -07005121 public Configuration getConfiguration() {
5122 Configuration ci;
5123 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005124 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005125 ci.userSetLocale = false;
5126 }
5127 return ci;
5128 }
5129
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005130 /**
5131 * Current global configuration information. Contains general settings for the entire system,
5132 * also corresponds to the merged configuration of the default display.
5133 */
5134 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005135 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005136 }
5137
5138 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5139 boolean initLocale) {
5140 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5141 }
5142
5143 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5144 boolean initLocale, boolean deferResume) {
5145 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5146 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5147 UserHandle.USER_NULL, deferResume);
5148 }
5149
Wale Ogunwale59507092018-10-29 09:00:30 -07005150 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005151 final long origId = Binder.clearCallingIdentity();
5152 try {
5153 synchronized (mGlobalLock) {
5154 updateConfigurationLocked(values, null, false, true, userId,
5155 false /* deferResume */);
5156 }
5157 } finally {
5158 Binder.restoreCallingIdentity(origId);
5159 }
5160 }
5161
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005162 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5163 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5164 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5165 deferResume, null /* result */);
5166 }
5167
5168 /**
5169 * Do either or both things: (1) change the current configuration, and (2)
5170 * make sure the given activity is running with the (now) current
5171 * configuration. Returns true if the activity has been left running, or
5172 * false if <var>starting</var> is being destroyed to match the new
5173 * configuration.
5174 *
5175 * @param userId is only used when persistent parameter is set to true to persist configuration
5176 * for that particular user
5177 */
5178 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5179 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5180 ActivityTaskManagerService.UpdateConfigurationResult result) {
5181 int changes = 0;
5182 boolean kept = true;
5183
Riddle Hsua0022cd2019-09-09 21:12:41 +08005184 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005185 try {
5186 if (values != null) {
5187 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5188 deferResume);
5189 }
5190
5191 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5192 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005193 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005194 }
5195
5196 if (result != null) {
5197 result.changes = changes;
5198 result.activityRelaunched = !kept;
5199 }
5200 return kept;
5201 }
5202
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005203 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005204 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005205 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005206
5207 final ActivityDisplay defaultDisplay =
5208 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5209
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005210 mTempConfig.setTo(getGlobalConfiguration());
5211 final int changes = mTempConfig.updateFrom(values);
5212 if (changes == 0) {
5213 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5214 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5215 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5216 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005217 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005218 return 0;
5219 }
5220
5221 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5222 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005223 writeConfigurationChanged(changes);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005224 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5225 values.colorMode,
5226 values.densityDpi,
5227 values.fontScale,
5228 values.hardKeyboardHidden,
5229 values.keyboard,
5230 values.keyboardHidden,
5231 values.mcc,
5232 values.mnc,
5233 values.navigation,
5234 values.navigationHidden,
5235 values.orientation,
5236 values.screenHeightDp,
5237 values.screenLayout,
5238 values.screenWidthDp,
5239 values.smallestScreenWidthDp,
5240 values.touchscreen,
5241 values.uiMode);
5242
5243
5244 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5245 final LocaleList locales = values.getLocales();
5246 int bestLocaleIndex = 0;
5247 if (locales.size() > 1) {
5248 if (mSupportedSystemLocales == null) {
5249 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5250 }
5251 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5252 }
5253 SystemProperties.set("persist.sys.locale",
5254 locales.get(bestLocaleIndex).toLanguageTag());
5255 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005256
5257 final Message m = PooledLambda.obtainMessage(
5258 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5259 locales.get(bestLocaleIndex));
5260 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005261 }
5262
Yunfan Chen75157d72018-07-27 14:47:21 +09005263 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005264
5265 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005266 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005267
5268 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5269 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005270 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005271
5272 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005273 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005274
5275 AttributeCache ac = AttributeCache.instance();
5276 if (ac != null) {
5277 ac.updateConfiguration(mTempConfig);
5278 }
5279
5280 // Make sure all resources in our process are updated right now, so that anyone who is going
5281 // to retrieve resource values after we return will be sure to get the new ones. This is
5282 // especially important during boot, where the first config change needs to guarantee all
5283 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005284 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005285
5286 // We need another copy of global config because we're scheduling some calls instead of
5287 // running them in place. We need to be sure that object we send will be handled unchanged.
5288 final Configuration configCopy = new Configuration(mTempConfig);
5289 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005290 final Message msg = PooledLambda.obtainMessage(
5291 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5292 this, userId, configCopy);
5293 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005294 }
5295
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005296 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5297 for (int i = pidMap.size() - 1; i >= 0; i--) {
5298 final int pid = pidMap.keyAt(i);
5299 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005300 if (DEBUG_CONFIGURATION) {
5301 Slog.v(TAG_CONFIGURATION, "Update process config of "
5302 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005303 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005304 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005305 }
5306
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005307 final Message msg = PooledLambda.obtainMessage(
5308 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5309 mAmInternal, changes, initLocale);
5310 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005311
5312 // Override configuration of the default display duplicates global config, so we need to
5313 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005314 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5315 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005316
5317 return changes;
5318 }
5319
Riddle Hsua0022cd2019-09-09 21:12:41 +08005320 /** @see WindowSurfacePlacer#deferLayout */
5321 void deferWindowLayout() {
5322 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5323 // Reset the reasons at the first entrance because we only care about the changes in the
5324 // deferred scope.
5325 mLayoutReasons = 0;
5326 }
5327
5328 mWindowManager.mWindowPlacerLocked.deferLayout();
5329 }
5330
5331 /** @see WindowSurfacePlacer#continueLayout */
5332 void continueWindowLayout() {
5333 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5334 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5335 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5336 }
5337 }
5338
5339 /**
5340 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5341 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5342 * defer count is gone.
5343 */
5344 void addWindowLayoutReasons(@LayoutReason int reasons) {
5345 mLayoutReasons |= reasons;
5346 }
5347
Wale Ogunwalef6733932018-06-27 05:14:34 -07005348 private void updateEventDispatchingLocked(boolean booted) {
5349 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5350 }
5351
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005352 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5353 final ContentResolver resolver = mContext.getContentResolver();
5354 Settings.System.putConfigurationForUser(resolver, config, userId);
5355 }
5356
5357 private void sendLocaleToMountDaemonMsg(Locale l) {
5358 try {
5359 IBinder service = ServiceManager.getService("mount");
5360 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5361 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5362 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5363 } catch (RemoteException e) {
5364 Log.e(TAG, "Error storing locale for decryption UI", e);
5365 }
5366 }
5367
Alison Cichowlas3e340502018-08-07 17:15:01 -04005368 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5369 mStartActivitySources.remove(permissionToken);
5370 mExpiredStartAsCallerTokens.add(permissionToken);
5371 }
5372
5373 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5374 mExpiredStartAsCallerTokens.remove(permissionToken);
5375 }
5376
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005377 boolean isActivityStartsLoggingEnabled() {
5378 return mAmInternal.isActivityStartsLoggingEnabled();
5379 }
5380
Michal Karpinski8596ded2018-11-14 14:43:48 +00005381 boolean isBackgroundActivityStartsEnabled() {
5382 return mAmInternal.isBackgroundActivityStartsEnabled();
5383 }
5384
Wale Ogunwalef6733932018-06-27 05:14:34 -07005385 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005386 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005387 mWindowManager.enableScreenAfterBoot();
5388
5389 synchronized (mGlobalLock) {
5390 updateEventDispatchingLocked(booted);
5391 }
5392 }
5393
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005394 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5395 if (r == null || !r.hasProcess()) {
5396 return KEY_DISPATCHING_TIMEOUT_MS;
5397 }
5398 return getInputDispatchingTimeoutLocked(r.app);
5399 }
5400
5401 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005402 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005403 }
5404
Wale Ogunwalef6733932018-06-27 05:14:34 -07005405 /**
5406 * Decide based on the configuration whether we should show the ANR,
5407 * crash, etc dialogs. The idea is that if there is no affordance to
5408 * press the on-screen buttons, or the user experience would be more
5409 * greatly impacted than the crash itself, we shouldn't show the dialog.
5410 *
5411 * A thought: SystemUI might also want to get told about this, the Power
5412 * dialog / global actions also might want different behaviors.
5413 */
5414 private void updateShouldShowDialogsLocked(Configuration config) {
5415 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5416 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5417 && config.navigation == Configuration.NAVIGATION_NONAV);
5418 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5419 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5420 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5421 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5422 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5423 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5424 HIDE_ERROR_DIALOGS, 0) != 0;
5425 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5426 }
5427
5428 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5429 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5430 FONT_SCALE, 1.0f, userId);
5431
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005432 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005433 if (getGlobalConfiguration().fontScale == scaleFactor) {
5434 return;
5435 }
5436
5437 final Configuration configuration
5438 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5439 configuration.fontScale = scaleFactor;
5440 updatePersistentConfiguration(configuration, userId);
5441 }
5442 }
5443
5444 // Actually is sleeping or shutting down or whatever else in the future
5445 // is an inactive state.
5446 boolean isSleepingOrShuttingDownLocked() {
5447 return isSleepingLocked() || mShuttingDown;
5448 }
5449
5450 boolean isSleepingLocked() {
5451 return mSleeping;
5452 }
5453
Riddle Hsu16567132018-08-16 21:37:47 +08005454 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005455 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005456 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005457 if (task.isActivityTypeStandard()) {
5458 if (mCurAppTimeTracker != r.appTimeTracker) {
5459 // We are switching app tracking. Complete the current one.
5460 if (mCurAppTimeTracker != null) {
5461 mCurAppTimeTracker.stop();
5462 mH.obtainMessage(
5463 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005464 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005465 mCurAppTimeTracker = null;
5466 }
5467 if (r.appTimeTracker != null) {
5468 mCurAppTimeTracker = r.appTimeTracker;
5469 startTimeTrackingFocusedActivityLocked();
5470 }
5471 } else {
5472 startTimeTrackingFocusedActivityLocked();
5473 }
5474 } else {
5475 r.appTimeTracker = null;
5476 }
5477 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5478 // TODO: Probably not, because we don't want to resume voice on switching
5479 // back to this activity
5480 if (task.voiceInteractor != null) {
5481 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5482 } else {
5483 finishRunningVoiceLocked();
5484
5485 if (mLastResumedActivity != null) {
5486 final IVoiceInteractionSession session;
5487
Louis Changcdec0802019-11-11 11:45:07 +08005488 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005489 if (lastResumedActivityTask != null
5490 && lastResumedActivityTask.voiceSession != null) {
5491 session = lastResumedActivityTask.voiceSession;
5492 } else {
5493 session = mLastResumedActivity.voiceSession;
5494 }
5495
5496 if (session != null) {
5497 // We had been in a voice interaction session, but now focused has
5498 // move to something different. Just finish the session, we can't
5499 // return to it and retain the proper state and synchronization with
5500 // the voice interaction service.
5501 finishVoiceTask(session);
5502 }
5503 }
5504 }
5505
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005506 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5507 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005508 }
5509 updateResumedAppTrace(r);
5510 mLastResumedActivity = r;
5511
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005512 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005513
5514 applyUpdateLockStateLocked(r);
5515 applyUpdateVrModeLocked(r);
5516
Jeff Changd136e772019-11-05 20:33:52 +08005517 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005518 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005519 r == null ? "NULL" : r.shortComponentName,
5520 reason);
5521 }
5522
5523 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5524 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005525 final ActivityTaskManagerInternal.SleepToken token =
5526 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005527 updateSleepIfNeededLocked();
5528 return token;
5529 }
5530 }
5531
5532 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005533 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005534 final boolean wasSleeping = mSleeping;
5535 boolean updateOomAdj = false;
5536
5537 if (!shouldSleep) {
5538 // If wasSleeping is true, we need to wake up activity manager state from when
5539 // we started sleeping. In either case, we need to apply the sleep tokens, which
5540 // will wake up stacks or put them to sleep as appropriate.
5541 if (wasSleeping) {
5542 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005543 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5544 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005545 startTimeTrackingFocusedActivityLocked();
5546 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005547 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005548 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5549 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005550 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005551 if (wasSleeping) {
5552 updateOomAdj = true;
5553 }
5554 } else if (!mSleeping && shouldSleep) {
5555 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005556 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5557 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005558 if (mCurAppTimeTracker != null) {
5559 mCurAppTimeTracker.stop();
5560 }
5561 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005562 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005563 mStackSupervisor.goingToSleepLocked();
5564 updateResumedAppTrace(null /* resumed */);
5565 updateOomAdj = true;
5566 }
5567 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005568 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005569 }
5570 }
5571
5572 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005573 mH.removeCallbacks(mUpdateOomAdjRunnable);
5574 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005575 }
5576
Wale Ogunwale53783742018-09-16 10:21:51 -07005577 void updateCpuStats() {
5578 mH.post(mAmInternal::updateCpuStats);
5579 }
5580
Hui Yu03d12402018-12-06 18:00:37 -08005581 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5582 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005583 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5584 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005585 mH.sendMessage(m);
5586 }
5587
Hui Yu03d12402018-12-06 18:00:37 -08005588 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005589 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005590 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005591 if (task != null) {
5592 final ActivityRecord rootActivity = task.getRootActivity();
5593 if (rootActivity != null) {
5594 taskRoot = rootActivity.mActivityComponent;
5595 }
5596 }
5597
Hui Yu03d12402018-12-06 18:00:37 -08005598 final Message m = PooledLambda.obtainMessage(
5599 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005600 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005601 mH.sendMessage(m);
5602 }
5603
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005604 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5605 String hostingType) {
5606 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005607 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5608 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005609 + activity.processName);
5610 }
5611 // Post message to start process to avoid possible deadlock of calling into AMS with the
5612 // ATMS lock held.
5613 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5614 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5615 isTop, hostingType, activity.intent.getComponent());
5616 mH.sendMessage(m);
5617 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005618 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005619 }
5620 }
5621
Wale Ogunwale53783742018-09-16 10:21:51 -07005622 void setBooting(boolean booting) {
5623 mAmInternal.setBooting(booting);
5624 }
5625
5626 boolean isBooting() {
5627 return mAmInternal.isBooting();
5628 }
5629
5630 void setBooted(boolean booted) {
5631 mAmInternal.setBooted(booted);
5632 }
5633
5634 boolean isBooted() {
5635 return mAmInternal.isBooted();
5636 }
5637
5638 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5639 mH.post(() -> {
5640 if (finishBooting) {
5641 mAmInternal.finishBooting();
5642 }
5643 if (enableScreen) {
5644 mInternal.enableScreenAfterBoot(isBooted());
5645 }
5646 });
5647 }
5648
5649 void setHeavyWeightProcess(ActivityRecord root) {
5650 mHeavyWeightProcess = root.app;
5651 final Message m = PooledLambda.obtainMessage(
5652 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005653 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005654 mH.sendMessage(m);
5655 }
5656
5657 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5658 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5659 return;
5660 }
5661
5662 mHeavyWeightProcess = null;
5663 final Message m = PooledLambda.obtainMessage(
5664 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5665 proc.mUserId);
5666 mH.sendMessage(m);
5667 }
5668
5669 private void cancelHeavyWeightProcessNotification(int userId) {
5670 final INotificationManager inm = NotificationManager.getService();
5671 if (inm == null) {
5672 return;
5673 }
5674 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005675 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005676 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5677 } catch (RuntimeException e) {
5678 Slog.w(TAG, "Error canceling notification for service", e);
5679 } catch (RemoteException e) {
5680 }
5681
5682 }
5683
5684 private void postHeavyWeightProcessNotification(
5685 WindowProcessController proc, Intent intent, int userId) {
5686 if (proc == null) {
5687 return;
5688 }
5689
5690 final INotificationManager inm = NotificationManager.getService();
5691 if (inm == null) {
5692 return;
5693 }
5694
5695 try {
5696 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5697 String text = mContext.getString(R.string.heavy_weight_notification,
5698 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5699 Notification notification =
5700 new Notification.Builder(context,
5701 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5702 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5703 .setWhen(0)
5704 .setOngoing(true)
5705 .setTicker(text)
5706 .setColor(mContext.getColor(
5707 com.android.internal.R.color.system_notification_accent_color))
5708 .setContentTitle(text)
5709 .setContentText(
5710 mContext.getText(R.string.heavy_weight_notification_detail))
5711 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5712 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5713 new UserHandle(userId)))
5714 .build();
5715 try {
5716 inm.enqueueNotificationWithTag("android", "android", null,
5717 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5718 } catch (RuntimeException e) {
5719 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5720 } catch (RemoteException e) {
5721 }
5722 } catch (PackageManager.NameNotFoundException e) {
5723 Slog.w(TAG, "Unable to create context for heavy notification", e);
5724 }
5725
5726 }
5727
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005728 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5729 IBinder token, String resultWho, int requestCode, Intent[] intents,
5730 String[] resolvedTypes, int flags, Bundle bOptions) {
5731
5732 ActivityRecord activity = null;
5733 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5734 activity = ActivityRecord.isInStackLocked(token);
5735 if (activity == null) {
5736 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5737 return null;
5738 }
5739 if (activity.finishing) {
5740 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5741 return null;
5742 }
5743 }
5744
5745 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5746 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5747 bOptions);
5748 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5749 if (noCreate) {
5750 return rec;
5751 }
5752 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5753 if (activity.pendingResults == null) {
5754 activity.pendingResults = new HashSet<>();
5755 }
5756 activity.pendingResults.add(rec.ref);
5757 }
5758 return rec;
5759 }
5760
Andrii Kulian52d255c2018-07-13 11:32:19 -07005761 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005762 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005763 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005764 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5765 mCurAppTimeTracker.start(resumedActivity.packageName);
5766 }
5767 }
5768
5769 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5770 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005771 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005772 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5773 }
5774 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005775 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005776 constructResumedTraceName(resumed.packageName), 0);
5777 }
5778 mTracedResumedActivity = resumed;
5779 }
5780
5781 private String constructResumedTraceName(String packageName) {
5782 return "focused app: " + packageName;
5783 }
5784
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005785 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005786 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005787 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005788 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005789 // mainStack is null during startup.
5790 if (mainStack != null) {
5791 if (changes != 0 && starting == null) {
5792 // If the configuration changed, and the caller is not already
5793 // in the process of starting an activity, then find the top
5794 // activity to check if its configuration needs to change.
5795 starting = mainStack.topRunningActivityLocked();
5796 }
5797
5798 if (starting != null) {
5799 kept = starting.ensureActivityConfiguration(changes,
5800 false /* preserveWindow */);
5801 // And we need to make sure at this point that all other activities
5802 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005803 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005804 !PRESERVE_WINDOWS);
5805 }
5806 }
5807
5808 return kept;
5809 }
5810
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005811 void scheduleAppGcsLocked() {
5812 mH.post(() -> mAmInternal.scheduleAppGcs());
5813 }
5814
Wale Ogunwale53783742018-09-16 10:21:51 -07005815 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5816 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5817 }
5818
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005819 /**
5820 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5821 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5822 * on demand.
5823 */
5824 IPackageManager getPackageManager() {
5825 return AppGlobals.getPackageManager();
5826 }
5827
5828 PackageManagerInternal getPackageManagerInternalLocked() {
5829 if (mPmInternal == null) {
5830 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5831 }
5832 return mPmInternal;
5833 }
5834
Hai Zhangf4da9be2019-05-01 13:46:06 +08005835 PermissionPolicyInternal getPermissionPolicyInternal() {
5836 if (mPermissionPolicyInternal == null) {
5837 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5838 }
5839 return mPermissionPolicyInternal;
5840 }
5841
Wale Ogunwale008163e2018-07-23 23:11:08 -07005842 AppWarnings getAppWarningsLocked() {
5843 return mAppWarnings;
5844 }
5845
Wale Ogunwale214f3482018-10-04 11:00:47 -07005846 Intent getHomeIntent() {
5847 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5848 intent.setComponent(mTopComponent);
5849 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5850 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5851 intent.addCategory(Intent.CATEGORY_HOME);
5852 }
5853 return intent;
5854 }
5855
Chilun2ef71f72018-11-16 17:57:15 +08005856 /**
5857 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5858 * activities.
5859 *
5860 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5861 * component defined in config_secondaryHomeComponent.
5862 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5863 */
5864 Intent getSecondaryHomeIntent(String preferredPackage) {
5865 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005866 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5867 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5868 if (preferredPackage == null || useSystemProvidedLauncher) {
5869 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005870 final String secondaryHomeComponent = mContext.getResources().getString(
5871 com.android.internal.R.string.config_secondaryHomeComponent);
5872 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5873 } else {
5874 intent.setPackage(preferredPackage);
5875 }
5876 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5877 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5878 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5879 }
5880 return intent;
5881 }
5882
Wale Ogunwale214f3482018-10-04 11:00:47 -07005883 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5884 if (info == null) return null;
5885 ApplicationInfo newInfo = new ApplicationInfo(info);
5886 newInfo.initForUser(userId);
5887 return newInfo;
5888 }
5889
Wale Ogunwale9c103022018-10-18 07:44:54 -07005890 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005891 if (uid == SYSTEM_UID) {
5892 // The system gets to run in any process. If there are multiple processes with the same
5893 // uid, just pick the first (this should never happen).
5894 final SparseArray<WindowProcessController> procs =
5895 mProcessNames.getMap().get(processName);
5896 if (procs == null) return null;
5897 final int procCount = procs.size();
5898 for (int i = 0; i < procCount; i++) {
5899 final int procUid = procs.keyAt(i);
5900 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5901 // Don't use an app process or different user process for system component.
5902 continue;
5903 }
5904 return procs.valueAt(i);
5905 }
5906 }
5907
5908 return mProcessNames.get(processName, uid);
5909 }
5910
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005911 WindowProcessController getProcessController(IApplicationThread thread) {
5912 if (thread == null) {
5913 return null;
5914 }
5915
5916 final IBinder threadBinder = thread.asBinder();
5917 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5918 for (int i = pmap.size()-1; i >= 0; i--) {
5919 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5920 for (int j = procs.size() - 1; j >= 0; j--) {
5921 final WindowProcessController proc = procs.valueAt(j);
5922 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5923 return proc;
5924 }
5925 }
5926 }
5927
5928 return null;
5929 }
5930
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005931 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005932 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005933 if (proc == null) return null;
5934 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5935 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005936 }
5937 return null;
5938 }
5939
Riddle Hsua0536432019-02-16 00:38:59 +08005940 int getUidState(int uid) {
5941 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005942 }
5943
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005944 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005945 // A uid is considered to be foreground if it has a visible non-toast window.
5946 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005947 }
5948
Ricky Wai96f5c352019-04-10 18:40:17 +01005949 boolean isDeviceOwner(int uid) {
5950 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005951 }
5952
Ricky Wai96f5c352019-04-10 18:40:17 +01005953 void setDeviceOwnerUid(int uid) {
5954 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005955 }
5956
Wale Ogunwale9de19442018-10-18 19:05:03 -07005957 /**
5958 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5959 * the whitelist
5960 */
5961 String getPendingTempWhitelistTagForUidLocked(int uid) {
5962 return mPendingTempWhitelist.get(uid);
5963 }
5964
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005965 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5966 if (true || Build.IS_USER) {
5967 return;
5968 }
5969
5970 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5971 StrictMode.allowThreadDiskWrites();
5972 try {
5973 File tracesDir = new File("/data/anr");
5974 File tracesFile = null;
5975 try {
5976 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5977
5978 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005979 String timeString =
5980 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5981 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005982 sb.append(": ");
5983 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5984 sb.append(" since ");
5985 sb.append(msg);
5986 FileOutputStream fos = new FileOutputStream(tracesFile);
5987 fos.write(sb.toString().getBytes());
5988 if (app == null) {
5989 fos.write("\n*** No application process!".getBytes());
5990 }
5991 fos.close();
5992 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5993 } catch (IOException e) {
5994 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5995 return;
5996 }
5997
5998 if (app != null && app.getPid() > 0) {
5999 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6000 firstPids.add(app.getPid());
6001 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6002 }
6003
6004 File lastTracesFile = null;
6005 File curTracesFile = null;
6006 for (int i=9; i>=0; i--) {
6007 String name = String.format(Locale.US, "slow%02d.txt", i);
6008 curTracesFile = new File(tracesDir, name);
6009 if (curTracesFile.exists()) {
6010 if (lastTracesFile != null) {
6011 curTracesFile.renameTo(lastTracesFile);
6012 } else {
6013 curTracesFile.delete();
6014 }
6015 }
6016 lastTracesFile = curTracesFile;
6017 }
6018 tracesFile.renameTo(curTracesFile);
6019 } finally {
6020 StrictMode.setThreadPolicy(oldPolicy);
6021 }
6022 }
6023
Michal Karpinskida34cd42019-04-02 19:46:52 +01006024 boolean isAssociatedCompanionApp(int userId, int uid) {
6025 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6026 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006027 return false;
6028 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006029 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006030 }
6031
Issei Suzuki734bc942019-06-05 13:59:52 +02006032 void notifySingleTaskDisplayEmpty(int displayId) {
6033 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6034 }
6035
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006036 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006037 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006038
6039
Wale Ogunwale98875612018-10-12 07:53:02 -07006040 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6041 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006042
Riddle Hsud93a6c42018-11-29 21:50:06 +08006043 H(Looper looper) {
6044 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006045 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006046
6047 @Override
6048 public void handleMessage(Message msg) {
6049 switch (msg.what) {
6050 case REPORT_TIME_TRACKER_MSG: {
6051 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6052 tracker.deliverResult(mContext);
6053 } break;
6054 }
6055 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006056 }
6057
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006058 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006059 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006060
6061 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006062 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006063 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006064
6065 @Override
6066 public void handleMessage(Message msg) {
6067 switch (msg.what) {
6068 case DISMISS_DIALOG_UI_MSG: {
6069 final Dialog d = (Dialog) msg.obj;
6070 d.dismiss();
6071 break;
6072 }
6073 }
6074 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006075 }
6076
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006077 final class LocalService extends ActivityTaskManagerInternal {
6078 @Override
6079 public SleepToken acquireSleepToken(String tag, int displayId) {
6080 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006081 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006082 }
6083
6084 @Override
6085 public ComponentName getHomeActivityForUser(int userId) {
6086 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006087 final ActivityRecord homeActivity =
6088 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006089 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006090 }
6091 }
6092
6093 @Override
6094 public void onLocalVoiceInteractionStarted(IBinder activity,
6095 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6096 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006097 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006098 }
6099 }
6100
6101 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006102 public void notifyAppTransitionStarting(SparseIntArray reasons,
Yan Wangd47f90b2019-10-03 19:17:15 -07006103 long timestampNs) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006104 synchronized (mGlobalLock) {
6105 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
Yan Wangd47f90b2019-10-03 19:17:15 -07006106 reasons, timestampNs);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006107 }
6108 }
6109
6110 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006111 public void notifySingleTaskDisplayDrawn(int displayId) {
6112 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6113 }
6114
6115 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006116 public void notifyAppTransitionFinished() {
6117 synchronized (mGlobalLock) {
6118 mStackSupervisor.notifyAppTransitionDone();
6119 }
6120 }
6121
6122 @Override
6123 public void notifyAppTransitionCancelled() {
6124 synchronized (mGlobalLock) {
6125 mStackSupervisor.notifyAppTransitionDone();
6126 }
6127 }
6128
6129 @Override
6130 public List<IBinder> getTopVisibleActivities() {
6131 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006132 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006133 }
6134 }
6135
6136 @Override
6137 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6138 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006139 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006140 }
6141 }
6142
6143 @Override
6144 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6145 Bundle bOptions) {
6146 Preconditions.checkNotNull(intents, "intents");
6147 final String[] resolvedTypes = new String[intents.length];
6148
6149 // UID of the package on user userId.
6150 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6151 // packageUid may not be initialized.
6152 int packageUid = 0;
6153 final long ident = Binder.clearCallingIdentity();
6154
6155 try {
6156 for (int i = 0; i < intents.length; i++) {
6157 resolvedTypes[i] =
6158 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6159 }
6160
6161 packageUid = AppGlobals.getPackageManager().getPackageUid(
6162 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6163 } catch (RemoteException e) {
6164 // Shouldn't happen.
6165 } finally {
6166 Binder.restoreCallingIdentity(ident);
6167 }
6168
Riddle Hsu591bf612019-02-14 17:55:31 +08006169 return getActivityStartController().startActivitiesInPackage(
6170 packageUid, packageName,
6171 intents, resolvedTypes, null /* resultTo */,
6172 SafeActivityOptions.fromBundle(bOptions), userId,
6173 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6174 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006175 }
6176
6177 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006178 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6179 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6180 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6181 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006182 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006183 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006184 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6185 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6186 userId, validateIncomingUser, originatingPendingIntent,
6187 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006188 }
6189 }
6190
6191 @Override
6192 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6193 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6194 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006195 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006196 PendingIntentRecord originatingPendingIntent,
6197 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006198 synchronized (mGlobalLock) {
6199 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6200 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6201 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006202 validateIncomingUser, originatingPendingIntent,
6203 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006204 }
6205 }
6206
6207 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006208 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6209 Intent intent, Bundle options, int userId) {
6210 return ActivityTaskManagerService.this.startActivityAsUser(
6211 caller, callerPacakge, intent,
6212 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6213 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6214 false /*validateIncomingUser*/);
6215 }
6216
6217 @Override
lumark588a3e82018-07-20 18:53:54 +08006218 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006219 synchronized (mGlobalLock) {
6220
6221 // We might change the visibilities here, so prepare an empty app transition which
6222 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006223 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006224 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006225 if (activityDisplay == null) {
6226 return;
6227 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006228 final DisplayContent dc = activityDisplay.mDisplayContent;
6229 final boolean wasTransitionSet =
6230 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006231 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006232 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006233 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006234 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006235
6236 // If there was a transition set already we don't want to interfere with it as we
6237 // might be starting it too early.
6238 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006239 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006240 }
6241 }
6242 if (callback != null) {
6243 callback.run();
6244 }
6245 }
6246
6247 @Override
6248 public void notifyKeyguardTrustedChanged() {
6249 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006250 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006251 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006252 }
6253 }
6254 }
6255
6256 /**
6257 * Called after virtual display Id is updated by
6258 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6259 * {@param vrVr2dDisplayId}.
6260 */
6261 @Override
6262 public void setVr2dDisplayId(int vr2dDisplayId) {
6263 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6264 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006265 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006266 }
6267 }
6268
6269 @Override
6270 public void setFocusedActivity(IBinder token) {
6271 synchronized (mGlobalLock) {
6272 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6273 if (r == null) {
6274 throw new IllegalArgumentException(
6275 "setFocusedActivity: No activity record matching token=" + token);
6276 }
Louis Chang19443452018-10-09 12:10:21 +08006277 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006278 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006279 }
6280 }
6281 }
6282
6283 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006284 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006285 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006286 }
6287
6288 @Override
6289 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006290 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006291 }
6292
6293 @Override
6294 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006295 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006296 }
6297
6298 @Override
6299 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6300 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6301 }
6302
6303 @Override
6304 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006305 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006306 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006307
6308 @Override
6309 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6310 synchronized (mGlobalLock) {
6311 mActiveVoiceInteractionServiceComponent = component;
6312 }
6313 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006314
6315 @Override
6316 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6317 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6318 return;
6319 }
6320 synchronized (mGlobalLock) {
6321 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6322 if (types == null) {
6323 if (uid < 0) {
6324 return;
6325 }
6326 types = new ArrayMap<>();
6327 mAllowAppSwitchUids.put(userId, types);
6328 }
6329 if (uid < 0) {
6330 types.remove(type);
6331 } else {
6332 types.put(type, uid);
6333 }
6334 }
6335 }
6336
6337 @Override
6338 public void onUserStopped(int userId) {
6339 synchronized (mGlobalLock) {
6340 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6341 mAllowAppSwitchUids.remove(userId);
6342 }
6343 }
6344
6345 @Override
6346 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6347 synchronized (mGlobalLock) {
6348 return ActivityTaskManagerService.this.isGetTasksAllowed(
6349 caller, callingPid, callingUid);
6350 }
6351 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006352
Riddle Hsua0536432019-02-16 00:38:59 +08006353 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006354 @Override
6355 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006356 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006357 mProcessNames.put(proc.mName, proc.mUid, proc);
6358 }
6359 }
6360
Riddle Hsua0536432019-02-16 00:38:59 +08006361 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006362 @Override
6363 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006364 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006365 mProcessNames.remove(name, uid);
6366 }
6367 }
6368
Riddle Hsua0536432019-02-16 00:38:59 +08006369 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006370 @Override
6371 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006372 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006373 if (proc == mHomeProcess) {
6374 mHomeProcess = null;
6375 }
6376 if (proc == mPreviousProcess) {
6377 mPreviousProcess = null;
6378 }
6379 }
6380 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006381
Riddle Hsua0536432019-02-16 00:38:59 +08006382 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006383 @Override
6384 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006385 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006386 return mTopProcessState;
6387 }
6388 }
6389
Riddle Hsua0536432019-02-16 00:38:59 +08006390 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006391 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006392 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006393 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006394 return proc == mHeavyWeightProcess;
6395 }
6396 }
6397
Riddle Hsua0536432019-02-16 00:38:59 +08006398 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006399 @Override
6400 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006401 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006402 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6403 }
6404 }
6405
6406 @Override
6407 public void finishHeavyWeightApp() {
6408 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006409 if (mHeavyWeightProcess != null) {
6410 mHeavyWeightProcess.finishActivities();
6411 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006412 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6413 mHeavyWeightProcess);
6414 }
6415 }
6416
Riddle Hsua0536432019-02-16 00:38:59 +08006417 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006418 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006419 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006420 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006421 return isSleepingLocked();
6422 }
6423 }
6424
6425 @Override
6426 public boolean isShuttingDown() {
6427 synchronized (mGlobalLock) {
6428 return mShuttingDown;
6429 }
6430 }
6431
6432 @Override
6433 public boolean shuttingDown(boolean booted, int timeout) {
6434 synchronized (mGlobalLock) {
6435 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006436 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006437 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006438 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006439 return mStackSupervisor.shutdownLocked(timeout);
6440 }
6441 }
6442
6443 @Override
6444 public void enableScreenAfterBoot(boolean booted) {
6445 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006446 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006447 mWindowManager.enableScreenAfterBoot();
6448 updateEventDispatchingLocked(booted);
6449 }
6450 }
6451
6452 @Override
6453 public boolean showStrictModeViolationDialog() {
6454 synchronized (mGlobalLock) {
6455 return mShowDialogs && !mSleeping && !mShuttingDown;
6456 }
6457 }
6458
6459 @Override
6460 public void showSystemReadyErrorDialogsIfNeeded() {
6461 synchronized (mGlobalLock) {
6462 try {
6463 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6464 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6465 + " data partition or your device will be unstable.");
6466 mUiHandler.post(() -> {
6467 if (mShowDialogs) {
6468 AlertDialog d = new BaseErrorDialog(mUiContext);
6469 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6470 d.setCancelable(false);
6471 d.setTitle(mUiContext.getText(R.string.android_system_label));
6472 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6473 d.setButton(DialogInterface.BUTTON_POSITIVE,
6474 mUiContext.getText(R.string.ok),
6475 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6476 d.show();
6477 }
6478 });
6479 }
6480 } catch (RemoteException e) {
6481 }
6482
6483 if (!Build.isBuildConsistent()) {
6484 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6485 mUiHandler.post(() -> {
6486 if (mShowDialogs) {
6487 AlertDialog d = new BaseErrorDialog(mUiContext);
6488 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6489 d.setCancelable(false);
6490 d.setTitle(mUiContext.getText(R.string.android_system_label));
6491 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6492 d.setButton(DialogInterface.BUTTON_POSITIVE,
6493 mUiContext.getText(R.string.ok),
6494 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6495 d.show();
6496 }
6497 });
6498 }
6499 }
6500 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006501
6502 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006503 public void onProcessMapped(int pid, WindowProcessController proc) {
6504 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006505 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006506 }
6507 }
6508
6509 @Override
6510 public void onProcessUnMapped(int pid) {
6511 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006512 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006513 }
6514 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006515
6516 @Override
6517 public void onPackageDataCleared(String name) {
6518 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006519 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006520 mAppWarnings.onPackageDataCleared(name);
6521 }
6522 }
6523
6524 @Override
6525 public void onPackageUninstalled(String name) {
6526 synchronized (mGlobalLock) {
6527 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006528 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006529 }
6530 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006531
6532 @Override
6533 public void onPackageAdded(String name, boolean replacing) {
6534 synchronized (mGlobalLock) {
6535 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6536 }
6537 }
6538
6539 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006540 public void onPackageReplaced(ApplicationInfo aInfo) {
6541 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006542 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006543 }
6544 }
6545
6546 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006547 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6548 synchronized (mGlobalLock) {
6549 return compatibilityInfoForPackageLocked(ai);
6550 }
6551 }
6552
Yunfan Chen75157d72018-07-27 14:47:21 +09006553 /**
6554 * Set the corresponding display information for the process global configuration. To be
6555 * called when we need to show IME on a different display.
6556 *
6557 * @param pid The process id associated with the IME window.
6558 * @param displayId The ID of the display showing the IME.
6559 */
6560 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006561 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006562 // Don't update process-level configuration for Multi-Client IME process since other
6563 // IMEs on other displays will also receive this configuration change due to IME
6564 // services use the same application config/context.
6565 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006566
Yunfan Chen75157d72018-07-27 14:47:21 +09006567 if (pid == MY_PID || pid < 0) {
6568 if (DEBUG_CONFIGURATION) {
6569 Slog.w(TAG,
6570 "Trying to update display configuration for system/invalid process.");
6571 }
6572 return;
6573 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006574 synchronized (mGlobalLock) {
6575 final ActivityDisplay activityDisplay =
6576 mRootActivityContainer.getActivityDisplay(displayId);
6577 if (activityDisplay == null) {
6578 // Call might come when display is not yet added or has been removed.
6579 if (DEBUG_CONFIGURATION) {
6580 Slog.w(TAG, "Trying to update display configuration for non-existing "
6581 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006582 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006583 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006584 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006585 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006586 if (process == null) {
6587 if (DEBUG_CONFIGURATION) {
6588 Slog.w(TAG, "Trying to update display configuration for invalid "
6589 + "process, pid=" + pid);
6590 }
6591 return;
6592 }
lumarkddc77fb2019-06-27 22:22:23 +08006593 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006594 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6595 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006596 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006597
6598 @Override
6599 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006600 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006601 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006602 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6603 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006604 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006605 }
6606 }
6607 }
6608
6609 @Override
6610 public void clearPendingResultForActivity(IBinder activityToken,
6611 WeakReference<PendingIntentRecord> pir) {
6612 synchronized (mGlobalLock) {
6613 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6614 if (r != null && r.pendingResults != null) {
6615 r.pendingResults.remove(pir);
6616 }
6617 }
6618 }
6619
6620 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006621 public ActivityTokens getTopActivityForTask(int taskId) {
6622 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08006623 final Task task = mRootActivityContainer.anyTaskForId(taskId);
6624 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006625 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6626 + " Requested task not found");
6627 return null;
6628 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006629 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006630 if (activity == null) {
6631 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6632 + " Requested activity not found");
6633 return null;
6634 }
6635 if (!activity.attachedToProcess()) {
6636 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6637 + activity);
6638 return null;
6639 }
6640 return new ActivityTokens(activity.appToken, activity.assistToken,
6641 activity.app.getThread());
6642 }
6643 }
6644
6645 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006646 public IIntentSender getIntentSender(int type, String packageName,
6647 int callingUid, int userId, IBinder token, String resultWho,
6648 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6649 Bundle bOptions) {
6650 synchronized (mGlobalLock) {
6651 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6652 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6653 }
6654 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006655
6656 @Override
6657 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6658 synchronized (mGlobalLock) {
6659 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6660 if (r == null) {
6661 return null;
6662 }
6663 if (r.mServiceConnectionsHolder == null) {
6664 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6665 ActivityTaskManagerService.this, r);
6666 }
6667
6668 return r.mServiceConnectionsHolder;
6669 }
6670 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006671
6672 @Override
6673 public Intent getHomeIntent() {
6674 synchronized (mGlobalLock) {
6675 return ActivityTaskManagerService.this.getHomeIntent();
6676 }
6677 }
6678
6679 @Override
6680 public boolean startHomeActivity(int userId, String reason) {
6681 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006682 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006683 }
6684 }
6685
6686 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006687 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006688 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006689 synchronized (mGlobalLock) {
6690 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006691 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006692 }
Chilun8b1f1be2019-03-13 17:14:36 +08006693 }
6694
6695 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006696 public boolean startHomeOnAllDisplays(int userId, String reason) {
6697 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006698 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006699 }
6700 }
6701
Riddle Hsua0536432019-02-16 00:38:59 +08006702 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006703 @Override
6704 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006705 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006706 if (mFactoryTest == FACTORY_TEST_OFF) {
6707 return false;
6708 }
6709 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6710 && wpc.mName.equals(mTopComponent.getPackageName())) {
6711 return true;
6712 }
6713 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6714 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6715 }
6716 }
6717
6718 @Override
6719 public void updateTopComponentForFactoryTest() {
6720 synchronized (mGlobalLock) {
6721 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6722 return;
6723 }
6724 final ResolveInfo ri = mContext.getPackageManager()
6725 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6726 final CharSequence errorMsg;
6727 if (ri != null) {
6728 final ActivityInfo ai = ri.activityInfo;
6729 final ApplicationInfo app = ai.applicationInfo;
6730 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6731 mTopAction = Intent.ACTION_FACTORY_TEST;
6732 mTopData = null;
6733 mTopComponent = new ComponentName(app.packageName, ai.name);
6734 errorMsg = null;
6735 } else {
6736 errorMsg = mContext.getResources().getText(
6737 com.android.internal.R.string.factorytest_not_system);
6738 }
6739 } else {
6740 errorMsg = mContext.getResources().getText(
6741 com.android.internal.R.string.factorytest_no_action);
6742 }
6743 if (errorMsg == null) {
6744 return;
6745 }
6746
6747 mTopAction = null;
6748 mTopData = null;
6749 mTopComponent = null;
6750 mUiHandler.post(() -> {
6751 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6752 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006753 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006754 });
6755 }
6756 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006757
Riddle Hsua0536432019-02-16 00:38:59 +08006758 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006759 @Override
6760 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6761 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006762 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006763 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006764 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006765
6766 wpc.clearRecentTasks();
6767 wpc.clearActivities();
6768
6769 if (wpc.isInstrumenting()) {
6770 finishInstrumentationCallback.run();
6771 }
6772
Jorim Jaggid0752812018-10-16 16:07:20 +02006773 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006774 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006775 try {
6776 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6777 // If there was nothing to resume, and we are not already restarting
6778 // this process, but there is a visible activity that is hosted by the
6779 // process...then make sure all visible activities are running, taking
6780 // care of restarting this process.
6781 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6782 !PRESERVE_WINDOWS);
6783 }
6784 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006785 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006786 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006787 }
6788 }
6789 }
6790
6791 @Override
6792 public void closeSystemDialogs(String reason) {
6793 enforceNotIsolatedCaller("closeSystemDialogs");
6794
6795 final int pid = Binder.getCallingPid();
6796 final int uid = Binder.getCallingUid();
6797 final long origId = Binder.clearCallingIdentity();
6798 try {
6799 synchronized (mGlobalLock) {
6800 // Only allow this from foreground processes, so that background
6801 // applications can't abuse it to prevent system UI from being shown.
6802 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006803 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006804 if (!proc.isPerceptible()) {
6805 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6806 + " from background process " + proc);
6807 return;
6808 }
6809 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006810 mWindowManager.closeSystemDialogs(reason);
6811
Wale Ogunwaled32da472018-11-16 07:19:28 -08006812 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006813 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006814 // Call into AM outside the synchronized block.
6815 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006816 } finally {
6817 Binder.restoreCallingIdentity(origId);
6818 }
6819 }
6820
6821 @Override
6822 public void cleanupDisabledPackageComponents(
6823 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6824 synchronized (mGlobalLock) {
6825 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006826 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006827 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006828 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006829 mStackSupervisor.scheduleIdleLocked();
6830 }
6831
6832 // Clean-up disabled tasks
6833 getRecentTasks().cleanupDisabledPackageTasksLocked(
6834 packageName, disabledClasses, userId);
6835 }
6836 }
6837
6838 @Override
6839 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6840 int userId) {
6841 synchronized (mGlobalLock) {
6842
6843 boolean didSomething =
6844 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006845 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006846 null, doit, evenPersistent, userId);
6847 return didSomething;
6848 }
6849 }
6850
6851 @Override
6852 public void resumeTopActivities(boolean scheduleIdle) {
6853 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006854 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006855 if (scheduleIdle) {
6856 mStackSupervisor.scheduleIdleLocked();
6857 }
6858 }
6859 }
6860
Riddle Hsua0536432019-02-16 00:38:59 +08006861 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006862 @Override
6863 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006864 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006865 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6866 }
6867 }
6868
Riddle Hsua0536432019-02-16 00:38:59 +08006869 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006870 @Override
6871 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006872 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006873 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6874 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6875 }
6876 try {
6877 return mRootActivityContainer.attachApplication(wpc);
6878 } finally {
6879 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6880 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006881 }
6882 }
6883
6884 @Override
6885 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6886 try {
6887 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6888 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6889 }
6890 } catch (RemoteException ex) {
6891 throw new SecurityException("Fail to check is caller a privileged app", ex);
6892 }
6893
6894 synchronized (mGlobalLock) {
6895 final long ident = Binder.clearCallingIdentity();
6896 try {
6897 if (mAmInternal.shouldConfirmCredentials(userId)) {
6898 if (mKeyguardController.isKeyguardLocked()) {
6899 // Showing launcher to avoid user entering credential twice.
6900 startHomeActivity(currentUserId, "notifyLockedProfile");
6901 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006902 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006903 }
6904 } finally {
6905 Binder.restoreCallingIdentity(ident);
6906 }
6907 }
6908 }
6909
6910 @Override
6911 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6912 mAmInternal.enforceCallingPermission(
6913 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6914
6915 synchronized (mGlobalLock) {
6916 final long ident = Binder.clearCallingIdentity();
6917 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006918 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6919 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006920 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006921 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6922 UserHandle.CURRENT);
6923 } finally {
6924 Binder.restoreCallingIdentity(ident);
6925 }
6926 }
6927 }
6928
6929 @Override
6930 public void writeActivitiesToProto(ProtoOutputStream proto) {
6931 synchronized (mGlobalLock) {
6932 // The output proto of "activity --proto activities"
6933 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006934 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006935 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6936 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006937 }
6938 }
6939
6940 @Override
6941 public void saveANRState(String reason) {
6942 synchronized (mGlobalLock) {
6943 final StringWriter sw = new StringWriter();
6944 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6945 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6946 if (reason != null) {
6947 pw.println(" Reason: " + reason);
6948 }
6949 pw.println();
6950 getActivityStartController().dump(pw, " ", null);
6951 pw.println();
6952 pw.println("-------------------------------------------------------------------------------");
6953 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6954 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6955 "" /* header */);
6956 pw.println();
6957 pw.close();
6958
6959 mLastANRState = sw.toString();
6960 }
6961 }
6962
6963 @Override
6964 public void clearSavedANRState() {
6965 synchronized (mGlobalLock) {
6966 mLastANRState = null;
6967 }
6968 }
6969
6970 @Override
6971 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6972 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6973 synchronized (mGlobalLock) {
6974 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6975 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6976 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6977 dumpLastANRLocked(pw);
6978 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6979 dumpLastANRTracesLocked(pw);
6980 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6981 dumpActivityStarterLocked(pw, dumpPackage);
6982 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6983 dumpActivityContainersLocked(pw);
6984 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6985 if (getRecentTasks() != null) {
6986 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6987 }
6988 }
6989 }
6990 }
6991
6992 @Override
6993 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6994 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6995 int wakefulness) {
6996 synchronized (mGlobalLock) {
6997 if (mHomeProcess != null && (dumpPackage == null
6998 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6999 if (needSep) {
7000 pw.println();
7001 needSep = false;
7002 }
7003 pw.println(" mHomeProcess: " + mHomeProcess);
7004 }
7005 if (mPreviousProcess != null && (dumpPackage == null
7006 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7007 if (needSep) {
7008 pw.println();
7009 needSep = false;
7010 }
7011 pw.println(" mPreviousProcess: " + mPreviousProcess);
7012 }
7013 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7014 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7015 StringBuilder sb = new StringBuilder(128);
7016 sb.append(" mPreviousProcessVisibleTime: ");
7017 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7018 pw.println(sb);
7019 }
7020 if (mHeavyWeightProcess != null && (dumpPackage == null
7021 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7022 if (needSep) {
7023 pw.println();
7024 needSep = false;
7025 }
7026 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7027 }
7028 if (dumpPackage == null) {
7029 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007030 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007031 }
7032 if (dumpAll) {
7033 if (dumpPackage == null) {
7034 pw.println(" mConfigWillChange: "
7035 + getTopDisplayFocusedStack().mConfigWillChange);
7036 }
7037 if (mCompatModePackages.getPackages().size() > 0) {
7038 boolean printed = false;
7039 for (Map.Entry<String, Integer> entry
7040 : mCompatModePackages.getPackages().entrySet()) {
7041 String pkg = entry.getKey();
7042 int mode = entry.getValue();
7043 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7044 continue;
7045 }
7046 if (!printed) {
7047 pw.println(" mScreenCompatPackages:");
7048 printed = true;
7049 }
7050 pw.println(" " + pkg + ": " + mode);
7051 }
7052 }
7053 }
7054
7055 if (dumpPackage == null) {
7056 pw.println(" mWakefulness="
7057 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007058 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007059 if (mRunningVoice != null) {
7060 pw.println(" mRunningVoice=" + mRunningVoice);
7061 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7062 }
7063 pw.println(" mSleeping=" + mSleeping);
7064 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7065 pw.println(" mVrController=" + mVrController);
7066 }
7067 if (mCurAppTimeTracker != null) {
7068 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7069 }
7070 if (mAllowAppSwitchUids.size() > 0) {
7071 boolean printed = false;
7072 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7073 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7074 for (int j = 0; j < types.size(); j++) {
7075 if (dumpPackage == null ||
7076 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7077 if (needSep) {
7078 pw.println();
7079 needSep = false;
7080 }
7081 if (!printed) {
7082 pw.println(" mAllowAppSwitchUids:");
7083 printed = true;
7084 }
7085 pw.print(" User ");
7086 pw.print(mAllowAppSwitchUids.keyAt(i));
7087 pw.print(": Type ");
7088 pw.print(types.keyAt(j));
7089 pw.print(" = ");
7090 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7091 pw.println();
7092 }
7093 }
7094 }
7095 }
7096 if (dumpPackage == null) {
7097 if (mController != null) {
7098 pw.println(" mController=" + mController
7099 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7100 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007101 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7102 pw.println(" mLaunchingActivityWakeLock="
7103 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007104 }
7105
7106 return needSep;
7107 }
7108 }
7109
7110 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007111 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7112 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007113 synchronized (mGlobalLock) {
7114 if (dumpPackage == null) {
7115 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7116 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007117 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7118 if (mRunningVoice != null) {
7119 final long vrToken = proto.start(
7120 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7121 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7122 mRunningVoice.toString());
7123 mVoiceWakeLock.writeToProto(
7124 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7125 proto.end(vrToken);
7126 }
7127 mVrController.writeToProto(proto,
7128 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007129 if (mController != null) {
7130 final long token = proto.start(CONTROLLER);
7131 proto.write(CONTROLLER, mController.toString());
7132 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7133 proto.end(token);
7134 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007135 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7136 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7137 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007138 }
7139
7140 if (mHomeProcess != null && (dumpPackage == null
7141 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007142 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007143 }
7144
7145 if (mPreviousProcess != null && (dumpPackage == null
7146 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007147 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007148 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7149 }
7150
7151 if (mHeavyWeightProcess != null && (dumpPackage == null
7152 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007153 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007154 }
7155
7156 for (Map.Entry<String, Integer> entry
7157 : mCompatModePackages.getPackages().entrySet()) {
7158 String pkg = entry.getKey();
7159 int mode = entry.getValue();
7160 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7161 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7162 proto.write(PACKAGE, pkg);
7163 proto.write(MODE, mode);
7164 proto.end(compatToken);
7165 }
7166 }
7167
7168 if (mCurAppTimeTracker != null) {
7169 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7170 }
7171
7172 }
7173 }
7174
7175 @Override
7176 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7177 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7178 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007179 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7180 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007181 }
7182
7183 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007184 public void dumpForOom(PrintWriter pw) {
7185 synchronized (mGlobalLock) {
7186 pw.println(" mHomeProcess: " + mHomeProcess);
7187 pw.println(" mPreviousProcess: " + mPreviousProcess);
7188 if (mHeavyWeightProcess != null) {
7189 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7190 }
7191 }
7192 }
7193
7194 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007195 public boolean canGcNow() {
7196 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007197 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007198 }
7199 }
7200
Riddle Hsua0536432019-02-16 00:38:59 +08007201 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007202 @Override
7203 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007204 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007205 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007206 return top != null ? top.app : null;
7207 }
7208 }
7209
Riddle Hsua0536432019-02-16 00:38:59 +08007210 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007211 @Override
7212 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007213 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007214 if (mRootActivityContainer != null) {
7215 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007216 }
7217 }
7218 }
7219
7220 @Override
7221 public void scheduleDestroyAllActivities(String reason) {
7222 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007223 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007224 }
7225 }
7226
7227 @Override
7228 public void removeUser(int userId) {
7229 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007230 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007231 }
7232 }
7233
7234 @Override
7235 public boolean switchUser(int userId, UserState userState) {
7236 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007237 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007238 }
7239 }
7240
7241 @Override
7242 public void onHandleAppCrash(WindowProcessController wpc) {
7243 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007244 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007245 }
7246 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007247
7248 @Override
7249 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7250 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007251 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007252 }
7253 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007254
Riddle Hsua0536432019-02-16 00:38:59 +08007255 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007256 @Override
7257 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007258 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007259 }
7260
Riddle Hsua0536432019-02-16 00:38:59 +08007261 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007262 @Override
7263 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007264 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007265 }
7266
Riddle Hsua0536432019-02-16 00:38:59 +08007267 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007268 @Override
7269 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007270 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007271 }
7272
Riddle Hsua0536432019-02-16 00:38:59 +08007273 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007274 @Override
7275 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007276 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007277 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007278
7279 @Override
7280 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007281 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007282 mPendingTempWhitelist.put(uid, tag);
7283 }
7284 }
7285
7286 @Override
7287 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007288 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007289 mPendingTempWhitelist.remove(uid);
7290 }
7291 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007292
7293 @Override
7294 public boolean handleAppCrashInActivityController(String processName, int pid,
7295 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7296 Runnable killCrashingAppCallback) {
7297 synchronized (mGlobalLock) {
7298 if (mController == null) {
7299 return false;
7300 }
7301
7302 try {
7303 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7304 stackTrace)) {
7305 killCrashingAppCallback.run();
7306 return true;
7307 }
7308 } catch (RemoteException e) {
7309 mController = null;
7310 Watchdog.getInstance().setActivityController(null);
7311 }
7312 return false;
7313 }
7314 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007315
7316 @Override
7317 public void removeRecentTasksByPackageName(String packageName, int userId) {
7318 synchronized (mGlobalLock) {
7319 mRecentTasks.removeTasksByPackageName(packageName, userId);
7320 }
7321 }
7322
7323 @Override
7324 public void cleanupRecentTasksForUser(int userId) {
7325 synchronized (mGlobalLock) {
7326 mRecentTasks.cleanupLocked(userId);
7327 }
7328 }
7329
7330 @Override
7331 public void loadRecentTasksForUser(int userId) {
7332 synchronized (mGlobalLock) {
7333 mRecentTasks.loadUserRecentsLocked(userId);
7334 }
7335 }
7336
7337 @Override
7338 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7339 synchronized (mGlobalLock) {
7340 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7341 }
7342 }
7343
7344 @Override
7345 public void flushRecentTasks() {
7346 mRecentTasks.flush();
7347 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007348
7349 @Override
7350 public WindowProcessController getHomeProcess() {
7351 synchronized (mGlobalLock) {
7352 return mHomeProcess;
7353 }
7354 }
7355
7356 @Override
7357 public WindowProcessController getPreviousProcess() {
7358 synchronized (mGlobalLock) {
7359 return mPreviousProcess;
7360 }
7361 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007362
7363 @Override
7364 public void clearLockedTasks(String reason) {
7365 synchronized (mGlobalLock) {
7366 getLockTaskController().clearLockedTasks(reason);
7367 }
7368 }
7369
7370 @Override
7371 public void updateUserConfiguration() {
7372 synchronized (mGlobalLock) {
7373 final Configuration configuration = new Configuration(getGlobalConfiguration());
7374 final int currentUserId = mAmInternal.getCurrentUserId();
7375 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7376 configuration, currentUserId, Settings.System.canWrite(mContext));
7377 updateConfigurationLocked(configuration, null /* starting */,
7378 false /* initLocale */, false /* persistent */, currentUserId,
7379 false /* deferResume */);
7380 }
7381 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007382
7383 @Override
7384 public boolean canShowErrorDialogs() {
7385 synchronized (mGlobalLock) {
7386 return mShowDialogs && !mSleeping && !mShuttingDown
7387 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7388 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7389 mAmInternal.getCurrentUserId())
7390 && !(UserManager.isDeviceInDemoMode(mContext)
7391 && mAmInternal.getCurrentUser().isDemo());
7392 }
7393 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007394
7395 @Override
7396 public void setProfileApp(String profileApp) {
7397 synchronized (mGlobalLock) {
7398 mProfileApp = profileApp;
7399 }
7400 }
7401
7402 @Override
7403 public void setProfileProc(WindowProcessController wpc) {
7404 synchronized (mGlobalLock) {
7405 mProfileProc = wpc;
7406 }
7407 }
7408
7409 @Override
7410 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7411 synchronized (mGlobalLock) {
7412 mProfilerInfo = profilerInfo;
7413 }
7414 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007415
7416 @Override
7417 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7418 synchronized (mGlobalLock) {
7419 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7420 }
7421 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007422
7423 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007424 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7425 boolean reducedResolution) {
7426 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7427 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007428 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007429
7430 @Override
7431 public boolean isUidForeground(int uid) {
7432 synchronized (mGlobalLock) {
7433 return ActivityTaskManagerService.this.isUidForeground(uid);
7434 }
7435 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007436
7437 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007438 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007439 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007440 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007441 }
7442 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007443
7444 @Override
7445 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007446 // Translate package names into UIDs
7447 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007448 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007449 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7450 if (uid >= 0) {
7451 result.add(uid);
7452 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007453 }
7454 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007455 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007456 }
7457 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007458 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007459}