blob: 45b4818add11be22061a3d226351a4c37a9ea487 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070031import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080055import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070067
Yunfan Chen79b96062018-10-17 12:45:23 -070068import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
69import static com.android.server.am.ActivityManagerService.MY_PID;
70import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
71import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Jeff Changd136e772019-11-05 20:33:52 +080086import static com.android.server.am.EventLogTags.writeBootProgressEnableScreen;
87import static com.android.server.am.EventLogTags.writeConfigurationChanged;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070088import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
89import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
Louis Changcdec0802019-11-11 11:45:07 +0800122import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800127import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700128import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.annotation.Nullable;
130import android.annotation.UserIdInt;
131import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700132import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700133import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.ActivityOptions;
135import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700136import android.app.ActivityThread;
137import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700138import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100139import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700140import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700141import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700142import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.IApplicationThread;
144import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400146import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700148import android.app.Notification;
149import android.app.NotificationManager;
150import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700151import android.app.PictureInPictureParams;
152import android.app.ProfilerInfo;
153import android.app.RemoteAction;
154import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700155import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.app.admin.DevicePolicyCache;
157import android.app.assist.AssistContent;
158import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700159import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700160import android.content.ActivityNotFoundException;
161import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700162import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700163import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700164import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700165import android.content.IIntentSender;
166import android.content.Intent;
167import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700168import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900169import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700170import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700172import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.pm.ParceledListSlice;
174import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700175import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700177import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700178import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.graphics.Bitmap;
180import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.metrics.LogMaker;
183import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700184import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700187import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700189import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700190import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700191import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700192import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800193import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700194import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700197import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100198import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700199import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700201import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700202import android.os.SystemClock;
203import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700204import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700205import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700206import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700207import android.os.UserManager;
208import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700209import android.os.storage.IStorageManager;
210import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import android.provider.Settings;
212import android.service.voice.IVoiceInteractionSession;
213import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900214import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700215import android.telecom.TelecomManager;
216import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100217import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700219import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700221import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.SparseArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700223import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700224import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700225import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700226import android.view.IRecentsAnimationRunner;
227import android.view.RemoteAnimationAdapter;
228import android.view.RemoteAnimationDefinition;
Evan Roskyddedfd42019-10-04 13:38:38 -0700229import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700230import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700231
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700233import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700235import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700237import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700240import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
241import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700242import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700243import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700244import com.android.internal.policy.IKeyguardDismissCallback;
245import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700246import com.android.internal.util.ArrayUtils;
247import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700248import com.android.internal.util.Preconditions;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800249import com.android.internal.util.function.pooled.PooledConsumer;
250import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700251import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700252import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700253import com.android.server.LocalServices;
254import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700255import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800256import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700257import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700258import com.android.server.am.ActivityManagerService;
259import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
260import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
261import com.android.server.am.AppTimeTracker;
262import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700263import com.android.server.am.PendingIntentController;
264import com.android.server.am.PendingIntentRecord;
265import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900266import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700267import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700268import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700269import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800270import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700271import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700275import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700277import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700279import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700280import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700281import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800282import java.lang.annotation.ElementType;
283import java.lang.annotation.Retention;
284import java.lang.annotation.RetentionPolicy;
285import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700286import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700288import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700289import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700290import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400291import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700292import java.util.HashSet;
Evan Roskyddedfd42019-10-04 13:38:38 -0700293import java.util.Iterator;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700295import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700296import java.util.Map;
297import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700298
299/**
300 * System service for managing activities and their containers (task, stacks, displays,... ).
301 *
302 * {@hide}
303 */
304public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700305 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700306 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700307 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
308 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
309 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
310 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
311 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700312 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700313
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700314 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700315 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700316 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700317 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100318 // How long we permit background activity starts after an activity in the process
319 // started or finished.
320 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700321
Wale Ogunwale98875612018-10-12 07:53:02 -0700322 /** Used to indicate that an app transition should be animated. */
323 static final boolean ANIMATE = true;
324
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700325 /** Hardware-reported OpenGLES version. */
326 final int GL_ES_VERSION;
327
Wale Ogunwale31913b52018-10-13 08:29:31 -0700328 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
329 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
330 public static final String DUMP_LASTANR_CMD = "lastanr" ;
331 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
332 public static final String DUMP_STARTER_CMD = "starter" ;
333 public static final String DUMP_CONTAINERS_CMD = "containers" ;
334 public static final String DUMP_RECENTS_CMD = "recents" ;
335 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
336
Wale Ogunwale64258362018-10-16 15:13:37 -0700337 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
338 public static final int RELAUNCH_REASON_NONE = 0;
339 /** This activity is being relaunched due to windowing mode change. */
340 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
341 /** This activity is being relaunched due to a free-resize operation. */
342 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
343
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700344 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700345
Wale Ogunwalef6733932018-06-27 05:14:34 -0700346 /**
347 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
348 * change at runtime. Use mContext for non-UI purposes.
349 */
350 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700351 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700352 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700353 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700354 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700355 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700356 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800357 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800358 @VisibleForTesting
359 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700360 PowerManagerInternal mPowerManagerInternal;
361 private UsageStatsManagerInternal mUsageStatsInternal;
362
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700363 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700364 IntentFirewall mIntentFirewall;
365
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700366 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800367 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800368 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700369 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800370 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
371 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
372 *
373 * @see WindowManagerThreadPriorityBooster
374 */
375 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700376 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800377 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700378 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700379 private UserManagerService mUserManager;
380 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700381 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800382 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700383 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700384 /** All processes currently running that might have a window organized by name. */
385 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100386 /** All processes we currently have running mapped by pid and uid */
387 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700388 /** This is the process holding what we currently consider to be the "home" activity. */
389 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700390 /** The currently running heavy-weight process, if any. */
391 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700392 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700393 /**
394 * This is the process holding the activity the user last visited that is in a different process
395 * from the one they are currently in.
396 */
397 WindowProcessController mPreviousProcess;
398 /** The time at which the previous process was last visible. */
399 long mPreviousProcessVisibleTime;
400
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700401 /** List of intents that were used to start the most recent tasks. */
402 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700403 /** State of external calls telling us if the device is awake or asleep. */
404 private boolean mKeyguardShown = false;
405
406 // Wrapper around VoiceInteractionServiceManager
407 private AssistUtils mAssistUtils;
408
409 // VoiceInteraction session ID that changes for each new request except when
410 // being called for multi-window assist in a single session.
411 private int mViSessionId = 1000;
412
413 // How long to wait in getAssistContextExtras for the activity and foreground services
414 // to respond with the result.
415 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
416
417 // How long top wait when going through the modern assist (which doesn't need to block
418 // on getting this result before starting to launch its UI).
419 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
420
421 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
422 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
423
Alison Cichowlas3e340502018-08-07 17:15:01 -0400424 // Permission tokens are used to temporarily granted a trusted app the ability to call
425 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
426 // showing any appropriate error messages to the user.
427 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
428 10 * MINUTE_IN_MILLIS;
429
430 // How long before the service actually expires a token. This is slightly longer than
431 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
432 // expiration exception.
433 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
434 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
435
436 // How long the service will remember expired tokens, for the purpose of providing error
437 // messaging when a client uses an expired token.
438 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
439 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
440
441 // Activity tokens of system activities that are delegating their call to
442 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
443 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
444
445 // Permission tokens that have expired, but we remember for error reporting.
446 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
447
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700448 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
449
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700450 // Keeps track of the active voice interaction service component, notified from
451 // VoiceInteractionManagerService
452 ComponentName mActiveVoiceInteractionServiceComponent;
453
Michal Karpinskida34cd42019-04-02 19:46:52 +0100454 // A map userId and all its companion app uids
455 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000456
Wale Ogunwalee2172292018-10-25 10:11:10 -0700457 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700458 KeyguardController mKeyguardController;
459 private final ClientLifecycleManager mLifecycleManager;
460 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700461 /** The controller for all operations related to locktask. */
462 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700463 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700464
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700465 boolean mSuppressResizeConfigChanges;
466
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700467 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700468 new UpdateConfigurationResult();
469
470 static final class UpdateConfigurationResult {
471 // Configuration changes that were updated.
472 int changes;
473 // If the activity was relaunched to match the new configuration.
474 boolean activityRelaunched;
475
476 void reset() {
477 changes = 0;
478 activityRelaunched = false;
479 }
480 }
481
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700482 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700483 private int mConfigurationSeq;
484 // To cache the list of supported system locales
485 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700486
487 /**
488 * Temp object used when global and/or display override configuration is updated. It is also
489 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
490 * anyone...
491 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492 private Configuration mTempConfig = new Configuration();
493
Wale Ogunwalef6733932018-06-27 05:14:34 -0700494 /** Temporary to avoid allocations. */
495 final StringBuilder mStringBuilder = new StringBuilder(256);
496
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700497 // Amount of time after a call to stopAppSwitches() during which we will
498 // prevent further untrusted switches from happening.
499 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
500
501 /**
502 * The time at which we will allow normal application switches again,
503 * after a call to {@link #stopAppSwitches()}.
504 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700506 /**
507 * This is set to true after the first switch after mAppSwitchesAllowedTime
508 * is set; any switches after that will clear the time.
509 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700510 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511
Ricky Wai906af482019-06-03 17:25:28 +0100512 /**
513 * Last stop app switches time, apps finished before this time cannot start background activity
514 * even if they are in grace period.
515 */
516 private long mLastStopAppSwitchesTime;
517
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700518 IActivityController mController = null;
519 boolean mControllerIsAMonkey = false;
520
Wale Ogunwale214f3482018-10-04 11:00:47 -0700521 final int mFactoryTest;
522
523 /** Used to control how we initialize the service. */
524 ComponentName mTopComponent;
525 String mTopAction = Intent.ACTION_MAIN;
526 String mTopData;
527
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800528 /** Profiling app information. */
529 String mProfileApp = null;
530 WindowProcessController mProfileProc = null;
531 ProfilerInfo mProfilerInfo = null;
532
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700533 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700534 * Dump of the activity state at the time of the last ANR. Cleared after
535 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
536 */
537 String mLastANRState;
538
539 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700540 * Used to retain an update lock when the foreground activity is in
541 * immersive mode.
542 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700543 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700544
545 /**
546 * Packages that are being allowed to perform unrestricted app switches. Mapping is
547 * User -> Type -> uid.
548 */
549 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
550
551 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700552 private int mThumbnailWidth;
553 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700554
555 /**
556 * Flag that indicates if multi-window is enabled.
557 *
558 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
559 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
560 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
561 * At least one of the forms of multi-window must be enabled in order for this flag to be
562 * initialized to 'true'.
563 *
564 * @see #mSupportsSplitScreenMultiWindow
565 * @see #mSupportsFreeformWindowManagement
566 * @see #mSupportsPictureInPicture
567 * @see #mSupportsMultiDisplay
568 */
569 boolean mSupportsMultiWindow;
570 boolean mSupportsSplitScreenMultiWindow;
571 boolean mSupportsFreeformWindowManagement;
572 boolean mSupportsPictureInPicture;
573 boolean mSupportsMultiDisplay;
574 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700575 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700576
577 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
578
579 // VR Vr2d Display Id.
580 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700581
Wale Ogunwalef6733932018-06-27 05:14:34 -0700582 /**
583 * Set while we are wanting to sleep, to prevent any
584 * activities from being started/resumed.
585 *
586 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
587 *
588 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
589 * while in the sleep state until there is a pending transition out of sleep, in which case
590 * mSleeping is set to false, and remains false while awake.
591 *
592 * Whether mSleeping can quickly toggled between true/false without the device actually
593 * display changing states is undefined.
594 */
595 private boolean mSleeping = false;
596
597 /**
598 * The process state used for processes that are running the top activities.
599 * This changes between TOP and TOP_SLEEPING to following mSleeping.
600 */
601 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
602
Riddle Hsua0022cd2019-09-09 21:12:41 +0800603 @Retention(RetentionPolicy.SOURCE)
604 @IntDef({
605 LAYOUT_REASON_CONFIG_CHANGED,
606 LAYOUT_REASON_VISIBILITY_CHANGED,
607 })
608 @interface LayoutReason {}
609 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
610 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
611
612 /** The reasons to perform surface placement. */
613 @LayoutReason
614 private int mLayoutReasons;
615
Wale Ogunwalef6733932018-06-27 05:14:34 -0700616 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
617 // automatically. Important for devices without direct input devices.
618 private boolean mShowDialogs = true;
619
620 /** Set if we are shutting down the system, similar to sleeping. */
621 boolean mShuttingDown = false;
622
623 /**
624 * We want to hold a wake lock while running a voice interaction session, since
625 * this may happen with the screen off and we need to keep the CPU running to
626 * be able to continue to interact with the user.
627 */
628 PowerManager.WakeLock mVoiceWakeLock;
629
630 /**
631 * Set while we are running a voice interaction. This overrides sleeping while it is active.
632 */
633 IVoiceInteractionSession mRunningVoice;
634
635 /**
636 * The last resumed activity. This is identical to the current resumed activity most
637 * of the time but could be different when we're pausing one activity before we resume
638 * another activity.
639 */
640 ActivityRecord mLastResumedActivity;
641
642 /**
643 * The activity that is currently being traced as the active resumed activity.
644 *
645 * @see #updateResumedAppTrace
646 */
647 private @Nullable ActivityRecord mTracedResumedActivity;
648
649 /** If non-null, we are tracking the time the user spends in the currently focused app. */
650 AppTimeTracker mCurAppTimeTracker;
651
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700652 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700653
Wale Ogunwale53783742018-09-16 10:21:51 -0700654 /**
655 * Packages that the user has asked to have run in screen size
656 * compatibility mode instead of filling the screen.
657 */
658 CompatModePackages mCompatModePackages;
659
Wale Ogunwalef6733932018-06-27 05:14:34 -0700660 private FontScaleSettingObserver mFontScaleSettingObserver;
661
Ricky Wai96f5c352019-04-10 18:40:17 +0100662 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000663
Wale Ogunwalef6733932018-06-27 05:14:34 -0700664 private final class FontScaleSettingObserver extends ContentObserver {
665 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
666 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
667
668 public FontScaleSettingObserver() {
669 super(mH);
670 final ContentResolver resolver = mContext.getContentResolver();
671 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
672 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
673 UserHandle.USER_ALL);
674 }
675
676 @Override
677 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
678 if (mFontScaleUri.equals(uri)) {
679 updateFontScaleIfNeeded(userId);
680 } else if (mHideErrorDialogsUri.equals(uri)) {
681 synchronized (mGlobalLock) {
682 updateShouldShowDialogsLocked(getGlobalConfiguration());
683 }
684 }
685 }
686 }
687
Riddle Hsua0536432019-02-16 00:38:59 +0800688 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
689 @Target(ElementType.METHOD)
690 @Retention(RetentionPolicy.SOURCE)
691 @interface HotPath {
692 int NONE = 0;
693 int OOM_ADJUSTMENT = 1;
694 int LRU_UPDATE = 2;
695 int PROCESS_CHANGE = 3;
696 int caller() default NONE;
697 }
698
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800699 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
700 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900701 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800702 mAmInternal.updateOomAdj();
703 }
704 };
705
Charles Chen8d98dd22018-12-26 17:36:54 +0800706 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
707 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700708 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700709 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700710 mSystemThread = ActivityThread.currentActivityThread();
711 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700712 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800713 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700714 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700715 }
716
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700717 public void onSystemReady() {
718 synchronized (mGlobalLock) {
719 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
720 PackageManager.FEATURE_CANT_SAVE_STATE);
721 mAssistUtils = new AssistUtils(mContext);
722 mVrController.onSystemReady();
723 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700724 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700725 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700726 }
727
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700728 public void onInitPowerManagement() {
729 synchronized (mGlobalLock) {
730 mStackSupervisor.initPowerManagement();
731 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
732 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
733 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
734 mVoiceWakeLock.setReferenceCounted(false);
735 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700736 }
737
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700738 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700739 mFontScaleSettingObserver = new FontScaleSettingObserver();
740 }
741
Wale Ogunwale59507092018-10-29 09:00:30 -0700742 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700743 final boolean freeformWindowManagement =
744 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
745 || Settings.Global.getInt(
746 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
747
748 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
749 final boolean supportsPictureInPicture = supportsMultiWindow &&
750 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
751 final boolean supportsSplitScreenMultiWindow =
752 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
753 final boolean supportsMultiDisplay = mContext.getPackageManager()
754 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700755 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
756 final boolean forceResizable = Settings.Global.getInt(
757 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700758 final boolean sizeCompatFreeform = Settings.Global.getInt(
759 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700760
761 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900762 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700763
764 final Configuration configuration = new Configuration();
765 Settings.System.getConfiguration(resolver, configuration);
766 if (forceRtl) {
767 // This will take care of setting the correct layout direction flags
768 configuration.setLayoutDirection(configuration.locale);
769 }
770
771 synchronized (mGlobalLock) {
772 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700773 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700774 final boolean multiWindowFormEnabled = freeformWindowManagement
775 || supportsSplitScreenMultiWindow
776 || supportsPictureInPicture
777 || supportsMultiDisplay;
778 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
779 mSupportsMultiWindow = true;
780 mSupportsFreeformWindowManagement = freeformWindowManagement;
781 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
782 mSupportsPictureInPicture = supportsPictureInPicture;
783 mSupportsMultiDisplay = supportsMultiDisplay;
784 } else {
785 mSupportsMultiWindow = false;
786 mSupportsFreeformWindowManagement = false;
787 mSupportsSplitScreenMultiWindow = false;
788 mSupportsPictureInPicture = false;
789 mSupportsMultiDisplay = false;
790 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700791 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700792 // This happens before any activities are started, so we can change global configuration
793 // in-place.
794 updateConfigurationLocked(configuration, null, true);
795 final Configuration globalConfig = getGlobalConfiguration();
796 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
797
798 // Load resources only after the current configuration has been set.
799 final Resources res = mContext.getResources();
800 mThumbnailWidth = res.getDimensionPixelSize(
801 com.android.internal.R.dimen.thumbnail_width);
802 mThumbnailHeight = res.getDimensionPixelSize(
803 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700804 }
805 }
806
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800807 public WindowManagerGlobalLock getGlobalLock() {
808 return mGlobalLock;
809 }
810
Yunfan Chen585f2932019-01-29 16:04:45 +0900811 /** For test purpose only. */
812 @VisibleForTesting
813 public ActivityTaskManagerInternal getAtmInternal() {
814 return mInternal;
815 }
816
Riddle Hsud93a6c42018-11-29 21:50:06 +0800817 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
818 Looper looper) {
819 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700820 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700821 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700822 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800823 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700824 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700825 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700826
827 mTempConfig.setToDefaults();
828 mTempConfig.setLocales(LocaleList.getDefault());
829 mConfigurationSeq = mTempConfig.seq = 1;
830 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800831 mRootActivityContainer = new RootActivityContainer(this);
832 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700833
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700834 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700835 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700836 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700837 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700838 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700839 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700840 mKeyguardController = mStackSupervisor.getKeyguardController();
841 }
842
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700843 public void onActivityManagerInternalAdded() {
844 synchronized (mGlobalLock) {
845 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
846 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
847 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700848 }
849
Yunfan Chen75157d72018-07-27 14:47:21 +0900850 int increaseConfigurationSeqLocked() {
851 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
852 return mConfigurationSeq;
853 }
854
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700855 protected ActivityStackSupervisor createStackSupervisor() {
856 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
857 supervisor.initialize();
858 return supervisor;
859 }
860
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800861 protected AppWarnings createAppWarnings(
862 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
863 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
864 }
865
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700866 public void setWindowManager(WindowManagerService wm) {
867 synchronized (mGlobalLock) {
868 mWindowManager = wm;
869 mLockTaskController.setWindowManager(wm);
870 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800871 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700872 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700873 }
874
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700875 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
876 synchronized (mGlobalLock) {
877 mUsageStatsInternal = usageStatsManager;
878 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700879 }
880
Wale Ogunwalef6733932018-06-27 05:14:34 -0700881 UserManagerService getUserManager() {
882 if (mUserManager == null) {
883 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
884 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
885 }
886 return mUserManager;
887 }
888
889 AppOpsService getAppOpsService() {
890 if (mAppOpsService == null) {
891 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
892 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
893 }
894 return mAppOpsService;
895 }
896
897 boolean hasUserRestriction(String restriction, int userId) {
898 return getUserManager().hasUserRestriction(restriction, userId);
899 }
900
Michal Karpinski15486842019-04-25 17:33:42 +0100901 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
902 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700903 callingUid, callingPackage, /* featureId */ null);
Michal Karpinski15486842019-04-25 17:33:42 +0100904 if (mode == AppOpsManager.MODE_DEFAULT) {
905 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
906 == PERMISSION_GRANTED;
907 }
908 return mode == AppOpsManager.MODE_ALLOWED;
909 }
910
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700911 @VisibleForTesting
912 protected void setRecentTasks(RecentTasks recentTasks) {
913 mRecentTasks = recentTasks;
914 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700915 }
916
917 RecentTasks getRecentTasks() {
918 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700919 }
920
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700921 ClientLifecycleManager getLifecycleManager() {
922 return mLifecycleManager;
923 }
924
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700925 ActivityStartController getActivityStartController() {
926 return mActivityStartController;
927 }
928
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700929 TaskChangeNotificationController getTaskChangeNotificationController() {
930 return mTaskChangeNotificationController;
931 }
932
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700933 LockTaskController getLockTaskController() {
934 return mLockTaskController;
935 }
936
Yunfan Chen75157d72018-07-27 14:47:21 +0900937 /**
938 * Return the global configuration used by the process corresponding to the input pid. This is
939 * usually the global configuration with some overrides specific to that process.
940 */
941 Configuration getGlobalConfigurationForCallingPid() {
942 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800943 return getGlobalConfigurationForPid(pid);
944 }
945
946 /**
947 * Return the global configuration used by the process corresponding to the given pid.
948 */
949 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900950 if (pid == MY_PID || pid < 0) {
951 return getGlobalConfiguration();
952 }
953 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100954 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900955 return app != null ? app.getConfiguration() : getGlobalConfiguration();
956 }
957 }
958
959 /**
960 * Return the device configuration info used by the process corresponding to the input pid.
961 * The value is consistent with the global configuration for the process.
962 */
963 @Override
964 public ConfigurationInfo getDeviceConfigurationInfo() {
965 ConfigurationInfo config = new ConfigurationInfo();
966 synchronized (mGlobalLock) {
967 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
968 config.reqTouchScreen = globalConfig.touchscreen;
969 config.reqKeyboardType = globalConfig.keyboard;
970 config.reqNavigation = globalConfig.navigation;
971 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
972 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
973 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
974 }
975 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
976 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
977 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
978 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700979 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900980 }
981 return config;
982 }
983
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700984 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700985 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700986 }
987
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700988 public static final class Lifecycle extends SystemService {
989 private final ActivityTaskManagerService mService;
990
991 public Lifecycle(Context context) {
992 super(context);
993 mService = new ActivityTaskManagerService(context);
994 }
995
996 @Override
997 public void onStart() {
998 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700999 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001000 }
1001
Garfield Tan891146c2018-10-09 12:14:00 -07001002 @Override
1003 public void onUnlockUser(int userId) {
1004 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001005 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001006 }
1007 }
1008
1009 @Override
1010 public void onCleanupUser(int userId) {
1011 synchronized (mService.getGlobalLock()) {
1012 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1013 }
1014 }
1015
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001016 public ActivityTaskManagerService getService() {
1017 return mService;
1018 }
1019 }
1020
1021 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022 public final int startActivity(IApplicationThread caller, String callingPackage,
1023 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1024 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1025 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1026 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1027 UserHandle.getCallingUserId());
1028 }
1029
1030 @Override
1031 public final int startActivities(IApplicationThread caller, String callingPackage,
1032 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1033 int userId) {
1034 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001035 enforceNotIsolatedCaller(reason);
1036 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001037 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001038 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1039 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1040 reason, null /* originatingPendingIntent */,
1041 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001042 }
1043
1044 @Override
1045 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1046 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1047 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1048 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1049 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1050 true /*validateIncomingUser*/);
1051 }
1052
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001053 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001054 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1055 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1056 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001057 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001058
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001059 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1061
1062 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001063 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001064 .setCaller(caller)
1065 .setCallingPackage(callingPackage)
1066 .setResolvedType(resolvedType)
1067 .setResultTo(resultTo)
1068 .setResultWho(resultWho)
1069 .setRequestCode(requestCode)
1070 .setStartFlags(startFlags)
1071 .setProfilerInfo(profilerInfo)
1072 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001073 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001074 .execute();
1075
1076 }
1077
1078 @Override
1079 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1080 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001081 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1082 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001083 // Refuse possible leaked file descriptors
1084 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1085 throw new IllegalArgumentException("File descriptors passed in Intent");
1086 }
1087
1088 if (!(target instanceof PendingIntentRecord)) {
1089 throw new IllegalArgumentException("Bad PendingIntent object");
1090 }
1091
1092 PendingIntentRecord pir = (PendingIntentRecord)target;
1093
1094 synchronized (mGlobalLock) {
1095 // If this is coming from the currently resumed activity, it is
1096 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001097 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001098 if (stack.mResumedActivity != null &&
1099 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001100 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001101 }
1102 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001103 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001104 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001105 }
1106
1107 @Override
1108 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1109 Bundle bOptions) {
1110 // Refuse possible leaked file descriptors
1111 if (intent != null && intent.hasFileDescriptors()) {
1112 throw new IllegalArgumentException("File descriptors passed in Intent");
1113 }
1114 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1115
1116 synchronized (mGlobalLock) {
1117 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1118 if (r == null) {
1119 SafeActivityOptions.abort(options);
1120 return false;
1121 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001122 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001123 // The caller is not running... d'oh!
1124 SafeActivityOptions.abort(options);
1125 return false;
1126 }
1127 intent = new Intent(intent);
1128 // The caller is not allowed to change the data.
1129 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1130 // And we are resetting to find the next component...
1131 intent.setComponent(null);
1132
1133 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1134
1135 ActivityInfo aInfo = null;
1136 try {
1137 List<ResolveInfo> resolves =
1138 AppGlobals.getPackageManager().queryIntentActivities(
1139 intent, r.resolvedType,
1140 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1141 UserHandle.getCallingUserId()).getList();
1142
1143 // Look for the original activity in the list...
1144 final int N = resolves != null ? resolves.size() : 0;
1145 for (int i=0; i<N; i++) {
1146 ResolveInfo rInfo = resolves.get(i);
1147 if (rInfo.activityInfo.packageName.equals(r.packageName)
1148 && rInfo.activityInfo.name.equals(r.info.name)) {
1149 // We found the current one... the next matching is
1150 // after it.
1151 i++;
1152 if (i<N) {
1153 aInfo = resolves.get(i).activityInfo;
1154 }
1155 if (debug) {
1156 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1157 + "/" + r.info.name);
1158 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1159 ? "null" : aInfo.packageName + "/" + aInfo.name));
1160 }
1161 break;
1162 }
1163 }
1164 } catch (RemoteException e) {
1165 }
1166
1167 if (aInfo == null) {
1168 // Nobody who is next!
1169 SafeActivityOptions.abort(options);
1170 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1171 return false;
1172 }
1173
1174 intent.setComponent(new ComponentName(
1175 aInfo.applicationInfo.packageName, aInfo.name));
1176 intent.setFlags(intent.getFlags()&~(
1177 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1178 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1179 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1180 FLAG_ACTIVITY_NEW_TASK));
1181
1182 // Okay now we need to start the new activity, replacing the currently running activity.
1183 // This is a little tricky because we want to start the new one as if the current one is
1184 // finished, but not finish the current one first so that there is no flicker.
1185 // And thus...
1186 final boolean wasFinishing = r.finishing;
1187 r.finishing = true;
1188
1189 // Propagate reply information over to the new activity.
1190 final ActivityRecord resultTo = r.resultTo;
1191 final String resultWho = r.resultWho;
1192 final int requestCode = r.requestCode;
1193 r.resultTo = null;
1194 if (resultTo != null) {
1195 resultTo.removeResultsLocked(r, resultWho, requestCode);
1196 }
1197
1198 final long origId = Binder.clearCallingIdentity();
1199 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001200 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001201 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001202 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001203 .setResolvedType(r.resolvedType)
1204 .setActivityInfo(aInfo)
1205 .setResultTo(resultTo != null ? resultTo.appToken : null)
1206 .setResultWho(resultWho)
1207 .setRequestCode(requestCode)
1208 .setCallingPid(-1)
1209 .setCallingUid(r.launchedFromUid)
1210 .setCallingPackage(r.launchedFromPackage)
1211 .setRealCallingPid(-1)
1212 .setRealCallingUid(r.launchedFromUid)
1213 .setActivityOptions(options)
1214 .execute();
1215 Binder.restoreCallingIdentity(origId);
1216
1217 r.finishing = wasFinishing;
1218 if (res != ActivityManager.START_SUCCESS) {
1219 return false;
1220 }
1221 return true;
1222 }
1223 }
1224
1225 @Override
1226 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1227 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1228 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1229 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001230 enforceNotIsolatedCaller("startActivityAndWait");
1231 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1232 userId, "startActivityAndWait");
1233 // TODO: Switch to user app stacks here.
1234 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1235 .setCaller(caller)
1236 .setCallingPackage(callingPackage)
1237 .setResolvedType(resolvedType)
1238 .setResultTo(resultTo)
1239 .setResultWho(resultWho)
1240 .setRequestCode(requestCode)
1241 .setStartFlags(startFlags)
1242 .setActivityOptions(bOptions)
1243 .setUserId(userId)
1244 .setProfilerInfo(profilerInfo)
1245 .setWaitResult(res)
1246 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001247 return res;
1248 }
1249
1250 @Override
1251 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1252 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1253 int startFlags, Configuration config, Bundle bOptions, int userId) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001254 enforceNotIsolatedCaller("startActivityWithConfig");
1255 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1256 "startActivityWithConfig");
1257 // TODO: Switch to user app stacks here.
1258 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1259 .setCaller(caller)
1260 .setCallingPackage(callingPackage)
1261 .setResolvedType(resolvedType)
1262 .setResultTo(resultTo)
1263 .setResultWho(resultWho)
1264 .setRequestCode(requestCode)
1265 .setStartFlags(startFlags)
1266 .setGlobalConfiguration(config)
1267 .setActivityOptions(bOptions)
1268 .setUserId(userId)
1269 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001270 }
1271
Alison Cichowlas3e340502018-08-07 17:15:01 -04001272
1273 @Override
1274 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1275 int callingUid = Binder.getCallingUid();
1276 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1277 throw new SecurityException("Only the system process can request a permission token, "
1278 + "received request from uid: " + callingUid);
1279 }
1280 IBinder permissionToken = new Binder();
1281 synchronized (mGlobalLock) {
1282 mStartActivitySources.put(permissionToken, delegatorToken);
1283 }
1284
1285 Message expireMsg = PooledLambda.obtainMessage(
1286 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1287 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1288
1289 Message forgetMsg = PooledLambda.obtainMessage(
1290 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1291 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1292
1293 return permissionToken;
1294 }
1295
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001296 @Override
1297 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1298 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001299 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1300 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001301 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001302 // permission grants) as any app that may launch one of your own activities. So we only
1303 // allow this in two cases:
1304 // 1) The caller is an activity that is part of the core framework, and then only when it
1305 // is running as the system.
1306 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1307 // can only be requested by a system activity, which may then delegate this call to
1308 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001309 final ActivityRecord sourceRecord;
1310 final int targetUid;
1311 final String targetPackage;
1312 final boolean isResolver;
1313 synchronized (mGlobalLock) {
1314 if (resultTo == null) {
1315 throw new SecurityException("Must be called from an activity");
1316 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001317 final IBinder sourceToken;
1318 if (permissionToken != null) {
1319 // To even attempt to use a permissionToken, an app must also have this signature
1320 // permission.
1321 mAmInternal.enforceCallingPermission(
1322 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1323 "startActivityAsCaller");
1324 // If called with a permissionToken, we want the sourceRecord from the delegator
1325 // activity that requested this token.
1326 sourceToken = mStartActivitySources.remove(permissionToken);
1327 if (sourceToken == null) {
1328 // Invalid permissionToken, check if it recently expired.
1329 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1330 throw new SecurityException("Called with expired permission token: "
1331 + permissionToken);
1332 } else {
1333 throw new SecurityException("Called with invalid permission token: "
1334 + permissionToken);
1335 }
1336 }
1337 } else {
1338 // This method was called directly by the source.
1339 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001340 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001341
Wale Ogunwaled32da472018-11-16 07:19:28 -08001342 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001343 if (sourceRecord == null) {
1344 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001345 }
1346 if (sourceRecord.app == null) {
1347 throw new SecurityException("Called without a process attached to activity");
1348 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001349
1350 // Whether called directly or from a delegate, the source activity must be from the
1351 // android package.
1352 if (!sourceRecord.info.packageName.equals("android")) {
1353 throw new SecurityException("Must be called from an activity that is "
1354 + "declared in the android package");
1355 }
1356
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001357 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001358 // This is still okay, as long as this activity is running under the
1359 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001360 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001361 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001362 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001363 + " must be system uid or original calling uid "
1364 + sourceRecord.launchedFromUid);
1365 }
1366 }
1367 if (ignoreTargetSecurity) {
1368 if (intent.getComponent() == null) {
1369 throw new SecurityException(
1370 "Component must be specified with ignoreTargetSecurity");
1371 }
1372 if (intent.getSelector() != null) {
1373 throw new SecurityException(
1374 "Selector not allowed with ignoreTargetSecurity");
1375 }
1376 }
1377 targetUid = sourceRecord.launchedFromUid;
1378 targetPackage = sourceRecord.launchedFromPackage;
1379 isResolver = sourceRecord.isResolverOrChildActivity();
1380 }
1381
1382 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001383 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001384 }
1385
1386 // TODO: Switch to user app stacks here.
1387 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001388 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001389 .setCallingUid(targetUid)
1390 .setCallingPackage(targetPackage)
1391 .setResolvedType(resolvedType)
1392 .setResultTo(resultTo)
1393 .setResultWho(resultWho)
1394 .setRequestCode(requestCode)
1395 .setStartFlags(startFlags)
1396 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001397 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001398 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1399 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001400 // The target may well be in the background, which would normally prevent it
1401 // from starting an activity. Here we definitely want the start to succeed.
1402 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001403 .execute();
1404 } catch (SecurityException e) {
1405 // XXX need to figure out how to propagate to original app.
1406 // A SecurityException here is generally actually a fault of the original
1407 // calling activity (such as a fairly granting permissions), so propagate it
1408 // back to them.
1409 /*
1410 StringBuilder msg = new StringBuilder();
1411 msg.append("While launching");
1412 msg.append(intent.toString());
1413 msg.append(": ");
1414 msg.append(e.getMessage());
1415 */
1416 throw e;
1417 }
1418 }
1419
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001420 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1421 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1422 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1423 }
1424
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001425 @Override
1426 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1427 Intent intent, String resolvedType, IVoiceInteractionSession session,
1428 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1429 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001430 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001431 if (session == null || interactor == null) {
1432 throw new NullPointerException("null session or interactor");
1433 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001434 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001435 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001436 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001437 .setCallingUid(callingUid)
1438 .setCallingPackage(callingPackage)
1439 .setResolvedType(resolvedType)
1440 .setVoiceSession(session)
1441 .setVoiceInteractor(interactor)
1442 .setStartFlags(startFlags)
1443 .setProfilerInfo(profilerInfo)
1444 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001445 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001446 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001447 .execute();
1448 }
1449
1450 @Override
1451 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1452 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001453 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1454 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001456 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001457 .setCallingUid(callingUid)
1458 .setCallingPackage(callingPackage)
1459 .setResolvedType(resolvedType)
1460 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001461 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001462 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001463 .execute();
1464 }
1465
Riddle Hsu609a8e22019-06-27 16:46:29 -06001466 /**
1467 * Start the recents activity to perform the recents animation.
1468 *
1469 * @param intent The intent to start the recents activity.
1470 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1471 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001472 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001473 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1474 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001475 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001476 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001477 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001478 final long origId = Binder.clearCallingIdentity();
1479 try {
1480 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001481 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1482 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001483 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001484
1485 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001486 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001487 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001488 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001489 if (recentsAnimationRunner == null) {
1490 anim.preloadRecentsActivity();
1491 } else {
1492 anim.startRecentsActivity(recentsAnimationRunner);
1493 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001494 }
1495 } finally {
1496 Binder.restoreCallingIdentity(origId);
1497 }
1498 }
1499
1500 @Override
1501 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001502 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001503 "startActivityFromRecents()");
1504
1505 final int callingPid = Binder.getCallingPid();
1506 final int callingUid = Binder.getCallingUid();
1507 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1508 final long origId = Binder.clearCallingIdentity();
1509 try {
1510 synchronized (mGlobalLock) {
1511 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1512 safeOptions);
1513 }
1514 } finally {
1515 Binder.restoreCallingIdentity(origId);
1516 }
1517 }
1518
1519 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001520 * Public API to check if the client is allowed to start an activity on specified display.
1521 *
1522 * If the target display is private or virtual, some restrictions will apply.
1523 *
1524 * @param displayId Target display id.
1525 * @param intent Intent used to launch the activity.
1526 * @param resolvedType The MIME type of the intent.
1527 * @param userId The id of the user for whom the call is made.
1528 * @return {@code true} if a call to start an activity on the target display should succeed and
1529 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1530 */
1531 @Override
1532 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1533 String resolvedType, int userId) {
1534 final int callingUid = Binder.getCallingUid();
1535 final int callingPid = Binder.getCallingPid();
1536 final long origId = Binder.clearCallingIdentity();
1537
1538 try {
1539 // Collect information about the target of the Intent.
1540 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1541 0 /* startFlags */, null /* profilerInfo */, userId,
1542 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1543 UserHandle.USER_NULL));
1544 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1545
1546 synchronized (mGlobalLock) {
1547 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1548 aInfo);
1549 }
1550 } finally {
1551 Binder.restoreCallingIdentity(origId);
1552 }
1553 }
1554
1555 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001556 * This is the internal entry point for handling Activity.finish().
1557 *
1558 * @param token The Binder token referencing the Activity we want to finish.
1559 * @param resultCode Result code, if any, from this Activity.
1560 * @param resultData Result data (Intent), if any, from this Activity.
1561 * @param finishTask Whether to finish the task associated with this Activity.
1562 *
1563 * @return Returns true if the activity successfully finished, or false if it is still running.
1564 */
1565 @Override
1566 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1567 int finishTask) {
1568 // Refuse possible leaked file descriptors
1569 if (resultData != null && resultData.hasFileDescriptors()) {
1570 throw new IllegalArgumentException("File descriptors passed in Intent");
1571 }
1572
1573 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001574 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001575 if (r == null) {
1576 return true;
1577 }
1578 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001579 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001580 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001581 if (rootR == null) {
1582 Slog.w(TAG, "Finishing task with all activities already finished");
1583 }
1584 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1585 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001586 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001587 return false;
1588 }
1589
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001590 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1591 // We should consolidate.
1592 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001593 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001594 final ActivityRecord next =
1595 r.getActivityStack().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001596 if (next != null) {
1597 // ask watcher if this is allowed
1598 boolean resumeOK = true;
1599 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001600 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001601 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001602 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001603 Watchdog.getInstance().setActivityController(null);
1604 }
1605
1606 if (!resumeOK) {
1607 Slog.i(TAG, "Not finishing activity because controller resumed");
1608 return false;
1609 }
1610 }
1611 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001612
1613 // note down that the process has finished an activity and is in background activity
1614 // starts grace period
1615 if (r.app != null) {
1616 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1617 }
1618
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001619 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001620 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001621 try {
1622 boolean res;
1623 final boolean finishWithRootActivity =
1624 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1625 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1626 || (finishWithRootActivity && r == rootR)) {
1627 // If requested, remove the task that is associated to this activity only if it
1628 // was the root activity in the task. The result code and data is ignored
1629 // because we don't support returning them across task boundaries. Also, to
1630 // keep backwards compatibility we remove the task from recents when finishing
1631 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001632 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001633 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001634 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001635 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001636 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001637 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001638 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001639 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001640 if (!res) {
1641 Slog.i(TAG, "Failed to finish by app-request");
1642 }
1643 }
1644 return res;
1645 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001646 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001647 Binder.restoreCallingIdentity(origId);
1648 }
1649 }
1650 }
1651
1652 @Override
1653 public boolean finishActivityAffinity(IBinder token) {
1654 synchronized (mGlobalLock) {
1655 final long origId = Binder.clearCallingIdentity();
1656 try {
1657 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1658 if (r == null) {
1659 return false;
1660 }
1661
1662 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1663 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001664 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001665 return false;
1666 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001667
1668 final PooledFunction p = PooledLambda.obtainFunction(
1669 ActivityRecord::finishIfSameAffinity, r,
1670 PooledLambda.__(ActivityRecord.class));
1671 r.getTask().forAllActivities(
1672 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1673 p.recycle();
1674
Andrii Kuliande93eff2019-07-12 12:21:27 -07001675 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001676 } finally {
1677 Binder.restoreCallingIdentity(origId);
1678 }
1679 }
1680 }
1681
1682 @Override
1683 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1684 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001685 try {
1686 WindowProcessController proc = null;
1687 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001688 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001689 ActivityStack stack = ActivityRecord.getStackLocked(token);
1690 if (stack == null) {
1691 return;
1692 }
1693 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1694 false /* fromTimeout */, false /* processPausingActivities */, config);
1695 if (r != null) {
1696 proc = r.app;
1697 }
1698 if (stopProfiling && proc != null) {
1699 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001700 }
1701 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001702 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001703 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001704 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001705 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001706 }
1707
1708 @Override
1709 public final void activityResumed(IBinder token) {
1710 final long origId = Binder.clearCallingIdentity();
1711 synchronized (mGlobalLock) {
1712 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001713 }
1714 Binder.restoreCallingIdentity(origId);
1715 }
1716
1717 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001718 public final void activityTopResumedStateLost() {
1719 final long origId = Binder.clearCallingIdentity();
1720 synchronized (mGlobalLock) {
1721 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1722 }
1723 Binder.restoreCallingIdentity(origId);
1724 }
1725
1726 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001727 public final void activityPaused(IBinder token) {
1728 final long origId = Binder.clearCallingIdentity();
1729 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001730 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001731 ActivityStack stack = ActivityRecord.getStackLocked(token);
1732 if (stack != null) {
1733 stack.activityPausedLocked(token, false);
1734 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001735 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001736 }
1737 Binder.restoreCallingIdentity(origId);
1738 }
1739
1740 @Override
1741 public final void activityStopped(IBinder token, Bundle icicle,
1742 PersistableBundle persistentState, CharSequence description) {
1743 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1744
1745 // Refuse possible leaked file descriptors
1746 if (icicle != null && icicle.hasFileDescriptors()) {
1747 throw new IllegalArgumentException("File descriptors passed in Bundle");
1748 }
1749
1750 final long origId = Binder.clearCallingIdentity();
1751
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001752 String restartingName = null;
1753 int restartingUid = 0;
1754 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001755 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001756 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001757 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001758 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001759 if (r.attachedToProcess()
1760 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1761 // The activity was requested to restart from
1762 // {@link #restartActivityProcessIfVisible}.
1763 restartingName = r.app.mName;
1764 restartingUid = r.app.mUid;
1765 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001766 r.activityStoppedLocked(icicle, persistentState, description);
1767 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001768 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001769 }
1770
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001771 if (restartingName != null) {
1772 // In order to let the foreground activity can be restarted with its saved state from
1773 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1774 // until the activity reports stopped with the state. And the activity record will be
1775 // kept because the record state is restarting, then the activity will be restarted
1776 // immediately if it is still the top one.
1777 mStackSupervisor.removeRestartTimeouts(r);
1778 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1779 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001780 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001781
1782 Binder.restoreCallingIdentity(origId);
1783 }
1784
1785 @Override
1786 public final void activityDestroyed(IBinder token) {
1787 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1788 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001789 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001790 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001791 try {
1792 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1793 if (activity != null) {
1794 activity.destroyed("activityDestroyed");
1795 }
1796 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001797 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001798 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001799 }
1800 }
1801 }
1802
1803 @Override
1804 public final void activityRelaunched(IBinder token) {
1805 final long origId = Binder.clearCallingIdentity();
1806 synchronized (mGlobalLock) {
1807 mStackSupervisor.activityRelaunchedLocked(token);
1808 }
1809 Binder.restoreCallingIdentity(origId);
1810 }
1811
1812 public final void activitySlept(IBinder token) {
1813 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1814
1815 final long origId = Binder.clearCallingIdentity();
1816
1817 synchronized (mGlobalLock) {
1818 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1819 if (r != null) {
1820 mStackSupervisor.activitySleptLocked(r);
1821 }
1822 }
1823
1824 Binder.restoreCallingIdentity(origId);
1825 }
1826
1827 @Override
1828 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1829 synchronized (mGlobalLock) {
1830 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1831 if (r == null) {
1832 return;
1833 }
1834 final long origId = Binder.clearCallingIdentity();
1835 try {
1836 r.setRequestedOrientation(requestedOrientation);
1837 } finally {
1838 Binder.restoreCallingIdentity(origId);
1839 }
1840 }
1841 }
1842
1843 @Override
1844 public int getRequestedOrientation(IBinder token) {
1845 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001846 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1847 return (r != null)
1848 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001849 }
1850 }
1851
1852 @Override
1853 public void setImmersive(IBinder token, boolean immersive) {
1854 synchronized (mGlobalLock) {
1855 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1856 if (r == null) {
1857 throw new IllegalArgumentException();
1858 }
1859 r.immersive = immersive;
1860
1861 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001862 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001863 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001864 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001865 }
1866 }
1867 }
1868
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001869 void applyUpdateLockStateLocked(ActivityRecord r) {
1870 // Modifications to the UpdateLock state are done on our handler, outside
1871 // the activity manager's locks. The new state is determined based on the
1872 // state *now* of the relevant activity record. The object is passed to
1873 // the handler solely for logging detail, not to be consulted/modified.
1874 final boolean nextState = r != null && r.immersive;
1875 mH.post(() -> {
1876 if (mUpdateLock.isHeld() != nextState) {
1877 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1878 "Applying new update lock state '" + nextState + "' for " + r);
1879 if (nextState) {
1880 mUpdateLock.acquire();
1881 } else {
1882 mUpdateLock.release();
1883 }
1884 }
1885 });
1886 }
1887
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001888 @Override
1889 public boolean isImmersive(IBinder token) {
1890 synchronized (mGlobalLock) {
1891 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1892 if (r == null) {
1893 throw new IllegalArgumentException();
1894 }
1895 return r.immersive;
1896 }
1897 }
1898
1899 @Override
1900 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001901 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001902 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001903 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001904 return (r != null) ? r.immersive : false;
1905 }
1906 }
1907
1908 @Override
1909 public void overridePendingTransition(IBinder token, String packageName,
1910 int enterAnim, int exitAnim) {
1911 synchronized (mGlobalLock) {
1912 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1913 if (self == null) {
1914 return;
1915 }
1916
1917 final long origId = Binder.clearCallingIdentity();
1918
1919 if (self.isState(
1920 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001921 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001922 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001923 }
1924
1925 Binder.restoreCallingIdentity(origId);
1926 }
1927 }
1928
1929 @Override
1930 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001931 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001932 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001933 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001934 if (r == null) {
1935 return ActivityManager.COMPAT_MODE_UNKNOWN;
1936 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001937 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001938 }
1939 }
1940
1941 @Override
1942 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001943 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001944 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001945 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001946 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001947 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001948 if (r == null) {
1949 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1950 return;
1951 }
1952 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001953 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001954 }
1955 }
1956
1957 @Override
1958 public int getLaunchedFromUid(IBinder activityToken) {
1959 ActivityRecord srec;
1960 synchronized (mGlobalLock) {
1961 srec = ActivityRecord.forTokenLocked(activityToken);
1962 }
1963 if (srec == null) {
1964 return -1;
1965 }
1966 return srec.launchedFromUid;
1967 }
1968
1969 @Override
1970 public String getLaunchedFromPackage(IBinder activityToken) {
1971 ActivityRecord srec;
1972 synchronized (mGlobalLock) {
1973 srec = ActivityRecord.forTokenLocked(activityToken);
1974 }
1975 if (srec == null) {
1976 return null;
1977 }
1978 return srec.launchedFromPackage;
1979 }
1980
1981 @Override
1982 public boolean convertFromTranslucent(IBinder token) {
1983 final long origId = Binder.clearCallingIdentity();
1984 try {
1985 synchronized (mGlobalLock) {
1986 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1987 if (r == null) {
1988 return false;
1989 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001990 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001991 }
1992 } finally {
1993 Binder.restoreCallingIdentity(origId);
1994 }
1995 }
1996
1997 @Override
1998 public boolean convertToTranslucent(IBinder token, Bundle options) {
1999 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2000 final long origId = Binder.clearCallingIdentity();
2001 try {
2002 synchronized (mGlobalLock) {
2003 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2004 if (r == null) {
2005 return false;
2006 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002007 final ActivityRecord under = r.getTask().getActivityBelow(r);
2008 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002009 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2010 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002011 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002012 }
2013 } finally {
2014 Binder.restoreCallingIdentity(origId);
2015 }
2016 }
2017
2018 @Override
2019 public void notifyActivityDrawn(IBinder token) {
2020 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2021 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002022 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002023 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002024 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002025 }
2026 }
2027 }
2028
2029 @Override
2030 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2031 synchronized (mGlobalLock) {
2032 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2033 if (r == null) {
2034 return;
2035 }
2036 r.reportFullyDrawnLocked(restoredFromBundle);
2037 }
2038 }
2039
2040 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002041 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002042 synchronized (mGlobalLock) {
2043 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2044 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2045 return stack.mDisplayId;
2046 }
2047 return DEFAULT_DISPLAY;
2048 }
2049 }
2050
2051 @Override
2052 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002053 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002054 long ident = Binder.clearCallingIdentity();
2055 try {
2056 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002057 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002058 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002059 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 }
2061 return null;
2062 }
2063 } finally {
2064 Binder.restoreCallingIdentity(ident);
2065 }
2066 }
2067
2068 @Override
2069 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002070 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002071 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2072 final long callingId = Binder.clearCallingIdentity();
2073 try {
2074 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002075 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002076 if (stack == null) {
2077 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2078 return;
2079 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002080 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002081 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002082 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002083 }
2084 }
2085 } finally {
2086 Binder.restoreCallingIdentity(callingId);
2087 }
2088 }
2089
2090 @Override
2091 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002092 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002093 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2094 final long callingId = Binder.clearCallingIdentity();
2095 try {
2096 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002097 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002098 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002099 if (task == null) {
2100 return;
2101 }
2102 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002103 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002104 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002105 }
2106 }
2107 } finally {
2108 Binder.restoreCallingIdentity(callingId);
2109 }
2110 }
2111
2112 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002113 public void restartActivityProcessIfVisible(IBinder activityToken) {
2114 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2115 final long callingId = Binder.clearCallingIdentity();
2116 try {
2117 synchronized (mGlobalLock) {
2118 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2119 if (r == null) {
2120 return;
2121 }
2122 r.restartProcessIfVisible();
2123 }
2124 } finally {
2125 Binder.restoreCallingIdentity(callingId);
2126 }
2127 }
2128
2129 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002130 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002131 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002132 synchronized (mGlobalLock) {
2133 final long ident = Binder.clearCallingIdentity();
2134 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002135 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002136 "remove-task");
2137 } finally {
2138 Binder.restoreCallingIdentity(ident);
2139 }
2140 }
2141 }
2142
2143 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002144 public void removeAllVisibleRecentTasks() {
2145 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2146 synchronized (mGlobalLock) {
2147 final long ident = Binder.clearCallingIdentity();
2148 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002149 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002150 } finally {
2151 Binder.restoreCallingIdentity(ident);
2152 }
2153 }
2154 }
2155
2156 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002157 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2158 synchronized (mGlobalLock) {
2159 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2160 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002161 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002162 }
2163 }
2164 return false;
2165 }
2166
2167 @Override
2168 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2169 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002170
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002171 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002172 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2173 if (r != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002174 return r.getActivityStack().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002175 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002176 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002177 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002178 }
2179 }
2180
2181 /**
2182 * Attempts to move a task backwards in z-order (the order of activities within the task is
2183 * unchanged).
2184 *
2185 * There are several possible results of this call:
2186 * - if the task is locked, then we will show the lock toast
2187 * - if there is a task behind the provided task, then that task is made visible and resumed as
2188 * this task is moved to the back
2189 * - otherwise, if there are no other tasks in the stack:
2190 * - if this task is in the pinned stack, then we remove the stack completely, which will
2191 * have the effect of moving the task to the top or bottom of the fullscreen stack
2192 * (depending on whether it is visible)
2193 * - otherwise, we simply return home and hide this task
2194 *
2195 * @param token A reference to the activity we wish to move
2196 * @param nonRoot If false then this only works if the activity is the root
2197 * of a task; if true it will work for any activity in a task.
2198 * @return Returns true if the move completed, false if not.
2199 */
2200 @Override
2201 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002202 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002203 synchronized (mGlobalLock) {
2204 final long origId = Binder.clearCallingIdentity();
2205 try {
2206 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Changcdec0802019-11-11 11:45:07 +08002207 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002208 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002209 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002210 }
2211 } finally {
2212 Binder.restoreCallingIdentity(origId);
2213 }
2214 }
2215 return false;
2216 }
2217
2218 @Override
2219 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002220 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002221 long ident = Binder.clearCallingIdentity();
2222 Rect rect = new Rect();
2223 try {
2224 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002225 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002226 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2227 if (task == null) {
2228 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2229 return rect;
2230 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002231 if (task.getParent() != null) {
2232 rect.set(task.getBounds());
2233 } else if (task.mLastNonFullscreenBounds != null) {
2234 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002235 }
2236 }
2237 } finally {
2238 Binder.restoreCallingIdentity(ident);
2239 }
2240 return rect;
2241 }
2242
2243 @Override
2244 public ActivityManager.TaskDescription getTaskDescription(int id) {
2245 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002246 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002247 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Changcdec0802019-11-11 11:45:07 +08002248 final Task tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002249 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2250 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002251 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002252 }
2253 }
2254 return null;
2255 }
2256
2257 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002258 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2259 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2260 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2261 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2262 return;
2263 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002264 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002265 synchronized (mGlobalLock) {
2266 final long ident = Binder.clearCallingIdentity();
2267 try {
Louis Changcdec0802019-11-11 11:45:07 +08002268 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002269 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002270 if (task == null) {
2271 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2272 return;
2273 }
2274
2275 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2276 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2277
2278 if (!task.isActivityTypeStandardOrUndefined()) {
2279 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2280 + " non-standard task " + taskId + " to windowing mode="
2281 + windowingMode);
2282 }
2283
2284 final ActivityStack stack = task.getStack();
2285 if (toTop) {
2286 stack.moveToFront("setTaskWindowingMode", task);
2287 }
2288 stack.setWindowingMode(windowingMode);
2289 } finally {
2290 Binder.restoreCallingIdentity(ident);
2291 }
2292 }
2293 }
2294
2295 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002296 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002297 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002298 ActivityRecord r = getCallingRecordLocked(token);
2299 return r != null ? r.info.packageName : null;
2300 }
2301 }
2302
2303 @Override
2304 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002305 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002306 ActivityRecord r = getCallingRecordLocked(token);
2307 return r != null ? r.intent.getComponent() : null;
2308 }
2309 }
2310
2311 private ActivityRecord getCallingRecordLocked(IBinder token) {
2312 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2313 if (r == null) {
2314 return null;
2315 }
2316 return r.resultTo;
2317 }
2318
2319 @Override
2320 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002321 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002322
2323 synchronized (mGlobalLock) {
2324 final long origId = Binder.clearCallingIdentity();
2325 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002326 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002327 } finally {
2328 Binder.restoreCallingIdentity(origId);
2329 }
2330 }
2331 }
2332
Mark Renouf446251d2019-04-26 10:22:41 -04002333 @Override
2334 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2335 synchronized (mGlobalLock) {
2336 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2337 if (r == null) {
2338 return;
2339 }
2340 ActivityStack stack = r.getActivityStack();
2341 if (stack != null && stack.isSingleTaskInstance()) {
2342 // Single-task stacks are used for activities which are presented in floating
2343 // windows above full screen activities. Instead of directly finishing the
2344 // task, a task change listener is used to notify SystemUI so the action can be
2345 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002346 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002347 mTaskChangeNotificationController
2348 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2349 } else {
2350 try {
2351 callback.requestFinish();
2352 } catch (RemoteException e) {
2353 Slog.e(TAG, "Failed to invoke request finish callback", e);
2354 }
2355 }
2356 }
2357 }
2358
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002359 /**
2360 * TODO: Add mController hook
2361 */
2362 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002363 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2364 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002365 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002366
2367 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2368 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002369 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2370 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002371 }
2372 }
2373
Ricky Waiaca8a772019-04-04 16:01:06 +01002374 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2375 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002376 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002377
Ricky Waiaca8a772019-04-04 16:01:06 +01002378 final int callingPid = Binder.getCallingPid();
2379 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002380 if (!isSameApp(callingUid, callingPackage)) {
2381 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2382 + Binder.getCallingPid() + " as package " + callingPackage;
2383 Slog.w(TAG, msg);
2384 throw new SecurityException(msg);
2385 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002386 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002387 SafeActivityOptions.abort(options);
2388 return;
2389 }
2390 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002391 WindowProcessController callerApp = null;
2392 if (appThread != null) {
2393 callerApp = getProcessController(appThread);
2394 }
2395 final ActivityStarter starter = getActivityStartController().obtainStarter(
2396 null /* intent */, "moveTaskToFront");
2397 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2398 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002399 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002400 return;
2401 }
2402 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002403 try {
Louis Changcdec0802019-11-11 11:45:07 +08002404 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002405 if (task == null) {
2406 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002407 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002408 return;
2409 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002410 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002411 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002412 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002413 return;
2414 }
2415 ActivityOptions realOptions = options != null
2416 ? options.getOptions(mStackSupervisor)
2417 : null;
2418 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2419 false /* forceNonResizable */);
2420
Wale Ogunwale21e06482019-11-18 05:14:15 -08002421 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002422 if (topActivity != null) {
2423
2424 // We are reshowing a task, use a starting window to hide the initial draw delay
2425 // so the transition can start earlier.
2426 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2427 true /* taskSwitch */, fromRecents);
2428 }
2429 } finally {
2430 Binder.restoreCallingIdentity(origId);
2431 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002432 }
2433
Ricky Waiaca8a772019-04-04 16:01:06 +01002434 /**
2435 * Return true if callingUid is system, or packageName belongs to that callingUid.
2436 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002437 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002438 try {
2439 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2440 if (packageName == null) {
2441 return false;
2442 }
2443 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2444 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2445 UserHandle.getUserId(callingUid));
2446 return UserHandle.isSameApp(callingUid, uid);
2447 }
2448 } catch (RemoteException e) {
2449 // Should not happen
2450 }
2451 return true;
2452 }
2453
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002454 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2455 int callingPid, int callingUid, String name) {
2456 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2457 return true;
2458 }
2459
2460 if (getRecentTasks().isCallerRecents(sourceUid)) {
2461 return true;
2462 }
2463
2464 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2465 if (perm == PackageManager.PERMISSION_GRANTED) {
2466 return true;
2467 }
2468 if (checkAllowAppSwitchUid(sourceUid)) {
2469 return true;
2470 }
2471
2472 // If the actual IPC caller is different from the logical source, then
2473 // also see if they are allowed to control app switches.
2474 if (callingUid != -1 && callingUid != sourceUid) {
2475 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2476 if (perm == PackageManager.PERMISSION_GRANTED) {
2477 return true;
2478 }
2479 if (checkAllowAppSwitchUid(callingUid)) {
2480 return true;
2481 }
2482 }
2483
2484 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2485 return false;
2486 }
2487
2488 private boolean checkAllowAppSwitchUid(int uid) {
2489 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2490 if (types != null) {
2491 for (int i = types.size() - 1; i >= 0; i--) {
2492 if (types.valueAt(i).intValue() == uid) {
2493 return true;
2494 }
2495 }
2496 }
2497 return false;
2498 }
2499
2500 @Override
2501 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2502 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2503 "setActivityController()");
2504 synchronized (mGlobalLock) {
2505 mController = controller;
2506 mControllerIsAMonkey = imAMonkey;
2507 Watchdog.getInstance().setActivityController(controller);
2508 }
2509 }
2510
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002511 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002512 synchronized (mGlobalLock) {
2513 return mController != null && mControllerIsAMonkey;
2514 }
2515 }
2516
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002517 @Override
2518 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2519 synchronized (mGlobalLock) {
2520 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2521 }
2522 }
2523
2524 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002525 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2526 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2527 }
2528
2529 @Override
2530 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2531 @WindowConfiguration.ActivityType int ignoreActivityType,
2532 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2533 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002534 final int callingPid = Binder.getCallingPid();
2535 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002536 final int[] profileIds = getUserManager().getProfileIds(
2537 UserHandle.getUserId(callingUid), true);
2538 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2539 for (int i = 0; i < profileIds.length; i++) {
2540 callingProfileIds.add(profileIds[i]);
2541 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002542 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2543
2544 synchronized (mGlobalLock) {
2545 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2546
Nicholas Sauer0259e532019-08-30 08:24:55 -07002547 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002548 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002549 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002550 }
2551
2552 return list;
2553 }
2554
2555 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002556 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2557 synchronized (mGlobalLock) {
2558 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002559 try {
2560 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2561 if (r == null) return;
2562
2563 final PooledConsumer c = PooledLambda.obtainConsumer(
2564 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2565 r, resultWho, requestCode);
2566 // TODO: This should probably only loop over the task since you need to be in the
2567 // same task to return results.
2568 r.getActivityStack().forAllActivities(c);
2569 c.recycle();
2570
2571 updateOomAdj();
2572 } finally {
2573 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002574 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002575 }
2576 }
2577
2578 @Override
2579 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002580 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002581 ActivityStack stack = ActivityRecord.getStackLocked(token);
2582 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002583 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002584 }
2585 return false;
2586 }
2587 }
2588
2589 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002590 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002591 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002592 synchronized (mGlobalLock) {
2593 final long ident = Binder.clearCallingIdentity();
2594 try {
Louis Changcdec0802019-11-11 11:45:07 +08002595 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002596 if (task == null) {
2597 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2598 return;
2599 }
2600
2601 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2602 + " to stackId=" + stackId + " toTop=" + toTop);
2603
Wale Ogunwaled32da472018-11-16 07:19:28 -08002604 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002605 if (stack == null) {
2606 throw new IllegalStateException(
2607 "moveTaskToStack: No stack for stackId=" + stackId);
2608 }
2609 if (!stack.isActivityTypeStandardOrUndefined()) {
2610 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2611 + taskId + " to stack " + stackId);
2612 }
2613 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002614 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002615 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2616 }
2617 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2618 "moveTaskToStack");
2619 } finally {
2620 Binder.restoreCallingIdentity(ident);
2621 }
2622 }
2623 }
2624
2625 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002626 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2627 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002628
2629 final long ident = Binder.clearCallingIdentity();
2630 try {
2631 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002632 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2633 if (stack == null) {
2634 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2635 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002636 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002637 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2638 throw new IllegalArgumentException("Stack: " + stackId
2639 + " doesn't support animated resize.");
2640 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002641 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002642 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002643 }
2644 } finally {
2645 Binder.restoreCallingIdentity(ident);
2646 }
2647 }
2648
wilsonshih5c4cf522019-01-25 09:03:47 +08002649 @Override
2650 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2651 int animationDuration) {
2652 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2653
2654 final long ident = Binder.clearCallingIdentity();
2655 try {
2656 synchronized (mGlobalLock) {
2657 if (xOffset == 0 && yOffset == 0) {
2658 return;
2659 }
2660 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2661 if (stack == null) {
2662 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2663 return;
2664 }
2665 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2666 throw new IllegalArgumentException("Stack: " + stackId
2667 + " doesn't support animated resize.");
2668 }
2669 final Rect destBounds = new Rect();
2670 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002671 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002672 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2673 return;
2674 }
2675 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002676 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002677 animationDuration, false /* fromFullscreen */);
2678 }
2679 } finally {
2680 Binder.restoreCallingIdentity(ident);
2681 }
2682 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002683 /**
2684 * Moves the specified task to the primary-split-screen stack.
2685 *
2686 * @param taskId Id of task to move.
2687 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2688 * exist already. See
2689 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2690 * and
2691 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2692 * @param toTop If the task and stack should be moved to the top.
2693 * @param animate Whether we should play an animation for the moving the task.
2694 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2695 * stack. Pass {@code null} to use default bounds.
2696 * @param showRecents If the recents activity should be shown on the other side of the task
2697 * going into split-screen mode.
2698 */
2699 @Override
2700 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2701 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002702 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002703 "setTaskWindowingModeSplitScreenPrimary()");
2704 synchronized (mGlobalLock) {
2705 final long ident = Binder.clearCallingIdentity();
2706 try {
Louis Changcdec0802019-11-11 11:45:07 +08002707 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002708 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002709 if (task == null) {
2710 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2711 return false;
2712 }
2713 if (DEBUG_STACK) Slog.d(TAG_STACK,
2714 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2715 + " to createMode=" + createMode + " toTop=" + toTop);
2716 if (!task.isActivityTypeStandardOrUndefined()) {
2717 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2718 + " non-standard task " + taskId + " to split-screen windowing mode");
2719 }
2720
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002721 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002722 final int windowingMode = task.getWindowingMode();
2723 final ActivityStack stack = task.getStack();
2724 if (toTop) {
2725 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2726 }
2727 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002728 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2729 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002730 return windowingMode != task.getWindowingMode();
2731 } finally {
2732 Binder.restoreCallingIdentity(ident);
2733 }
2734 }
2735 }
2736
2737 /**
2738 * Removes stacks in the input windowing modes from the system if they are of activity type
2739 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2740 */
2741 @Override
2742 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002743 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002744 "removeStacksInWindowingModes()");
2745
2746 synchronized (mGlobalLock) {
2747 final long ident = Binder.clearCallingIdentity();
2748 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002749 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002750 } finally {
2751 Binder.restoreCallingIdentity(ident);
2752 }
2753 }
2754 }
2755
2756 @Override
2757 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002758 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002759 "removeStacksWithActivityTypes()");
2760
2761 synchronized (mGlobalLock) {
2762 final long ident = Binder.clearCallingIdentity();
2763 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002764 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002765 } finally {
2766 Binder.restoreCallingIdentity(ident);
2767 }
2768 }
2769 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002770
2771 @Override
2772 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2773 int userId) {
2774 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002775 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2776 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002777 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002778 final boolean detailed = checkGetTasksPermission(
2779 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2780 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002781 == PackageManager.PERMISSION_GRANTED;
2782
2783 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002784 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002785 callingUid);
2786 }
2787 }
2788
2789 @Override
2790 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002791 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002792 long ident = Binder.clearCallingIdentity();
2793 try {
2794 synchronized (mGlobalLock) {
Evan Roskyfd439692019-11-06 16:12:59 -08002795 return mRootActivityContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002796 }
2797 } finally {
2798 Binder.restoreCallingIdentity(ident);
2799 }
2800 }
2801
2802 @Override
2803 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002804 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002805 long ident = Binder.clearCallingIdentity();
2806 try {
2807 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002808 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 }
2810 } finally {
2811 Binder.restoreCallingIdentity(ident);
2812 }
2813 }
2814
2815 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002816 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2817 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2818 long ident = Binder.clearCallingIdentity();
2819 try {
2820 synchronized (mGlobalLock) {
2821 return mRootActivityContainer.getAllStackInfos(displayId);
2822 }
2823 } finally {
2824 Binder.restoreCallingIdentity(ident);
2825 }
2826 }
2827
2828 @Override
2829 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2830 int displayId) {
2831 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2832 long ident = Binder.clearCallingIdentity();
2833 try {
2834 synchronized (mGlobalLock) {
2835 return mRootActivityContainer.getStackInfo(windowingMode, activityType, displayId);
2836 }
2837 } finally {
2838 Binder.restoreCallingIdentity(ident);
2839 }
2840 }
2841
2842 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002843 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002844 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002845 final long callingUid = Binder.getCallingUid();
2846 final long origId = Binder.clearCallingIdentity();
2847 try {
2848 synchronized (mGlobalLock) {
2849 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002850 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002851 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2852 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2853 }
2854 } finally {
2855 Binder.restoreCallingIdentity(origId);
2856 }
2857 }
2858
2859 @Override
2860 public void startLockTaskModeByToken(IBinder token) {
2861 synchronized (mGlobalLock) {
2862 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2863 if (r == null) {
2864 return;
2865 }
Louis Changcdec0802019-11-11 11:45:07 +08002866 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002867 }
2868 }
2869
2870 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002871 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002872 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002873 // This makes inner call to look as if it was initiated by system.
2874 long ident = Binder.clearCallingIdentity();
2875 try {
2876 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002877 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002878 MATCH_TASK_IN_STACKS_ONLY);
2879 if (task == null) {
2880 return;
2881 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002882
2883 // When starting lock task mode the stack must be in front and focused
2884 task.getStack().moveToFront("startSystemLockTaskMode");
2885 startLockTaskModeLocked(task, true /* isSystemCaller */);
2886 }
2887 } finally {
2888 Binder.restoreCallingIdentity(ident);
2889 }
2890 }
2891
2892 @Override
2893 public void stopLockTaskModeByToken(IBinder token) {
2894 synchronized (mGlobalLock) {
2895 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2896 if (r == null) {
2897 return;
2898 }
Louis Changcdec0802019-11-11 11:45:07 +08002899 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002900 }
2901 }
2902
2903 /**
2904 * This API should be called by SystemUI only when user perform certain action to dismiss
2905 * lock task mode. We should only dismiss pinned lock task mode in this case.
2906 */
2907 @Override
2908 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002909 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002910 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2911 }
2912
Louis Changcdec0802019-11-11 11:45:07 +08002913 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002914 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2915 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2916 return;
2917 }
2918
Wale Ogunwaled32da472018-11-16 07:19:28 -08002919 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002920 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002921 throw new IllegalArgumentException("Invalid task, not in foreground");
2922 }
2923
2924 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2925 // system or a specific app.
2926 // * System-initiated requests will only start the pinned mode (screen pinning)
2927 // * App-initiated requests
2928 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2929 // - will start the pinned mode, otherwise
2930 final int callingUid = Binder.getCallingUid();
2931 long ident = Binder.clearCallingIdentity();
2932 try {
2933 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002934 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002935
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002936 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002937 } finally {
2938 Binder.restoreCallingIdentity(ident);
2939 }
2940 }
2941
Louis Changcdec0802019-11-11 11:45:07 +08002942 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002943 final int callingUid = Binder.getCallingUid();
2944 long ident = Binder.clearCallingIdentity();
2945 try {
2946 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002947 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002948 }
2949 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2950 // task and jumping straight into a call in the case of emergency call back.
2951 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2952 if (tm != null) {
2953 tm.showInCallScreen(false);
2954 }
2955 } finally {
2956 Binder.restoreCallingIdentity(ident);
2957 }
2958 }
2959
2960 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002961 public void updateLockTaskPackages(int userId, String[] packages) {
2962 final int callingUid = Binder.getCallingUid();
2963 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2964 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2965 "updateLockTaskPackages()");
2966 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002967 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002968 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2969 + Arrays.toString(packages));
2970 getLockTaskController().updateLockTaskPackages(userId, packages);
2971 }
2972 }
2973
2974 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002975 public boolean isInLockTaskMode() {
2976 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2977 }
2978
2979 @Override
2980 public int getLockTaskModeState() {
2981 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002982 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002983 }
2984 }
2985
2986 @Override
2987 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2988 synchronized (mGlobalLock) {
2989 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2990 if (r != null) {
2991 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08002992 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002993 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002994 }
2995 }
2996 }
2997
2998 @Override
2999 public Bundle getActivityOptions(IBinder token) {
3000 final long origId = Binder.clearCallingIdentity();
3001 try {
3002 synchronized (mGlobalLock) {
3003 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3004 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003005 final ActivityOptions activityOptions = r.takeOptionsLocked(
3006 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003007 return activityOptions == null ? null : activityOptions.toBundle();
3008 }
3009 return null;
3010 }
3011 } finally {
3012 Binder.restoreCallingIdentity(origId);
3013 }
3014 }
3015
3016 @Override
3017 public List<IBinder> getAppTasks(String callingPackage) {
3018 int callingUid = Binder.getCallingUid();
3019 long ident = Binder.clearCallingIdentity();
3020 try {
3021 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003022 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003023 }
3024 } finally {
3025 Binder.restoreCallingIdentity(ident);
3026 }
3027 }
3028
3029 @Override
3030 public void finishVoiceTask(IVoiceInteractionSession session) {
3031 synchronized (mGlobalLock) {
3032 final long origId = Binder.clearCallingIdentity();
3033 try {
3034 // TODO: VI Consider treating local voice interactions and voice tasks
3035 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08003036 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003037 } finally {
3038 Binder.restoreCallingIdentity(origId);
3039 }
3040 }
3041
3042 }
3043
3044 @Override
3045 public boolean isTopOfTask(IBinder token) {
3046 synchronized (mGlobalLock) {
3047 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003048 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003049 }
3050 }
3051
3052 @Override
3053 public void notifyLaunchTaskBehindComplete(IBinder token) {
3054 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3055 }
3056
3057 @Override
3058 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003059 mH.post(() -> {
3060 synchronized (mGlobalLock) {
3061 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003062 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003063 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003064 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003065 } catch (RemoteException e) {
3066 }
3067 }
3068 }
3069
3070 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003071 }
3072
3073 /** Called from an app when assist data is ready. */
3074 @Override
3075 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3076 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003077 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003078 synchronized (pae) {
3079 pae.result = extras;
3080 pae.structure = structure;
3081 pae.content = content;
3082 if (referrer != null) {
3083 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3084 }
3085 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003086 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003087 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003088 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003089 structure.setHomeActivity(pae.isHome);
3090 }
3091 pae.haveResult = true;
3092 pae.notifyAll();
3093 if (pae.intent == null && pae.receiver == null) {
3094 // Caller is just waiting for the result.
3095 return;
3096 }
3097 }
3098 // We are now ready to launch the assist activity.
3099 IAssistDataReceiver sendReceiver = null;
3100 Bundle sendBundle = null;
3101 synchronized (mGlobalLock) {
3102 buildAssistBundleLocked(pae, extras);
3103 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003104 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003105 if (!exists) {
3106 // Timed out.
3107 return;
3108 }
3109
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003110 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003111 // Caller wants result sent back to them.
3112 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003113 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003114 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003115 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3116 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003117 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3118 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3119 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3120 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3121 }
3122 }
3123 if (sendReceiver != null) {
3124 try {
3125 sendReceiver.onHandleAssistData(sendBundle);
3126 } catch (RemoteException e) {
3127 }
3128 return;
3129 }
3130
3131 final long ident = Binder.clearCallingIdentity();
3132 try {
3133 if (TextUtils.equals(pae.intent.getAction(),
3134 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003135 // Start voice interaction through VoiceInteractionManagerService.
3136 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3137 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003138 } else {
3139 pae.intent.replaceExtras(pae.extras);
3140 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3141 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3142 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003143 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003144
3145 try {
3146 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3147 } catch (ActivityNotFoundException e) {
3148 Slog.w(TAG, "No activity to handle assist action.", e);
3149 }
3150 }
3151 } finally {
3152 Binder.restoreCallingIdentity(ident);
3153 }
3154 }
3155
3156 @Override
3157 public int addAppTask(IBinder activityToken, Intent intent,
3158 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3159 final int callingUid = Binder.getCallingUid();
3160 final long callingIdent = Binder.clearCallingIdentity();
3161
3162 try {
3163 synchronized (mGlobalLock) {
3164 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3165 if (r == null) {
3166 throw new IllegalArgumentException("Activity does not exist; token="
3167 + activityToken);
3168 }
3169 ComponentName comp = intent.getComponent();
3170 if (comp == null) {
3171 throw new IllegalArgumentException("Intent " + intent
3172 + " must specify explicit component");
3173 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003174 if (thumbnail.getWidth() != mThumbnailWidth
3175 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003176 throw new IllegalArgumentException("Bad thumbnail size: got "
3177 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003178 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003179 }
3180 if (intent.getSelector() != null) {
3181 intent.setSelector(null);
3182 }
3183 if (intent.getSourceBounds() != null) {
3184 intent.setSourceBounds(null);
3185 }
3186 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3187 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3188 // The caller has added this as an auto-remove task... that makes no
3189 // sense, so turn off auto-remove.
3190 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3191 }
3192 }
3193 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3194 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3195 if (ainfo.applicationInfo.uid != callingUid) {
3196 throw new SecurityException(
3197 "Can't add task for another application: target uid="
3198 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3199 }
3200
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003201 final ActivityStack stack = r.getActivityStack();
Louis Changcdec0802019-11-11 11:45:07 +08003202 final Task task = stack.createTask(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003203 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003204 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003205 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003207 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003208 return INVALID_TASK_ID;
3209 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003210 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003211
3212 // TODO: Send the thumbnail to WM to store it.
3213
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003214 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003215 }
3216 } finally {
3217 Binder.restoreCallingIdentity(callingIdent);
3218 }
3219 }
3220
3221 @Override
3222 public Point getAppTaskThumbnailSize() {
3223 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003224 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003225 }
3226 }
3227
3228 @Override
3229 public void setTaskResizeable(int taskId, int resizeableMode) {
3230 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08003231 final Task task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003232 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3233 if (task == null) {
3234 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3235 return;
3236 }
3237 task.setResizeMode(resizeableMode);
3238 }
3239 }
3240
3241 @Override
3242 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003243 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003244 long ident = Binder.clearCallingIdentity();
3245 try {
3246 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08003247 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003248 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003249 if (task == null) {
3250 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3251 return;
3252 }
3253 // Place the task in the right stack if it isn't there already based on
3254 // the requested bounds.
3255 // The stack transition logic is:
3256 // - a null bounds on a freeform task moves that task to fullscreen
3257 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3258 // that task to freeform
3259 // - otherwise the task is not moved
3260 ActivityStack stack = task.getStack();
3261 if (!task.getWindowConfiguration().canResizeTask()) {
3262 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3263 }
3264 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3265 stack = stack.getDisplay().getOrCreateStack(
3266 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3267 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3268 stack = stack.getDisplay().getOrCreateStack(
3269 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3270 }
3271
3272 // Reparent the task to the right stack if necessary
3273 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3274 if (stack != task.getStack()) {
3275 // Defer resume until the task is resized below
3276 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3277 DEFER_RESUME, "resizeTask");
3278 preserveWindow = false;
3279 }
3280
3281 // After reparenting (which only resizes the task to the stack bounds), resize the
3282 // task to the actual bounds provided
3283 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3284 }
3285 } finally {
3286 Binder.restoreCallingIdentity(ident);
3287 }
3288 }
3289
Evan Roskyddedfd42019-10-04 13:38:38 -07003290 private void sanitizeAndApplyConfigChange(ConfigurationContainer container,
3291 WindowContainerTransaction.Change change) {
Evan Rosky282ee672019-11-13 15:50:46 -08003292 if (!(container instanceof Task || container instanceof ActivityStack)) {
Evan Roskyddedfd42019-10-04 13:38:38 -07003293 throw new RuntimeException("Invalid token in task transaction");
3294 }
3295 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3296 // masks here.
3297 int configMask = change.getConfigSetMask();
3298 int windowMask = change.getWindowSetMask();
3299 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3300 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3301 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
3302 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3303 c.setTo(change.getConfiguration(), configMask, windowMask);
3304 container.onRequestedOverrideConfigurationChanged(c);
Hongwei Wangebf18082019-09-26 14:25:11 -07003305 // TODO(b/145675353): remove the following once we could apply new bounds to the
3306 // pinned stack together with its children.
3307 resizePinnedStackIfNeeded(container, configMask, windowMask, c);
3308 }
3309
3310 private void resizePinnedStackIfNeeded(ConfigurationContainer container, int configMask,
3311 int windowMask, Configuration config) {
3312 if ((container instanceof ActivityStack)
3313 && ((configMask & ActivityInfo.CONFIG_WINDOW_CONFIGURATION) != 0)
3314 && ((windowMask & WindowConfiguration.WINDOW_CONFIG_BOUNDS) != 0)) {
3315 final ActivityStack stack = (ActivityStack) container;
3316 if (stack.inPinnedWindowingMode()) {
3317 stack.resize(config.windowConfiguration.getBounds(),
3318 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
3319 PRESERVE_WINDOWS, true /* deferResume */);
3320 }
3321 }
Evan Roskyddedfd42019-10-04 13:38:38 -07003322 }
3323
3324 @Override
3325 public void applyContainerTransaction(WindowContainerTransaction t) {
3326 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
3327 long ident = Binder.clearCallingIdentity();
3328 try {
3329 if (t == null) {
3330 return;
3331 }
3332 synchronized (mGlobalLock) {
3333 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3334 t.getChanges().entrySet().iterator();
3335 while (entries.hasNext()) {
3336 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3337 entries.next();
3338 final ConfigurationContainer cc = ConfigurationContainer.RemoteToken.fromBinder(
3339 entry.getKey()).getContainer();
3340 sanitizeAndApplyConfigChange(cc, entry.getValue());
3341 }
3342 }
3343 } finally {
3344 Binder.restoreCallingIdentity(ident);
3345 }
3346 }
3347
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003348 @Override
3349 public boolean releaseActivityInstance(IBinder token) {
3350 synchronized (mGlobalLock) {
3351 final long origId = Binder.clearCallingIdentity();
3352 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003353 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3354 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003355 return false;
3356 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003357 r.destroyImmediately(true /* removeFromApp */, "app-req");
3358 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003359 } finally {
3360 Binder.restoreCallingIdentity(origId);
3361 }
3362 }
3363 }
3364
3365 @Override
3366 public void releaseSomeActivities(IApplicationThread appInt) {
3367 synchronized (mGlobalLock) {
3368 final long origId = Binder.clearCallingIdentity();
3369 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003370 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003371 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003372 } finally {
3373 Binder.restoreCallingIdentity(origId);
3374 }
3375 }
3376 }
3377
3378 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003379 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003380 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003381 != PackageManager.PERMISSION_GRANTED) {
3382 throw new SecurityException("Requires permission "
3383 + android.Manifest.permission.DEVICE_POWER);
3384 }
3385
3386 synchronized (mGlobalLock) {
3387 long ident = Binder.clearCallingIdentity();
3388 if (mKeyguardShown != keyguardShowing) {
3389 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003390 final Message msg = PooledLambda.obtainMessage(
3391 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3392 keyguardShowing);
3393 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003394 }
3395 try {
wilsonshih177261f2019-02-22 12:02:18 +08003396 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003397 } finally {
3398 Binder.restoreCallingIdentity(ident);
3399 }
3400 }
3401
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003402 mH.post(() -> {
3403 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3404 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3405 }
3406 });
3407 }
3408
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003409 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003410 mH.post(() -> {
3411 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3412 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3413 }
3414 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003415 }
3416
3417 @Override
3418 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003419 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3420 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003421
3422 final File passedIconFile = new File(filePath);
3423 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3424 passedIconFile.getName());
3425 if (!legitIconFile.getPath().equals(filePath)
3426 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3427 throw new IllegalArgumentException("Bad file path: " + filePath
3428 + " passed for userId " + userId);
3429 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003430 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003431 }
3432
3433 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003434 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003435 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003436 synchronized (mGlobalLock) {
3437 final long ident = Binder.clearCallingIdentity();
3438 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003439 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003440 if (stack == null) {
3441 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3442 return;
3443 }
3444 if (!stack.isActivityTypeStandardOrUndefined()) {
3445 throw new IllegalArgumentException(
3446 "Removing non-standard stack is not allowed.");
3447 }
3448 mStackSupervisor.removeStack(stack);
3449 } finally {
3450 Binder.restoreCallingIdentity(ident);
3451 }
3452 }
3453 }
3454
3455 @Override
3456 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003457 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003458
3459 synchronized (mGlobalLock) {
3460 final long ident = Binder.clearCallingIdentity();
3461 try {
3462 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3463 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003464 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003465 } finally {
3466 Binder.restoreCallingIdentity(ident);
3467 }
3468 }
3469 }
3470
3471 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003472 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003473 synchronized (mGlobalLock) {
3474 long ident = Binder.clearCallingIdentity();
3475 try {
3476 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3477 if (r == null) {
3478 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003479 "toggleFreeformWindowingMode: No activity record matching token="
3480 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003481 }
3482
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003483 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003484 if (stack == null) {
3485 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3486 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003487 }
3488
Yunfan Chend967af82019-01-17 18:30:18 +09003489 if (!stack.inFreeformWindowingMode()
3490 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3491 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3492 + "toggle between fullscreen and freeform.");
3493 }
3494
3495 if (stack.inFreeformWindowingMode()) {
3496 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003497 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003498 throw new IllegalStateException("Size-compat windows are currently not"
3499 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003500 } else if (stack.getParent().inFreeformWindowingMode()) {
3501 // If the window is on a freeform display, set it to undefined. It will be
3502 // resolved to freeform and it can adjust windowing mode when the display mode
3503 // changes in runtime.
3504 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003505 } else {
3506 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3507 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003508 } finally {
3509 Binder.restoreCallingIdentity(ident);
3510 }
3511 }
3512 }
3513
3514 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3515 @Override
3516 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003517 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003518 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003519 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003520 }
3521
3522 /** Unregister a task stack listener so that it stops receiving callbacks. */
3523 @Override
3524 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003525 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003526 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003527 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003528 }
3529
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003530 @Override
3531 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3532 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3533 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3534 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3535 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3536 }
3537
3538 @Override
3539 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3540 IBinder activityToken, int flags) {
3541 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3542 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3543 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3544 }
3545
3546 @Override
3547 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3548 Bundle args) {
3549 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3550 true /* focused */, true /* newSessionId */, userHandle, args,
3551 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3552 }
3553
3554 @Override
3555 public Bundle getAssistContextExtras(int requestType) {
3556 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3557 null, null, true /* focused */, true /* newSessionId */,
3558 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3559 if (pae == null) {
3560 return null;
3561 }
3562 synchronized (pae) {
3563 while (!pae.haveResult) {
3564 try {
3565 pae.wait();
3566 } catch (InterruptedException e) {
3567 }
3568 }
3569 }
3570 synchronized (mGlobalLock) {
3571 buildAssistBundleLocked(pae, pae.result);
3572 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003573 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003574 }
3575 return pae.extras;
3576 }
3577
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003578 /**
3579 * Binder IPC calls go through the public entry point.
3580 * This can be called with or without the global lock held.
3581 */
3582 private static int checkCallingPermission(String permission) {
3583 return checkPermission(
3584 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3585 }
3586
3587 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003588 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003589 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3590 mAmInternal.enforceCallingPermission(permission, func);
3591 }
3592 }
3593
3594 @VisibleForTesting
3595 int checkGetTasksPermission(String permission, int pid, int uid) {
3596 return checkPermission(permission, pid, uid);
3597 }
3598
3599 static int checkPermission(String permission, int pid, int uid) {
3600 if (permission == null) {
3601 return PackageManager.PERMISSION_DENIED;
3602 }
3603 return checkComponentPermission(permission, pid, uid, -1, true);
3604 }
3605
Wale Ogunwale214f3482018-10-04 11:00:47 -07003606 public static int checkComponentPermission(String permission, int pid, int uid,
3607 int owningUid, boolean exported) {
3608 return ActivityManagerService.checkComponentPermission(
3609 permission, pid, uid, owningUid, exported);
3610 }
3611
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003612 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3613 if (getRecentTasks().isCallerRecents(callingUid)) {
3614 // Always allow the recents component to get tasks
3615 return true;
3616 }
3617
3618 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3619 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3620 if (!allowed) {
3621 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3622 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3623 // Temporary compatibility: some existing apps on the system image may
3624 // still be requesting the old permission and not switched to the new
3625 // one; if so, we'll still allow them full access. This means we need
3626 // to see if they are holding the old permission and are a system app.
3627 try {
3628 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3629 allowed = true;
3630 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3631 + " is using old GET_TASKS but privileged; allowing");
3632 }
3633 } catch (RemoteException e) {
3634 }
3635 }
3636 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3637 + " does not hold REAL_GET_TASKS; limiting output");
3638 }
3639 return allowed;
3640 }
3641
Nicholas Sauer0259e532019-08-30 08:24:55 -07003642 boolean isCrossUserAllowed(int pid, int uid) {
3643 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3644 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3645 }
3646
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003647 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3648 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3649 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3650 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003651 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003652 "enqueueAssistContext()");
3653
3654 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003655 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003656 if (activity == null) {
3657 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3658 return null;
3659 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003660 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003661 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3662 return null;
3663 }
3664 if (focused) {
3665 if (activityToken != null) {
3666 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3667 if (activity != caller) {
3668 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3669 + " is not current top " + activity);
3670 return null;
3671 }
3672 }
3673 } else {
3674 activity = ActivityRecord.forTokenLocked(activityToken);
3675 if (activity == null) {
3676 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3677 + " couldn't be found");
3678 return null;
3679 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003680 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003681 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3682 return null;
3683 }
3684 }
3685
3686 PendingAssistExtras pae;
3687 Bundle extras = new Bundle();
3688 if (args != null) {
3689 extras.putAll(args);
3690 }
3691 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003692 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003693
3694 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3695 userHandle);
3696 pae.isHome = activity.isActivityTypeHome();
3697
3698 // Increment the sessionId if necessary
3699 if (newSessionId) {
3700 mViSessionId++;
3701 }
3702 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003703 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3704 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003705 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003706 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003707 } catch (RemoteException e) {
3708 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3709 return null;
3710 }
3711 return pae;
3712 }
3713 }
3714
3715 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3716 if (result != null) {
3717 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3718 }
3719 if (pae.hint != null) {
3720 pae.extras.putBoolean(pae.hint, true);
3721 }
3722 }
3723
3724 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3725 IAssistDataReceiver receiver;
3726 synchronized (mGlobalLock) {
3727 mPendingAssistExtras.remove(pae);
3728 receiver = pae.receiver;
3729 }
3730 if (receiver != null) {
3731 // Caller wants result sent back to them.
3732 Bundle sendBundle = new Bundle();
3733 // At least return the receiver extras
3734 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3735 try {
3736 pae.receiver.onHandleAssistData(sendBundle);
3737 } catch (RemoteException e) {
3738 }
3739 }
3740 }
3741
3742 public class PendingAssistExtras extends Binder implements Runnable {
3743 public final ActivityRecord activity;
3744 public boolean isHome;
3745 public final Bundle extras;
3746 public final Intent intent;
3747 public final String hint;
3748 public final IAssistDataReceiver receiver;
3749 public final int userHandle;
3750 public boolean haveResult = false;
3751 public Bundle result = null;
3752 public AssistStructure structure = null;
3753 public AssistContent content = null;
3754 public Bundle receiverExtras;
3755
3756 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3757 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3758 int _userHandle) {
3759 activity = _activity;
3760 extras = _extras;
3761 intent = _intent;
3762 hint = _hint;
3763 receiver = _receiver;
3764 receiverExtras = _receiverExtras;
3765 userHandle = _userHandle;
3766 }
3767
3768 @Override
3769 public void run() {
3770 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3771 synchronized (this) {
3772 haveResult = true;
3773 notifyAll();
3774 }
3775 pendingAssistExtrasTimedOut(this);
3776 }
3777 }
3778
3779 @Override
3780 public boolean isAssistDataAllowedOnCurrentActivity() {
3781 int userId;
3782 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003783 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003784 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3785 return false;
3786 }
3787
Wale Ogunwale21e06482019-11-18 05:14:15 -08003788 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003789 if (activity == null) {
3790 return false;
3791 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003792 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003793 }
3794 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3795 }
3796
3797 @Override
3798 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3799 long ident = Binder.clearCallingIdentity();
3800 try {
3801 synchronized (mGlobalLock) {
3802 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003803 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003804 if (top != caller) {
3805 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3806 + " is not current top " + top);
3807 return false;
3808 }
3809 if (!top.nowVisible) {
3810 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3811 + " is not visible");
3812 return false;
3813 }
3814 }
3815 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3816 token);
3817 } finally {
3818 Binder.restoreCallingIdentity(ident);
3819 }
3820 }
3821
3822 @Override
3823 public boolean isRootVoiceInteraction(IBinder token) {
3824 synchronized (mGlobalLock) {
3825 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3826 if (r == null) {
3827 return false;
3828 }
3829 return r.rootVoiceInteraction;
3830 }
3831 }
3832
Wale Ogunwalef6733932018-06-27 05:14:34 -07003833 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3834 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3835 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3836 if (activityToCallback == null) return;
3837 activityToCallback.setVoiceSessionLocked(voiceSession);
3838
3839 // Inform the activity
3840 try {
3841 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3842 voiceInteractor);
3843 long token = Binder.clearCallingIdentity();
3844 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003845 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003846 } finally {
3847 Binder.restoreCallingIdentity(token);
3848 }
3849 // TODO: VI Should we cache the activity so that it's easier to find later
3850 // rather than scan through all the stacks and activities?
3851 } catch (RemoteException re) {
3852 activityToCallback.clearVoiceSessionLocked();
3853 // TODO: VI Should this terminate the voice session?
3854 }
3855 }
3856
3857 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3858 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3859 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3860 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3861 boolean wasRunningVoice = mRunningVoice != null;
3862 mRunningVoice = session;
3863 if (!wasRunningVoice) {
3864 mVoiceWakeLock.acquire();
3865 updateSleepIfNeededLocked();
3866 }
3867 }
3868 }
3869
3870 void finishRunningVoiceLocked() {
3871 if (mRunningVoice != null) {
3872 mRunningVoice = null;
3873 mVoiceWakeLock.release();
3874 updateSleepIfNeededLocked();
3875 }
3876 }
3877
3878 @Override
3879 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3880 synchronized (mGlobalLock) {
3881 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3882 if (keepAwake) {
3883 mVoiceWakeLock.acquire();
3884 } else {
3885 mVoiceWakeLock.release();
3886 }
3887 }
3888 }
3889 }
3890
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003891 @Override
3892 public ComponentName getActivityClassForToken(IBinder token) {
3893 synchronized (mGlobalLock) {
3894 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3895 if (r == null) {
3896 return null;
3897 }
3898 return r.intent.getComponent();
3899 }
3900 }
3901
3902 @Override
3903 public String getPackageForToken(IBinder token) {
3904 synchronized (mGlobalLock) {
3905 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3906 if (r == null) {
3907 return null;
3908 }
3909 return r.packageName;
3910 }
3911 }
3912
3913 @Override
3914 public void showLockTaskEscapeMessage(IBinder token) {
3915 synchronized (mGlobalLock) {
3916 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3917 if (r == null) {
3918 return;
3919 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003920 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003921 }
3922 }
3923
3924 @Override
3925 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003926 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003927 final long token = Binder.clearCallingIdentity();
3928 try {
3929 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003930 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003931 }
3932 } finally {
3933 Binder.restoreCallingIdentity(token);
3934 }
3935 }
3936
3937 /**
3938 * Try to place task to provided position. The final position might be different depending on
3939 * current user and stacks state. The task will be moved to target stack if it's currently in
3940 * different stack.
3941 */
3942 @Override
3943 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003944 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003945 synchronized (mGlobalLock) {
3946 long ident = Binder.clearCallingIdentity();
3947 try {
3948 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3949 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Changcdec0802019-11-11 11:45:07 +08003950 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003951 if (task == null) {
3952 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3953 + taskId);
3954 }
3955
Wale Ogunwaled32da472018-11-16 07:19:28 -08003956 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003957
3958 if (stack == null) {
3959 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3960 + stackId);
3961 }
3962 if (!stack.isActivityTypeStandardOrUndefined()) {
3963 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3964 + " the position of task " + taskId + " in/to non-standard stack");
3965 }
3966
3967 // TODO: Have the callers of this API call a separate reparent method if that is
3968 // what they intended to do vs. having this method also do reparenting.
3969 if (task.getStack() == stack) {
3970 // Change position in current stack.
3971 stack.positionChildAt(task, position);
3972 } else {
3973 // Reparent to new stack.
3974 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3975 !DEFER_RESUME, "positionTaskInStack");
3976 }
3977 } finally {
3978 Binder.restoreCallingIdentity(ident);
3979 }
3980 }
3981 }
3982
3983 @Override
3984 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3985 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3986 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003987 + Arrays.toString(horizontalSizeConfiguration) + " "
3988 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003989 synchronized (mGlobalLock) {
3990 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3991 if (record == null) {
3992 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3993 + "found for: " + token);
3994 }
3995 record.setSizeConfigurations(horizontalSizeConfiguration,
3996 verticalSizeConfigurations, smallestSizeConfigurations);
3997 }
3998 }
3999
4000 /**
4001 * Dismisses split-screen multi-window mode.
4002 * @param toTop If true the current primary split-screen stack will be placed or left on top.
4003 */
4004 @Override
4005 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004006 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004007 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
4008 final long ident = Binder.clearCallingIdentity();
4009 try {
4010 synchronized (mGlobalLock) {
4011 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08004012 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004013 if (stack == null) {
4014 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
4015 return;
4016 }
4017
4018 if (toTop) {
4019 // Caller wants the current split-screen primary stack to be the top stack after
4020 // it goes fullscreen, so move it to the front.
4021 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004022 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004023 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004024 // stack after it goes fullscreen, so we move the focus to the top-most
4025 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004026 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
4027 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
4028 if (otherStack != null) {
4029 otherStack.moveToFront("dismissSplitScreenMode_other");
4030 }
4031 }
4032
Evan Rosky10475742018-09-05 19:02:48 -07004033 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004034 }
4035 } finally {
4036 Binder.restoreCallingIdentity(ident);
4037 }
4038 }
4039
4040 /**
4041 * Dismisses Pip
4042 * @param animate True if the dismissal should be animated.
4043 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4044 * default animation duration should be used.
4045 */
4046 @Override
4047 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004048 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004049 final long ident = Binder.clearCallingIdentity();
4050 try {
4051 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004052 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08004053 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004054 if (stack == null) {
4055 Slog.w(TAG, "dismissPip: pinned stack not found.");
4056 return;
4057 }
4058 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4059 throw new IllegalArgumentException("Stack: " + stack
4060 + " doesn't support animated resize.");
4061 }
4062 if (animate) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004063 stack.animateResizePinnedStack(null /* destBounds */,
4064 null /* sourceHintBounds */, animationDuration,
4065 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004066 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004067 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004068 }
4069 }
4070 } finally {
4071 Binder.restoreCallingIdentity(ident);
4072 }
4073 }
4074
4075 @Override
4076 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004077 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004078 synchronized (mGlobalLock) {
4079 mSuppressResizeConfigChanges = suppress;
4080 }
4081 }
4082
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004083 @Override
4084 // TODO: API should just be about changing windowing modes...
4085 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004086 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004087 "moveTasksToFullscreenStack()");
4088 synchronized (mGlobalLock) {
4089 final long origId = Binder.clearCallingIdentity();
4090 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004091 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004092 if (stack != null){
4093 if (!stack.isActivityTypeStandardOrUndefined()) {
4094 throw new IllegalArgumentException(
4095 "You can't move tasks from non-standard stacks.");
4096 }
4097 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4098 }
4099 } finally {
4100 Binder.restoreCallingIdentity(origId);
4101 }
4102 }
4103 }
4104
4105 /**
4106 * Moves the top activity in the input stackId to the pinned stack.
4107 *
4108 * @param stackId Id of stack to move the top activity to pinned stack.
4109 * @param bounds Bounds to use for pinned stack.
4110 *
4111 * @return True if the top activity of the input stack was successfully moved to the pinned
4112 * stack.
4113 */
4114 @Override
4115 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004116 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004117 "moveTopActivityToPinnedStack()");
4118 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004119 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004120 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4121 + "Device doesn't support picture-in-picture mode");
4122 }
4123
4124 long ident = Binder.clearCallingIdentity();
4125 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004126 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004127 } finally {
4128 Binder.restoreCallingIdentity(ident);
4129 }
4130 }
4131 }
4132
4133 @Override
4134 public boolean isInMultiWindowMode(IBinder token) {
4135 final long origId = Binder.clearCallingIdentity();
4136 try {
4137 synchronized (mGlobalLock) {
4138 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4139 if (r == null) {
4140 return false;
4141 }
4142 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4143 return r.inMultiWindowMode();
4144 }
4145 } finally {
4146 Binder.restoreCallingIdentity(origId);
4147 }
4148 }
4149
4150 @Override
4151 public boolean isInPictureInPictureMode(IBinder token) {
4152 final long origId = Binder.clearCallingIdentity();
4153 try {
4154 synchronized (mGlobalLock) {
4155 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4156 }
4157 } finally {
4158 Binder.restoreCallingIdentity(origId);
4159 }
4160 }
4161
4162 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004163 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4164 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004165 return false;
4166 }
4167
4168 // If we are animating to fullscreen then we have already dispatched the PIP mode
4169 // changed, so we should reflect that check here as well.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004170 final ActivityStack taskStack = r.getActivityStack();
Yunfan Chen279f5582018-12-12 15:24:50 -08004171 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004172 }
4173
4174 @Override
4175 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4176 final long origId = Binder.clearCallingIdentity();
4177 try {
4178 synchronized (mGlobalLock) {
4179 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4180 "enterPictureInPictureMode", token, params);
4181
4182 // If the activity is already in picture in picture mode, then just return early
4183 if (isInPictureInPictureMode(r)) {
4184 return true;
4185 }
4186
4187 // Activity supports picture-in-picture, now check that we can enter PiP at this
4188 // point, if it is
4189 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4190 false /* beforeStopping */)) {
4191 return false;
4192 }
4193
4194 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004195 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004196 if (r.getParent() == null) {
4197 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4198 return;
4199 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004200 // Only update the saved args from the args that are set
4201 r.pictureInPictureArgs.copyOnlySet(params);
4202 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4203 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4204 // Adjust the source bounds by the insets for the transition down
4205 final Rect sourceBounds = new Rect(
4206 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004207 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004208 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004209 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004210 stack.setPictureInPictureAspectRatio(aspectRatio);
4211 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004212 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4213 r.info.applicationInfo.uid, r.shortComponentName,
4214 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004215 logPictureInPictureArgs(params);
4216 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004217 };
4218
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004219 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004220 // If the keyguard is showing or occluded, then try and dismiss it before
4221 // entering picture-in-picture (this will prompt the user to authenticate if the
4222 // device is currently locked).
4223 dismissKeyguard(token, new KeyguardDismissCallback() {
4224 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004225 public void onDismissSucceeded() {
4226 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004227 }
4228 }, null /* message */);
4229 } else {
4230 // Enter picture in picture immediately otherwise
4231 enterPipRunnable.run();
4232 }
4233 return true;
4234 }
4235 } finally {
4236 Binder.restoreCallingIdentity(origId);
4237 }
4238 }
4239
4240 @Override
4241 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4242 final long origId = Binder.clearCallingIdentity();
4243 try {
4244 synchronized (mGlobalLock) {
4245 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4246 "setPictureInPictureParams", token, params);
4247
4248 // Only update the saved args from the args that are set
4249 r.pictureInPictureArgs.copyOnlySet(params);
4250 if (r.inPinnedWindowingMode()) {
4251 // If the activity is already in picture-in-picture, update the pinned stack now
4252 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4253 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004254 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004255 if (!stack.isAnimatingBoundsToFullscreen()) {
4256 stack.setPictureInPictureAspectRatio(
4257 r.pictureInPictureArgs.getAspectRatio());
4258 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4259 }
4260 }
4261 logPictureInPictureArgs(params);
4262 }
4263 } finally {
4264 Binder.restoreCallingIdentity(origId);
4265 }
4266 }
4267
4268 @Override
4269 public int getMaxNumPictureInPictureActions(IBinder token) {
4270 // Currently, this is a static constant, but later, we may change this to be dependent on
4271 // the context of the activity
4272 return 3;
4273 }
4274
4275 private void logPictureInPictureArgs(PictureInPictureParams params) {
4276 if (params.hasSetActions()) {
4277 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4278 params.getActions().size());
4279 }
4280 if (params.hasSetAspectRatio()) {
4281 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4282 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4283 MetricsLogger.action(lm);
4284 }
4285 }
4286
4287 /**
4288 * Checks the state of the system and the activity associated with the given {@param token} to
4289 * verify that picture-in-picture is supported for that activity.
4290 *
4291 * @return the activity record for the given {@param token} if all the checks pass.
4292 */
4293 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4294 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004295 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004296 throw new IllegalStateException(caller
4297 + ": Device doesn't support picture-in-picture mode.");
4298 }
4299
4300 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4301 if (r == null) {
4302 throw new IllegalStateException(caller
4303 + ": Can't find activity for token=" + token);
4304 }
4305
4306 if (!r.supportsPictureInPicture()) {
4307 throw new IllegalStateException(caller
4308 + ": Current activity does not support picture-in-picture.");
4309 }
4310
4311 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004312 && !mWindowManager.isValidPictureInPictureAspectRatio(
4313 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004314 final float minAspectRatio = mContext.getResources().getFloat(
4315 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4316 final float maxAspectRatio = mContext.getResources().getFloat(
4317 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4318 throw new IllegalArgumentException(String.format(caller
4319 + ": Aspect ratio is too extreme (must be between %f and %f).",
4320 minAspectRatio, maxAspectRatio));
4321 }
4322
4323 // Truncate the number of actions if necessary
4324 params.truncateActions(getMaxNumPictureInPictureActions(token));
4325
4326 return r;
4327 }
4328
4329 @Override
4330 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004331 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004332 synchronized (mGlobalLock) {
4333 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4334 if (r == null) {
4335 throw new IllegalArgumentException("Activity does not exist; token="
4336 + activityToken);
4337 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004338 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004339 }
4340 }
4341
4342 @Override
4343 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4344 Rect tempDockedTaskInsetBounds,
4345 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004346 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004347 long ident = Binder.clearCallingIdentity();
4348 try {
4349 synchronized (mGlobalLock) {
4350 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4351 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4352 PRESERVE_WINDOWS);
4353 }
4354 } finally {
4355 Binder.restoreCallingIdentity(ident);
4356 }
4357 }
4358
4359 @Override
4360 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004361 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004362 final long ident = Binder.clearCallingIdentity();
4363 try {
4364 synchronized (mGlobalLock) {
4365 mStackSupervisor.setSplitScreenResizing(resizing);
4366 }
4367 } finally {
4368 Binder.restoreCallingIdentity(ident);
4369 }
4370 }
4371
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004372 /**
4373 * Check that we have the features required for VR-related API calls, and throw an exception if
4374 * not.
4375 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004376 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004377 if (!mContext.getPackageManager().hasSystemFeature(
4378 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4379 throw new UnsupportedOperationException("VR mode not supported on this device!");
4380 }
4381 }
4382
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004383 @Override
4384 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004385 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386
4387 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4388
4389 ActivityRecord r;
4390 synchronized (mGlobalLock) {
4391 r = ActivityRecord.isInStackLocked(token);
4392 }
4393
4394 if (r == null) {
4395 throw new IllegalArgumentException();
4396 }
4397
4398 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004399 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004400 VrManagerInternal.NO_ERROR) {
4401 return err;
4402 }
4403
4404 // Clear the binder calling uid since this path may call moveToTask().
4405 final long callingId = Binder.clearCallingIdentity();
4406 try {
4407 synchronized (mGlobalLock) {
4408 r.requestedVrComponent = (enabled) ? packageName : null;
4409
4410 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004411 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004412 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004413 }
4414 return 0;
4415 }
4416 } finally {
4417 Binder.restoreCallingIdentity(callingId);
4418 }
4419 }
4420
4421 @Override
4422 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4423 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4424 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004425 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004426 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4427 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4428 }
Louis Changcdec0802019-11-11 11:45:07 +08004429 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004430 || activity.voiceSession != null) {
4431 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4432 return;
4433 }
4434 if (activity.pendingVoiceInteractionStart) {
4435 Slog.w(TAG, "Pending start of voice interaction already.");
4436 return;
4437 }
4438 activity.pendingVoiceInteractionStart = true;
4439 }
4440 LocalServices.getService(VoiceInteractionManagerInternal.class)
4441 .startLocalVoiceInteraction(callingActivity, options);
4442 }
4443
4444 @Override
4445 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4446 LocalServices.getService(VoiceInteractionManagerInternal.class)
4447 .stopLocalVoiceInteraction(callingActivity);
4448 }
4449
4450 @Override
4451 public boolean supportsLocalVoiceInteraction() {
4452 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4453 .supportsLocalVoiceInteraction();
4454 }
4455
4456 /** Notifies all listeners when the pinned stack animation starts. */
4457 @Override
4458 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004459 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004460 }
4461
4462 /** Notifies all listeners when the pinned stack animation ends. */
4463 @Override
4464 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004465 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004466 }
4467
4468 @Override
4469 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004470 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004471 final long ident = Binder.clearCallingIdentity();
4472 try {
4473 synchronized (mGlobalLock) {
4474 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4475 }
4476 } finally {
4477 Binder.restoreCallingIdentity(ident);
4478 }
4479 }
4480
4481 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004482 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004483 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004484
4485 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004486 if (mWindowManager == null) {
4487 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4488 return false;
4489 }
4490
4491 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004492 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004493 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004494 }
4495
Riddle Hsua0022cd2019-09-09 21:12:41 +08004496 mH.sendMessage(PooledLambda.obtainMessage(
4497 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4498 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004499
4500 final long origId = Binder.clearCallingIdentity();
4501 try {
4502 if (values != null) {
4503 Settings.System.clearConfiguration(values);
4504 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004505 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004506 UserHandle.USER_NULL, false /* deferResume */,
4507 mTmpUpdateConfigurationResult);
4508 return mTmpUpdateConfigurationResult.changes != 0;
4509 } finally {
4510 Binder.restoreCallingIdentity(origId);
4511 }
4512 }
4513 }
4514
4515 @Override
4516 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4517 CharSequence message) {
4518 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004519 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004520 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4521 }
4522 final long callingId = Binder.clearCallingIdentity();
4523 try {
4524 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004525 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004526 }
4527 } finally {
4528 Binder.restoreCallingIdentity(callingId);
4529 }
4530 }
4531
4532 @Override
4533 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004534 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004535 "cancelTaskWindowTransition()");
4536 final long ident = Binder.clearCallingIdentity();
4537 try {
4538 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08004539 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004540 MATCH_TASK_IN_STACKS_ONLY);
4541 if (task == null) {
4542 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4543 return;
4544 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004545 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004546 }
4547 } finally {
4548 Binder.restoreCallingIdentity(ident);
4549 }
4550 }
4551
4552 @Override
4553 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004554 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004555 final long ident = Binder.clearCallingIdentity();
4556 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004557 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004558 } finally {
4559 Binder.restoreCallingIdentity(ident);
4560 }
4561 }
4562
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004563 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4564 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004565 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004566 synchronized (mGlobalLock) {
4567 task = mRootActivityContainer.anyTaskForId(taskId,
4568 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4569 if (task == null) {
4570 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4571 return null;
4572 }
4573 }
4574 // Don't call this while holding the lock as this operation might hit the disk.
4575 return task.getSnapshot(reducedResolution, restoreFromDisk);
4576 }
4577
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004578 @Override
4579 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4580 synchronized (mGlobalLock) {
4581 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4582 if (r == null) {
4583 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4584 + token);
4585 return;
4586 }
4587 final long origId = Binder.clearCallingIdentity();
4588 try {
4589 r.setDisablePreviewScreenshots(disable);
4590 } finally {
4591 Binder.restoreCallingIdentity(origId);
4592 }
4593 }
4594 }
4595
Riddle Hsu440f88b2019-11-06 22:17:35 +08004596 @Override
4597 public void invalidateHomeTaskSnapshot(IBinder token) {
4598 synchronized (mGlobalLock) {
4599 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4600 if (r == null || !r.isActivityTypeHome()) {
4601 return;
4602 }
4603 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4604 }
4605 }
4606
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004607 /** Return the user id of the last resumed activity. */
4608 @Override
4609 public @UserIdInt
4610 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004611 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004612 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4613 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004614 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004615 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004616 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004617 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004618 }
4619 }
4620
4621 @Override
4622 public void updateLockTaskFeatures(int userId, int flags) {
4623 final int callingUid = Binder.getCallingUid();
4624 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004625 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004626 "updateLockTaskFeatures()");
4627 }
4628 synchronized (mGlobalLock) {
4629 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4630 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004631 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004632 }
4633 }
4634
4635 @Override
4636 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4637 synchronized (mGlobalLock) {
4638 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4639 if (r == null) {
4640 return;
4641 }
4642 final long origId = Binder.clearCallingIdentity();
4643 try {
4644 r.setShowWhenLocked(showWhenLocked);
4645 } finally {
4646 Binder.restoreCallingIdentity(origId);
4647 }
4648 }
4649 }
4650
4651 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004652 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4653 synchronized (mGlobalLock) {
4654 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4655 if (r == null) {
4656 return;
4657 }
4658 final long origId = Binder.clearCallingIdentity();
4659 try {
4660 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4661 } finally {
4662 Binder.restoreCallingIdentity(origId);
4663 }
4664 }
4665 }
4666
4667 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004668 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4669 synchronized (mGlobalLock) {
4670 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4671 if (r == null) {
4672 return;
4673 }
4674 final long origId = Binder.clearCallingIdentity();
4675 try {
4676 r.setTurnScreenOn(turnScreenOn);
4677 } finally {
4678 Binder.restoreCallingIdentity(origId);
4679 }
4680 }
4681 }
4682
4683 @Override
4684 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004685 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004686 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004687 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004688 synchronized (mGlobalLock) {
4689 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4690 if (r == null) {
4691 return;
4692 }
4693 final long origId = Binder.clearCallingIdentity();
4694 try {
4695 r.registerRemoteAnimations(definition);
4696 } finally {
4697 Binder.restoreCallingIdentity(origId);
4698 }
4699 }
4700 }
4701
4702 @Override
4703 public void registerRemoteAnimationForNextActivityStart(String packageName,
4704 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004705 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004706 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004707 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004708 synchronized (mGlobalLock) {
4709 final long origId = Binder.clearCallingIdentity();
4710 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004711 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004712 packageName, adapter);
4713 } finally {
4714 Binder.restoreCallingIdentity(origId);
4715 }
4716 }
4717 }
4718
Evan Rosky966759f2019-01-15 10:33:58 -08004719 @Override
4720 public void registerRemoteAnimationsForDisplay(int displayId,
4721 RemoteAnimationDefinition definition) {
4722 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4723 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004724 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004725 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08004726 final DisplayContent display = mRootActivityContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004727 if (display == null) {
4728 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4729 return;
4730 }
4731 final long origId = Binder.clearCallingIdentity();
4732 try {
4733 display.mDisplayContent.registerRemoteAnimations(definition);
4734 } finally {
4735 Binder.restoreCallingIdentity(origId);
4736 }
4737 }
4738 }
4739
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004740 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4741 @Override
4742 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4743 synchronized (mGlobalLock) {
4744 final long origId = Binder.clearCallingIdentity();
4745 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004746 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004747 } finally {
4748 Binder.restoreCallingIdentity(origId);
4749 }
4750 }
4751 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004752
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004753 @Override
4754 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004755 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004756 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004757 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004758 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004759 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004760 }
4761 }
4762
4763 @Override
4764 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004765 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004766 != PERMISSION_GRANTED) {
4767 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4768 + Binder.getCallingPid()
4769 + ", uid=" + Binder.getCallingUid()
4770 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4771 Slog.w(TAG, msg);
4772 throw new SecurityException(msg);
4773 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004774 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004775 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004776 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004777 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004778 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004779 }
4780 }
4781
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004782 @Override
4783 public void stopAppSwitches() {
4784 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4785 synchronized (mGlobalLock) {
4786 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004787 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004788 mDidAppSwitch = false;
4789 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4790 }
4791 }
4792
4793 @Override
4794 public void resumeAppSwitches() {
4795 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4796 synchronized (mGlobalLock) {
4797 // Note that we don't execute any pending app switches... we will
4798 // let those wait until either the timeout, or the next start
4799 // activity request.
4800 mAppSwitchesAllowedTime = 0;
4801 }
4802 }
4803
Ricky Wai906af482019-06-03 17:25:28 +01004804 long getLastStopAppSwitchesTime() {
4805 return mLastStopAppSwitchesTime;
4806 }
4807
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004808 void onStartActivitySetDidAppSwitch() {
4809 if (mDidAppSwitch) {
4810 // This is the second allowed switch since we stopped switches, so now just generally
4811 // allow switches. Use case:
4812 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4813 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4814 // anyone to switch again).
4815 mAppSwitchesAllowedTime = 0;
4816 } else {
4817 mDidAppSwitch = true;
4818 }
4819 }
4820
4821 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004822 boolean shouldDisableNonVrUiLocked() {
4823 return mVrController.shouldDisableNonVrUiLocked();
4824 }
4825
Wale Ogunwale53783742018-09-16 10:21:51 -07004826 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004827 // 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 +00004828 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004829 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004830 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4831 + " to main display for VR");
4832 mRootActivityContainer.moveStackToDisplay(
4833 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004834 }
4835 mH.post(() -> {
4836 if (!mVrController.onVrModeChanged(r)) {
4837 return;
4838 }
4839 synchronized (mGlobalLock) {
4840 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4841 mWindowManager.disableNonVrUi(disableNonVrUi);
4842 if (disableNonVrUi) {
4843 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4844 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004845 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004846 }
4847 }
4848 });
4849 }
4850
Wale Ogunwale53783742018-09-16 10:21:51 -07004851 @Override
4852 public int getPackageScreenCompatMode(String packageName) {
4853 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4854 synchronized (mGlobalLock) {
4855 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4856 }
4857 }
4858
4859 @Override
4860 public void setPackageScreenCompatMode(String packageName, int mode) {
4861 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4862 "setPackageScreenCompatMode");
4863 synchronized (mGlobalLock) {
4864 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4865 }
4866 }
4867
4868 @Override
4869 public boolean getPackageAskScreenCompat(String packageName) {
4870 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4871 synchronized (mGlobalLock) {
4872 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4873 }
4874 }
4875
4876 @Override
4877 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4878 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4879 "setPackageAskScreenCompat");
4880 synchronized (mGlobalLock) {
4881 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4882 }
4883 }
4884
Wale Ogunwale64258362018-10-16 15:13:37 -07004885 public static String relaunchReasonToString(int relaunchReason) {
4886 switch (relaunchReason) {
4887 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4888 return "window_resize";
4889 case RELAUNCH_REASON_FREE_RESIZE:
4890 return "free_resize";
4891 default:
4892 return null;
4893 }
4894 }
4895
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004896 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004897 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004898 }
4899
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004900 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004901 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004902 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4903 }
4904
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004905 boolean isKeyguardLocked() {
4906 return mKeyguardController.isKeyguardLocked();
4907 }
4908
Garfield Tan01548632018-11-27 10:15:48 -08004909 /**
4910 * Clears launch params for the given package.
4911 * @param packageNames the names of the packages of which the launch params are to be cleared
4912 */
4913 @Override
4914 public void clearLaunchParamsForPackages(List<String> packageNames) {
4915 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4916 "clearLaunchParamsForPackages");
4917 synchronized (mGlobalLock) {
4918 for (int i = 0; i < packageNames.size(); ++i) {
4919 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4920 }
4921 }
4922 }
4923
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004924 /**
4925 * Makes the display with the given id a single task instance display. I.e the display can only
4926 * contain one task.
4927 */
4928 @Override
4929 public void setDisplayToSingleTaskInstance(int displayId) {
4930 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4931 "setDisplayToSingleTaskInstance");
4932 final long origId = Binder.clearCallingIdentity();
4933 try {
Louis Chang677921f2019-12-06 16:44:24 +08004934 final DisplayContent display =
4935 mRootActivityContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004936 if (display != null) {
4937 display.setDisplayToSingleTaskInstance();
4938 }
4939 } finally {
4940 Binder.restoreCallingIdentity(origId);
4941 }
4942 }
4943
Wale Ogunwale31913b52018-10-13 08:29:31 -07004944 void dumpLastANRLocked(PrintWriter pw) {
4945 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4946 if (mLastANRState == null) {
4947 pw.println(" <no ANR has occurred since boot>");
4948 } else {
4949 pw.println(mLastANRState);
4950 }
4951 }
4952
4953 void dumpLastANRTracesLocked(PrintWriter pw) {
4954 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4955
4956 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4957 if (ArrayUtils.isEmpty(files)) {
4958 pw.println(" <no ANR has occurred since boot>");
4959 return;
4960 }
4961 // Find the latest file.
4962 File latest = null;
4963 for (File f : files) {
4964 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4965 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004966 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004967 }
4968 pw.print("File: ");
4969 pw.print(latest.getName());
4970 pw.println();
4971 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4972 String line;
4973 while ((line = in.readLine()) != null) {
4974 pw.println(line);
4975 }
4976 } catch (IOException e) {
4977 pw.print("Unable to read: ");
4978 pw.print(e);
4979 pw.println();
4980 }
4981 }
4982
4983 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4984 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4985 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4986 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4987 }
4988
4989 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4990 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4991 pw.println(header);
4992
Wale Ogunwaled32da472018-11-16 07:19:28 -08004993 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004994 dumpPackage);
4995 boolean needSep = printedAnything;
4996
4997 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004998 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004999 " ResumedActivity: ");
5000 if (printed) {
5001 printedAnything = true;
5002 needSep = false;
5003 }
5004
5005 if (dumpPackage == null) {
5006 if (needSep) {
5007 pw.println();
5008 }
5009 printedAnything = true;
5010 mStackSupervisor.dump(pw, " ");
5011 }
5012
5013 if (!printedAnything) {
5014 pw.println(" (nothing)");
5015 }
5016 }
5017
5018 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005019 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08005020 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005021 pw.println(" ");
5022 }
5023
5024 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5025 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5026 getActivityStartController().dump(pw, "", dumpPackage);
5027 }
5028
5029 /**
5030 * There are three things that cmd can be:
5031 * - a flattened component name that matches an existing activity
5032 * - the cmd arg isn't the flattened component name of an existing activity:
5033 * dump all activity whose component contains the cmd as a substring
5034 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005035 * <p>
5036 * The caller should not hold lock when calling this method because it will wait for the
5037 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005038 *
5039 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5040 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5041 */
5042 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5043 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5044 ArrayList<ActivityRecord> activities;
5045
5046 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005047 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005048 dumpFocusedStackOnly);
5049 }
5050
5051 if (activities.size() <= 0) {
5052 return false;
5053 }
5054
5055 String[] newArgs = new String[args.length - opti];
5056 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5057
Louis Changcdec0802019-11-11 11:45:07 +08005058 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005059 boolean needSep = false;
5060 for (int i = activities.size() - 1; i >= 0; i--) {
5061 ActivityRecord r = activities.get(i);
5062 if (needSep) {
5063 pw.println();
5064 }
5065 needSep = true;
5066 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005067 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005068 if (lastTask != task) {
5069 lastTask = task;
5070 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005071 pw.print(" id="); pw.print(lastTask.mTaskId);
5072 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005073 if (dumpAll) {
5074 lastTask.dump(pw, " ");
5075 }
5076 }
5077 }
5078 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5079 }
5080 return true;
5081 }
5082
5083 /**
5084 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5085 * there is a thread associated with the activity.
5086 */
5087 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5088 final ActivityRecord r, String[] args, boolean dumpAll) {
5089 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005090 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005091 synchronized (mGlobalLock) {
5092 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5093 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5094 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005095 if (r.hasProcess()) {
5096 pw.println(r.app.getPid());
5097 appThread = r.app.getThread();
5098 } else {
5099 pw.println("(not running)");
5100 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005101 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005102 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005103 }
5104 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005105 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005106 // flush anything that is already in the PrintWriter since the thread is going
5107 // to write to the file descriptor directly
5108 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005109 try (TransferPipe tp = new TransferPipe()) {
5110 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5111 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005112 } catch (IOException e) {
5113 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5114 } catch (RemoteException e) {
5115 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5116 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005117 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005118 }
5119
sanryhuang498e77e2018-12-06 14:57:01 +08005120 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5121 boolean testPssMode) {
5122 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5123 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5124 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005125 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005126 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5127 st.toString());
5128 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005129 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5130 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5131 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005132 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5133 testPssMode);
5134 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005135 }
5136
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005137 int getCurrentUserId() {
5138 return mAmInternal.getCurrentUserId();
5139 }
5140
5141 private void enforceNotIsolatedCaller(String caller) {
5142 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5143 throw new SecurityException("Isolated process not allowed to call " + caller);
5144 }
5145 }
5146
Wale Ogunwalef6733932018-06-27 05:14:34 -07005147 public Configuration getConfiguration() {
5148 Configuration ci;
5149 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005150 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005151 ci.userSetLocale = false;
5152 }
5153 return ci;
5154 }
5155
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005156 /**
5157 * Current global configuration information. Contains general settings for the entire system,
5158 * also corresponds to the merged configuration of the default display.
5159 */
5160 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005161 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005162 }
5163
5164 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5165 boolean initLocale) {
5166 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5167 }
5168
5169 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5170 boolean initLocale, boolean deferResume) {
5171 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5172 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5173 UserHandle.USER_NULL, deferResume);
5174 }
5175
Wale Ogunwale59507092018-10-29 09:00:30 -07005176 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005177 final long origId = Binder.clearCallingIdentity();
5178 try {
5179 synchronized (mGlobalLock) {
5180 updateConfigurationLocked(values, null, false, true, userId,
5181 false /* deferResume */);
5182 }
5183 } finally {
5184 Binder.restoreCallingIdentity(origId);
5185 }
5186 }
5187
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005188 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5189 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5190 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5191 deferResume, null /* result */);
5192 }
5193
5194 /**
5195 * Do either or both things: (1) change the current configuration, and (2)
5196 * make sure the given activity is running with the (now) current
5197 * configuration. Returns true if the activity has been left running, or
5198 * false if <var>starting</var> is being destroyed to match the new
5199 * configuration.
5200 *
5201 * @param userId is only used when persistent parameter is set to true to persist configuration
5202 * for that particular user
5203 */
5204 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5205 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5206 ActivityTaskManagerService.UpdateConfigurationResult result) {
5207 int changes = 0;
5208 boolean kept = true;
5209
Riddle Hsua0022cd2019-09-09 21:12:41 +08005210 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005211 try {
5212 if (values != null) {
5213 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5214 deferResume);
5215 }
5216
5217 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5218 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005219 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005220 }
5221
5222 if (result != null) {
5223 result.changes = changes;
5224 result.activityRelaunched = !kept;
5225 }
5226 return kept;
5227 }
5228
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005229 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005230 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005231 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005232
Louis Chang677921f2019-12-06 16:44:24 +08005233 final DisplayContent defaultDisplay =
5234 mRootActivityContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005235
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005236 mTempConfig.setTo(getGlobalConfiguration());
5237 final int changes = mTempConfig.updateFrom(values);
5238 if (changes == 0) {
5239 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5240 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5241 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5242 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005243 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005244 return 0;
5245 }
5246
5247 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5248 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005249 writeConfigurationChanged(changes);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005250 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5251 values.colorMode,
5252 values.densityDpi,
5253 values.fontScale,
5254 values.hardKeyboardHidden,
5255 values.keyboard,
5256 values.keyboardHidden,
5257 values.mcc,
5258 values.mnc,
5259 values.navigation,
5260 values.navigationHidden,
5261 values.orientation,
5262 values.screenHeightDp,
5263 values.screenLayout,
5264 values.screenWidthDp,
5265 values.smallestScreenWidthDp,
5266 values.touchscreen,
5267 values.uiMode);
5268
5269
5270 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5271 final LocaleList locales = values.getLocales();
5272 int bestLocaleIndex = 0;
5273 if (locales.size() > 1) {
5274 if (mSupportedSystemLocales == null) {
5275 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5276 }
5277 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5278 }
5279 SystemProperties.set("persist.sys.locale",
5280 locales.get(bestLocaleIndex).toLanguageTag());
5281 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005282
5283 final Message m = PooledLambda.obtainMessage(
5284 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5285 locales.get(bestLocaleIndex));
5286 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005287 }
5288
Yunfan Chen75157d72018-07-27 14:47:21 +09005289 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005290
5291 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005292 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005293
5294 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5295 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005296 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005297
5298 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005299 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005300
5301 AttributeCache ac = AttributeCache.instance();
5302 if (ac != null) {
5303 ac.updateConfiguration(mTempConfig);
5304 }
5305
5306 // Make sure all resources in our process are updated right now, so that anyone who is going
5307 // to retrieve resource values after we return will be sure to get the new ones. This is
5308 // especially important during boot, where the first config change needs to guarantee all
5309 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005310 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005311
5312 // We need another copy of global config because we're scheduling some calls instead of
5313 // running them in place. We need to be sure that object we send will be handled unchanged.
5314 final Configuration configCopy = new Configuration(mTempConfig);
5315 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005316 final Message msg = PooledLambda.obtainMessage(
5317 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5318 this, userId, configCopy);
5319 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005320 }
5321
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005322 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5323 for (int i = pidMap.size() - 1; i >= 0; i--) {
5324 final int pid = pidMap.keyAt(i);
5325 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005326 if (DEBUG_CONFIGURATION) {
5327 Slog.v(TAG_CONFIGURATION, "Update process config of "
5328 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005329 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005330 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005331 }
5332
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005333 final Message msg = PooledLambda.obtainMessage(
5334 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5335 mAmInternal, changes, initLocale);
5336 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005337
5338 // Override configuration of the default display duplicates global config, so we need to
5339 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005340 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5341 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005342
5343 return changes;
5344 }
5345
Riddle Hsua0022cd2019-09-09 21:12:41 +08005346 /** @see WindowSurfacePlacer#deferLayout */
5347 void deferWindowLayout() {
5348 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5349 // Reset the reasons at the first entrance because we only care about the changes in the
5350 // deferred scope.
5351 mLayoutReasons = 0;
5352 }
5353
5354 mWindowManager.mWindowPlacerLocked.deferLayout();
5355 }
5356
5357 /** @see WindowSurfacePlacer#continueLayout */
5358 void continueWindowLayout() {
5359 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5360 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5361 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5362 }
5363 }
5364
5365 /**
5366 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5367 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5368 * defer count is gone.
5369 */
5370 void addWindowLayoutReasons(@LayoutReason int reasons) {
5371 mLayoutReasons |= reasons;
5372 }
5373
Wale Ogunwalef6733932018-06-27 05:14:34 -07005374 private void updateEventDispatchingLocked(boolean booted) {
5375 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5376 }
5377
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005378 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5379 final ContentResolver resolver = mContext.getContentResolver();
5380 Settings.System.putConfigurationForUser(resolver, config, userId);
5381 }
5382
5383 private void sendLocaleToMountDaemonMsg(Locale l) {
5384 try {
5385 IBinder service = ServiceManager.getService("mount");
5386 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5387 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5388 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5389 } catch (RemoteException e) {
5390 Log.e(TAG, "Error storing locale for decryption UI", e);
5391 }
5392 }
5393
Alison Cichowlas3e340502018-08-07 17:15:01 -04005394 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5395 mStartActivitySources.remove(permissionToken);
5396 mExpiredStartAsCallerTokens.add(permissionToken);
5397 }
5398
5399 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5400 mExpiredStartAsCallerTokens.remove(permissionToken);
5401 }
5402
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005403 boolean isActivityStartsLoggingEnabled() {
5404 return mAmInternal.isActivityStartsLoggingEnabled();
5405 }
5406
Michal Karpinski8596ded2018-11-14 14:43:48 +00005407 boolean isBackgroundActivityStartsEnabled() {
5408 return mAmInternal.isBackgroundActivityStartsEnabled();
5409 }
5410
Wale Ogunwalef6733932018-06-27 05:14:34 -07005411 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005412 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005413 mWindowManager.enableScreenAfterBoot();
5414
5415 synchronized (mGlobalLock) {
5416 updateEventDispatchingLocked(booted);
5417 }
5418 }
5419
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005420 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5421 if (r == null || !r.hasProcess()) {
5422 return KEY_DISPATCHING_TIMEOUT_MS;
5423 }
5424 return getInputDispatchingTimeoutLocked(r.app);
5425 }
5426
5427 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005428 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005429 }
5430
Wale Ogunwalef6733932018-06-27 05:14:34 -07005431 /**
5432 * Decide based on the configuration whether we should show the ANR,
5433 * crash, etc dialogs. The idea is that if there is no affordance to
5434 * press the on-screen buttons, or the user experience would be more
5435 * greatly impacted than the crash itself, we shouldn't show the dialog.
5436 *
5437 * A thought: SystemUI might also want to get told about this, the Power
5438 * dialog / global actions also might want different behaviors.
5439 */
5440 private void updateShouldShowDialogsLocked(Configuration config) {
5441 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5442 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5443 && config.navigation == Configuration.NAVIGATION_NONAV);
5444 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5445 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5446 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5447 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5448 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5449 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5450 HIDE_ERROR_DIALOGS, 0) != 0;
5451 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5452 }
5453
5454 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5455 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5456 FONT_SCALE, 1.0f, userId);
5457
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005458 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005459 if (getGlobalConfiguration().fontScale == scaleFactor) {
5460 return;
5461 }
5462
5463 final Configuration configuration
5464 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5465 configuration.fontScale = scaleFactor;
5466 updatePersistentConfiguration(configuration, userId);
5467 }
5468 }
5469
5470 // Actually is sleeping or shutting down or whatever else in the future
5471 // is an inactive state.
5472 boolean isSleepingOrShuttingDownLocked() {
5473 return isSleepingLocked() || mShuttingDown;
5474 }
5475
5476 boolean isSleepingLocked() {
5477 return mSleeping;
5478 }
5479
Riddle Hsu16567132018-08-16 21:37:47 +08005480 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005481 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005482 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005483 if (task.isActivityTypeStandard()) {
5484 if (mCurAppTimeTracker != r.appTimeTracker) {
5485 // We are switching app tracking. Complete the current one.
5486 if (mCurAppTimeTracker != null) {
5487 mCurAppTimeTracker.stop();
5488 mH.obtainMessage(
5489 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005490 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005491 mCurAppTimeTracker = null;
5492 }
5493 if (r.appTimeTracker != null) {
5494 mCurAppTimeTracker = r.appTimeTracker;
5495 startTimeTrackingFocusedActivityLocked();
5496 }
5497 } else {
5498 startTimeTrackingFocusedActivityLocked();
5499 }
5500 } else {
5501 r.appTimeTracker = null;
5502 }
5503 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5504 // TODO: Probably not, because we don't want to resume voice on switching
5505 // back to this activity
5506 if (task.voiceInteractor != null) {
5507 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5508 } else {
5509 finishRunningVoiceLocked();
5510
5511 if (mLastResumedActivity != null) {
5512 final IVoiceInteractionSession session;
5513
Louis Changcdec0802019-11-11 11:45:07 +08005514 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005515 if (lastResumedActivityTask != null
5516 && lastResumedActivityTask.voiceSession != null) {
5517 session = lastResumedActivityTask.voiceSession;
5518 } else {
5519 session = mLastResumedActivity.voiceSession;
5520 }
5521
5522 if (session != null) {
5523 // We had been in a voice interaction session, but now focused has
5524 // move to something different. Just finish the session, we can't
5525 // return to it and retain the proper state and synchronization with
5526 // the voice interaction service.
5527 finishVoiceTask(session);
5528 }
5529 }
5530 }
5531
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005532 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5533 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005534 }
5535 updateResumedAppTrace(r);
5536 mLastResumedActivity = r;
5537
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005538 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005539
5540 applyUpdateLockStateLocked(r);
5541 applyUpdateVrModeLocked(r);
5542
Jeff Changd136e772019-11-05 20:33:52 +08005543 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005544 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005545 r == null ? "NULL" : r.shortComponentName,
5546 reason);
5547 }
5548
5549 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5550 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005551 final ActivityTaskManagerInternal.SleepToken token =
5552 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005553 updateSleepIfNeededLocked();
5554 return token;
5555 }
5556 }
5557
5558 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005559 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005560 final boolean wasSleeping = mSleeping;
5561 boolean updateOomAdj = false;
5562
5563 if (!shouldSleep) {
5564 // If wasSleeping is true, we need to wake up activity manager state from when
5565 // we started sleeping. In either case, we need to apply the sleep tokens, which
5566 // will wake up stacks or put them to sleep as appropriate.
5567 if (wasSleeping) {
5568 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005569 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5570 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005571 startTimeTrackingFocusedActivityLocked();
5572 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005573 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005574 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5575 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005576 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005577 if (wasSleeping) {
5578 updateOomAdj = true;
5579 }
5580 } else if (!mSleeping && shouldSleep) {
5581 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005582 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5583 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005584 if (mCurAppTimeTracker != null) {
5585 mCurAppTimeTracker.stop();
5586 }
5587 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005588 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005589 mStackSupervisor.goingToSleepLocked();
5590 updateResumedAppTrace(null /* resumed */);
5591 updateOomAdj = true;
5592 }
5593 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005594 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005595 }
5596 }
5597
5598 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005599 mH.removeCallbacks(mUpdateOomAdjRunnable);
5600 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005601 }
5602
Wale Ogunwale53783742018-09-16 10:21:51 -07005603 void updateCpuStats() {
5604 mH.post(mAmInternal::updateCpuStats);
5605 }
5606
Hui Yu03d12402018-12-06 18:00:37 -08005607 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5608 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005609 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5610 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005611 mH.sendMessage(m);
5612 }
5613
Hui Yu03d12402018-12-06 18:00:37 -08005614 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005615 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005616 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005617 if (task != null) {
5618 final ActivityRecord rootActivity = task.getRootActivity();
5619 if (rootActivity != null) {
5620 taskRoot = rootActivity.mActivityComponent;
5621 }
5622 }
5623
Hui Yu03d12402018-12-06 18:00:37 -08005624 final Message m = PooledLambda.obtainMessage(
5625 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005626 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005627 mH.sendMessage(m);
5628 }
5629
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005630 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5631 String hostingType) {
5632 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005633 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5634 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005635 + activity.processName);
5636 }
5637 // Post message to start process to avoid possible deadlock of calling into AMS with the
5638 // ATMS lock held.
5639 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5640 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5641 isTop, hostingType, activity.intent.getComponent());
5642 mH.sendMessage(m);
5643 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005644 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005645 }
5646 }
5647
Wale Ogunwale53783742018-09-16 10:21:51 -07005648 void setBooting(boolean booting) {
5649 mAmInternal.setBooting(booting);
5650 }
5651
5652 boolean isBooting() {
5653 return mAmInternal.isBooting();
5654 }
5655
5656 void setBooted(boolean booted) {
5657 mAmInternal.setBooted(booted);
5658 }
5659
5660 boolean isBooted() {
5661 return mAmInternal.isBooted();
5662 }
5663
5664 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5665 mH.post(() -> {
5666 if (finishBooting) {
5667 mAmInternal.finishBooting();
5668 }
5669 if (enableScreen) {
5670 mInternal.enableScreenAfterBoot(isBooted());
5671 }
5672 });
5673 }
5674
5675 void setHeavyWeightProcess(ActivityRecord root) {
5676 mHeavyWeightProcess = root.app;
5677 final Message m = PooledLambda.obtainMessage(
5678 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005679 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005680 mH.sendMessage(m);
5681 }
5682
5683 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5684 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5685 return;
5686 }
5687
5688 mHeavyWeightProcess = null;
5689 final Message m = PooledLambda.obtainMessage(
5690 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5691 proc.mUserId);
5692 mH.sendMessage(m);
5693 }
5694
5695 private void cancelHeavyWeightProcessNotification(int userId) {
5696 final INotificationManager inm = NotificationManager.getService();
5697 if (inm == null) {
5698 return;
5699 }
5700 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005701 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005702 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5703 } catch (RuntimeException e) {
5704 Slog.w(TAG, "Error canceling notification for service", e);
5705 } catch (RemoteException e) {
5706 }
5707
5708 }
5709
5710 private void postHeavyWeightProcessNotification(
5711 WindowProcessController proc, Intent intent, int userId) {
5712 if (proc == null) {
5713 return;
5714 }
5715
5716 final INotificationManager inm = NotificationManager.getService();
5717 if (inm == null) {
5718 return;
5719 }
5720
5721 try {
5722 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5723 String text = mContext.getString(R.string.heavy_weight_notification,
5724 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5725 Notification notification =
5726 new Notification.Builder(context,
5727 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5728 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5729 .setWhen(0)
5730 .setOngoing(true)
5731 .setTicker(text)
5732 .setColor(mContext.getColor(
5733 com.android.internal.R.color.system_notification_accent_color))
5734 .setContentTitle(text)
5735 .setContentText(
5736 mContext.getText(R.string.heavy_weight_notification_detail))
5737 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5738 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5739 new UserHandle(userId)))
5740 .build();
5741 try {
5742 inm.enqueueNotificationWithTag("android", "android", null,
5743 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5744 } catch (RuntimeException e) {
5745 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5746 } catch (RemoteException e) {
5747 }
5748 } catch (PackageManager.NameNotFoundException e) {
5749 Slog.w(TAG, "Unable to create context for heavy notification", e);
5750 }
5751
5752 }
5753
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005754 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5755 IBinder token, String resultWho, int requestCode, Intent[] intents,
5756 String[] resolvedTypes, int flags, Bundle bOptions) {
5757
5758 ActivityRecord activity = null;
5759 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5760 activity = ActivityRecord.isInStackLocked(token);
5761 if (activity == null) {
5762 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5763 return null;
5764 }
5765 if (activity.finishing) {
5766 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5767 return null;
5768 }
5769 }
5770
5771 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5772 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5773 bOptions);
5774 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5775 if (noCreate) {
5776 return rec;
5777 }
5778 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5779 if (activity.pendingResults == null) {
5780 activity.pendingResults = new HashSet<>();
5781 }
5782 activity.pendingResults.add(rec.ref);
5783 }
5784 return rec;
5785 }
5786
Andrii Kulian52d255c2018-07-13 11:32:19 -07005787 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005788 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005789 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005790 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5791 mCurAppTimeTracker.start(resumedActivity.packageName);
5792 }
5793 }
5794
5795 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5796 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005797 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005798 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5799 }
5800 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005801 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005802 constructResumedTraceName(resumed.packageName), 0);
5803 }
5804 mTracedResumedActivity = resumed;
5805 }
5806
5807 private String constructResumedTraceName(String packageName) {
5808 return "focused app: " + packageName;
5809 }
5810
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005811 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005812 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005813 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005814 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005815 // mainStack is null during startup.
5816 if (mainStack != null) {
5817 if (changes != 0 && starting == null) {
5818 // If the configuration changed, and the caller is not already
5819 // in the process of starting an activity, then find the top
5820 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005821 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005822 }
5823
5824 if (starting != null) {
5825 kept = starting.ensureActivityConfiguration(changes,
5826 false /* preserveWindow */);
5827 // And we need to make sure at this point that all other activities
5828 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005829 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005830 !PRESERVE_WINDOWS);
5831 }
5832 }
5833
5834 return kept;
5835 }
5836
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005837 void scheduleAppGcsLocked() {
5838 mH.post(() -> mAmInternal.scheduleAppGcs());
5839 }
5840
Wale Ogunwale53783742018-09-16 10:21:51 -07005841 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5842 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5843 }
5844
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005845 /**
5846 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5847 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5848 * on demand.
5849 */
5850 IPackageManager getPackageManager() {
5851 return AppGlobals.getPackageManager();
5852 }
5853
5854 PackageManagerInternal getPackageManagerInternalLocked() {
5855 if (mPmInternal == null) {
5856 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5857 }
5858 return mPmInternal;
5859 }
5860
Hai Zhangf4da9be2019-05-01 13:46:06 +08005861 PermissionPolicyInternal getPermissionPolicyInternal() {
5862 if (mPermissionPolicyInternal == null) {
5863 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5864 }
5865 return mPermissionPolicyInternal;
5866 }
5867
Wale Ogunwale008163e2018-07-23 23:11:08 -07005868 AppWarnings getAppWarningsLocked() {
5869 return mAppWarnings;
5870 }
5871
Wale Ogunwale214f3482018-10-04 11:00:47 -07005872 Intent getHomeIntent() {
5873 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5874 intent.setComponent(mTopComponent);
5875 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5876 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5877 intent.addCategory(Intent.CATEGORY_HOME);
5878 }
5879 return intent;
5880 }
5881
Chilun2ef71f72018-11-16 17:57:15 +08005882 /**
5883 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5884 * activities.
5885 *
5886 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5887 * component defined in config_secondaryHomeComponent.
5888 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5889 */
5890 Intent getSecondaryHomeIntent(String preferredPackage) {
5891 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005892 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5893 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5894 if (preferredPackage == null || useSystemProvidedLauncher) {
5895 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005896 final String secondaryHomeComponent = mContext.getResources().getString(
5897 com.android.internal.R.string.config_secondaryHomeComponent);
5898 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5899 } else {
5900 intent.setPackage(preferredPackage);
5901 }
5902 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5903 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5904 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5905 }
5906 return intent;
5907 }
5908
Wale Ogunwale214f3482018-10-04 11:00:47 -07005909 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5910 if (info == null) return null;
5911 ApplicationInfo newInfo = new ApplicationInfo(info);
5912 newInfo.initForUser(userId);
5913 return newInfo;
5914 }
5915
Wale Ogunwale9c103022018-10-18 07:44:54 -07005916 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005917 if (uid == SYSTEM_UID) {
5918 // The system gets to run in any process. If there are multiple processes with the same
5919 // uid, just pick the first (this should never happen).
5920 final SparseArray<WindowProcessController> procs =
5921 mProcessNames.getMap().get(processName);
5922 if (procs == null) return null;
5923 final int procCount = procs.size();
5924 for (int i = 0; i < procCount; i++) {
5925 final int procUid = procs.keyAt(i);
5926 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5927 // Don't use an app process or different user process for system component.
5928 continue;
5929 }
5930 return procs.valueAt(i);
5931 }
5932 }
5933
5934 return mProcessNames.get(processName, uid);
5935 }
5936
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005937 WindowProcessController getProcessController(IApplicationThread thread) {
5938 if (thread == null) {
5939 return null;
5940 }
5941
5942 final IBinder threadBinder = thread.asBinder();
5943 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5944 for (int i = pmap.size()-1; i >= 0; i--) {
5945 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5946 for (int j = procs.size() - 1; j >= 0; j--) {
5947 final WindowProcessController proc = procs.valueAt(j);
5948 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5949 return proc;
5950 }
5951 }
5952 }
5953
5954 return null;
5955 }
5956
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005957 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005958 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005959 if (proc == null) return null;
5960 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5961 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005962 }
5963 return null;
5964 }
5965
Riddle Hsua0536432019-02-16 00:38:59 +08005966 int getUidState(int uid) {
5967 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005968 }
5969
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005970 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005971 // A uid is considered to be foreground if it has a visible non-toast window.
5972 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005973 }
5974
Ricky Wai96f5c352019-04-10 18:40:17 +01005975 boolean isDeviceOwner(int uid) {
5976 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005977 }
5978
Ricky Wai96f5c352019-04-10 18:40:17 +01005979 void setDeviceOwnerUid(int uid) {
5980 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005981 }
5982
Wale Ogunwale9de19442018-10-18 19:05:03 -07005983 /**
5984 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5985 * the whitelist
5986 */
5987 String getPendingTempWhitelistTagForUidLocked(int uid) {
5988 return mPendingTempWhitelist.get(uid);
5989 }
5990
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005991 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5992 if (true || Build.IS_USER) {
5993 return;
5994 }
5995
5996 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5997 StrictMode.allowThreadDiskWrites();
5998 try {
5999 File tracesDir = new File("/data/anr");
6000 File tracesFile = null;
6001 try {
6002 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6003
6004 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006005 String timeString =
6006 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6007 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006008 sb.append(": ");
6009 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6010 sb.append(" since ");
6011 sb.append(msg);
6012 FileOutputStream fos = new FileOutputStream(tracesFile);
6013 fos.write(sb.toString().getBytes());
6014 if (app == null) {
6015 fos.write("\n*** No application process!".getBytes());
6016 }
6017 fos.close();
6018 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6019 } catch (IOException e) {
6020 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6021 return;
6022 }
6023
6024 if (app != null && app.getPid() > 0) {
6025 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6026 firstPids.add(app.getPid());
6027 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6028 }
6029
6030 File lastTracesFile = null;
6031 File curTracesFile = null;
6032 for (int i=9; i>=0; i--) {
6033 String name = String.format(Locale.US, "slow%02d.txt", i);
6034 curTracesFile = new File(tracesDir, name);
6035 if (curTracesFile.exists()) {
6036 if (lastTracesFile != null) {
6037 curTracesFile.renameTo(lastTracesFile);
6038 } else {
6039 curTracesFile.delete();
6040 }
6041 }
6042 lastTracesFile = curTracesFile;
6043 }
6044 tracesFile.renameTo(curTracesFile);
6045 } finally {
6046 StrictMode.setThreadPolicy(oldPolicy);
6047 }
6048 }
6049
Michal Karpinskida34cd42019-04-02 19:46:52 +01006050 boolean isAssociatedCompanionApp(int userId, int uid) {
6051 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6052 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006053 return false;
6054 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006055 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006056 }
6057
Issei Suzuki734bc942019-06-05 13:59:52 +02006058 void notifySingleTaskDisplayEmpty(int displayId) {
6059 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6060 }
6061
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006062 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006063 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006064
6065
Wale Ogunwale98875612018-10-12 07:53:02 -07006066 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6067 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006068
Riddle Hsud93a6c42018-11-29 21:50:06 +08006069 H(Looper looper) {
6070 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006071 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006072
6073 @Override
6074 public void handleMessage(Message msg) {
6075 switch (msg.what) {
6076 case REPORT_TIME_TRACKER_MSG: {
6077 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6078 tracker.deliverResult(mContext);
6079 } break;
6080 }
6081 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006082 }
6083
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006084 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006085 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006086
6087 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006088 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006089 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006090
6091 @Override
6092 public void handleMessage(Message msg) {
6093 switch (msg.what) {
6094 case DISMISS_DIALOG_UI_MSG: {
6095 final Dialog d = (Dialog) msg.obj;
6096 d.dismiss();
6097 break;
6098 }
6099 }
6100 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006101 }
6102
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006103 final class LocalService extends ActivityTaskManagerInternal {
6104 @Override
6105 public SleepToken acquireSleepToken(String tag, int displayId) {
6106 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006107 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006108 }
6109
6110 @Override
6111 public ComponentName getHomeActivityForUser(int userId) {
6112 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006113 final ActivityRecord homeActivity =
6114 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006115 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006116 }
6117 }
6118
6119 @Override
6120 public void onLocalVoiceInteractionStarted(IBinder activity,
6121 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6122 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006123 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006124 }
6125 }
6126
6127 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006128 public void notifySingleTaskDisplayDrawn(int displayId) {
6129 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6130 }
6131
6132 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006133 public void notifyAppTransitionFinished() {
6134 synchronized (mGlobalLock) {
6135 mStackSupervisor.notifyAppTransitionDone();
6136 }
6137 }
6138
6139 @Override
6140 public void notifyAppTransitionCancelled() {
6141 synchronized (mGlobalLock) {
6142 mStackSupervisor.notifyAppTransitionDone();
6143 }
6144 }
6145
6146 @Override
6147 public List<IBinder> getTopVisibleActivities() {
6148 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006149 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006150 }
6151 }
6152
6153 @Override
6154 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6155 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006156 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006157 }
6158 }
6159
6160 @Override
6161 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6162 Bundle bOptions) {
6163 Preconditions.checkNotNull(intents, "intents");
6164 final String[] resolvedTypes = new String[intents.length];
6165
6166 // UID of the package on user userId.
6167 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6168 // packageUid may not be initialized.
6169 int packageUid = 0;
6170 final long ident = Binder.clearCallingIdentity();
6171
6172 try {
6173 for (int i = 0; i < intents.length; i++) {
6174 resolvedTypes[i] =
6175 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6176 }
6177
6178 packageUid = AppGlobals.getPackageManager().getPackageUid(
6179 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6180 } catch (RemoteException e) {
6181 // Shouldn't happen.
6182 } finally {
6183 Binder.restoreCallingIdentity(ident);
6184 }
6185
Riddle Hsu591bf612019-02-14 17:55:31 +08006186 return getActivityStartController().startActivitiesInPackage(
6187 packageUid, packageName,
6188 intents, resolvedTypes, null /* resultTo */,
6189 SafeActivityOptions.fromBundle(bOptions), userId,
6190 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6191 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006192 }
6193
6194 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006195 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6196 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6197 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6198 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006199 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006200 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006201 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6202 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6203 userId, validateIncomingUser, originatingPendingIntent,
6204 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006205 }
6206 }
6207
6208 @Override
6209 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6210 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6211 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006212 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006213 PendingIntentRecord originatingPendingIntent,
6214 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006215 synchronized (mGlobalLock) {
6216 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6217 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6218 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006219 validateIncomingUser, originatingPendingIntent,
6220 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006221 }
6222 }
6223
6224 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006225 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6226 Intent intent, Bundle options, int userId) {
6227 return ActivityTaskManagerService.this.startActivityAsUser(
6228 caller, callerPacakge, intent,
6229 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6230 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6231 false /*validateIncomingUser*/);
6232 }
6233
6234 @Override
lumark588a3e82018-07-20 18:53:54 +08006235 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006236 synchronized (mGlobalLock) {
6237
6238 // We might change the visibilities here, so prepare an empty app transition which
6239 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006240 final DisplayContent displayContent =
6241 mRootActivityContainer.getDisplayContent(displayId);
6242 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006243 return;
6244 }
Louis Chang677921f2019-12-06 16:44:24 +08006245 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006246 final boolean wasTransitionSet =
6247 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006248 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006249 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006250 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006251 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006252
6253 // If there was a transition set already we don't want to interfere with it as we
6254 // might be starting it too early.
6255 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006256 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006257 }
6258 }
6259 if (callback != null) {
6260 callback.run();
6261 }
6262 }
6263
6264 @Override
6265 public void notifyKeyguardTrustedChanged() {
6266 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006267 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006268 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006269 }
6270 }
6271 }
6272
6273 /**
6274 * Called after virtual display Id is updated by
6275 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6276 * {@param vrVr2dDisplayId}.
6277 */
6278 @Override
6279 public void setVr2dDisplayId(int vr2dDisplayId) {
6280 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6281 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006282 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006283 }
6284 }
6285
6286 @Override
6287 public void setFocusedActivity(IBinder token) {
6288 synchronized (mGlobalLock) {
6289 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6290 if (r == null) {
6291 throw new IllegalArgumentException(
6292 "setFocusedActivity: No activity record matching token=" + token);
6293 }
Louis Chang19443452018-10-09 12:10:21 +08006294 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006295 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006296 }
6297 }
6298 }
6299
6300 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006301 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006302 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006303 }
6304
6305 @Override
6306 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006307 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006308 }
6309
6310 @Override
6311 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006312 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006313 }
6314
6315 @Override
6316 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6317 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6318 }
6319
6320 @Override
6321 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006322 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006323 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006324
6325 @Override
6326 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6327 synchronized (mGlobalLock) {
6328 mActiveVoiceInteractionServiceComponent = component;
6329 }
6330 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006331
6332 @Override
6333 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6334 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6335 return;
6336 }
6337 synchronized (mGlobalLock) {
6338 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6339 if (types == null) {
6340 if (uid < 0) {
6341 return;
6342 }
6343 types = new ArrayMap<>();
6344 mAllowAppSwitchUids.put(userId, types);
6345 }
6346 if (uid < 0) {
6347 types.remove(type);
6348 } else {
6349 types.put(type, uid);
6350 }
6351 }
6352 }
6353
6354 @Override
6355 public void onUserStopped(int userId) {
6356 synchronized (mGlobalLock) {
6357 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6358 mAllowAppSwitchUids.remove(userId);
6359 }
6360 }
6361
6362 @Override
6363 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6364 synchronized (mGlobalLock) {
6365 return ActivityTaskManagerService.this.isGetTasksAllowed(
6366 caller, callingPid, callingUid);
6367 }
6368 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006369
Riddle Hsua0536432019-02-16 00:38:59 +08006370 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006371 @Override
6372 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006373 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006374 mProcessNames.put(proc.mName, proc.mUid, proc);
6375 }
6376 }
6377
Riddle Hsua0536432019-02-16 00:38:59 +08006378 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006379 @Override
6380 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006381 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006382 mProcessNames.remove(name, uid);
6383 }
6384 }
6385
Riddle Hsua0536432019-02-16 00:38:59 +08006386 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006387 @Override
6388 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006389 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006390 if (proc == mHomeProcess) {
6391 mHomeProcess = null;
6392 }
6393 if (proc == mPreviousProcess) {
6394 mPreviousProcess = null;
6395 }
6396 }
6397 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006398
Riddle Hsua0536432019-02-16 00:38:59 +08006399 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006400 @Override
6401 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006402 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006403 return mTopProcessState;
6404 }
6405 }
6406
Riddle Hsua0536432019-02-16 00:38:59 +08006407 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006408 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006409 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006410 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006411 return proc == mHeavyWeightProcess;
6412 }
6413 }
6414
Riddle Hsua0536432019-02-16 00:38:59 +08006415 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006416 @Override
6417 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006418 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006419 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6420 }
6421 }
6422
6423 @Override
6424 public void finishHeavyWeightApp() {
6425 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006426 if (mHeavyWeightProcess != null) {
6427 mHeavyWeightProcess.finishActivities();
6428 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006429 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6430 mHeavyWeightProcess);
6431 }
6432 }
6433
Riddle Hsua0536432019-02-16 00:38:59 +08006434 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006435 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006436 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006437 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006438 return isSleepingLocked();
6439 }
6440 }
6441
6442 @Override
6443 public boolean isShuttingDown() {
6444 synchronized (mGlobalLock) {
6445 return mShuttingDown;
6446 }
6447 }
6448
6449 @Override
6450 public boolean shuttingDown(boolean booted, int timeout) {
6451 synchronized (mGlobalLock) {
6452 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006453 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006454 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006455 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006456 return mStackSupervisor.shutdownLocked(timeout);
6457 }
6458 }
6459
6460 @Override
6461 public void enableScreenAfterBoot(boolean booted) {
6462 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006463 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006464 mWindowManager.enableScreenAfterBoot();
6465 updateEventDispatchingLocked(booted);
6466 }
6467 }
6468
6469 @Override
6470 public boolean showStrictModeViolationDialog() {
6471 synchronized (mGlobalLock) {
6472 return mShowDialogs && !mSleeping && !mShuttingDown;
6473 }
6474 }
6475
6476 @Override
6477 public void showSystemReadyErrorDialogsIfNeeded() {
6478 synchronized (mGlobalLock) {
6479 try {
6480 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6481 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6482 + " data partition or your device will be unstable.");
6483 mUiHandler.post(() -> {
6484 if (mShowDialogs) {
6485 AlertDialog d = new BaseErrorDialog(mUiContext);
6486 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6487 d.setCancelable(false);
6488 d.setTitle(mUiContext.getText(R.string.android_system_label));
6489 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6490 d.setButton(DialogInterface.BUTTON_POSITIVE,
6491 mUiContext.getText(R.string.ok),
6492 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6493 d.show();
6494 }
6495 });
6496 }
6497 } catch (RemoteException e) {
6498 }
6499
6500 if (!Build.isBuildConsistent()) {
6501 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6502 mUiHandler.post(() -> {
6503 if (mShowDialogs) {
6504 AlertDialog d = new BaseErrorDialog(mUiContext);
6505 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6506 d.setCancelable(false);
6507 d.setTitle(mUiContext.getText(R.string.android_system_label));
6508 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6509 d.setButton(DialogInterface.BUTTON_POSITIVE,
6510 mUiContext.getText(R.string.ok),
6511 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6512 d.show();
6513 }
6514 });
6515 }
6516 }
6517 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006518
6519 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006520 public void onProcessMapped(int pid, WindowProcessController proc) {
6521 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006522 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006523 }
6524 }
6525
6526 @Override
6527 public void onProcessUnMapped(int pid) {
6528 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006529 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006530 }
6531 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006532
6533 @Override
6534 public void onPackageDataCleared(String name) {
6535 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006536 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006537 mAppWarnings.onPackageDataCleared(name);
6538 }
6539 }
6540
6541 @Override
6542 public void onPackageUninstalled(String name) {
6543 synchronized (mGlobalLock) {
6544 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006545 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006546 }
6547 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006548
6549 @Override
6550 public void onPackageAdded(String name, boolean replacing) {
6551 synchronized (mGlobalLock) {
6552 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6553 }
6554 }
6555
6556 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006557 public void onPackageReplaced(ApplicationInfo aInfo) {
6558 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006559 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006560 }
6561 }
6562
6563 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006564 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6565 synchronized (mGlobalLock) {
6566 return compatibilityInfoForPackageLocked(ai);
6567 }
6568 }
6569
Yunfan Chen75157d72018-07-27 14:47:21 +09006570 /**
6571 * Set the corresponding display information for the process global configuration. To be
6572 * called when we need to show IME on a different display.
6573 *
6574 * @param pid The process id associated with the IME window.
6575 * @param displayId The ID of the display showing the IME.
6576 */
6577 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006578 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006579 // Don't update process-level configuration for Multi-Client IME process since other
6580 // IMEs on other displays will also receive this configuration change due to IME
6581 // services use the same application config/context.
6582 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006583
Yunfan Chen75157d72018-07-27 14:47:21 +09006584 if (pid == MY_PID || pid < 0) {
6585 if (DEBUG_CONFIGURATION) {
6586 Slog.w(TAG,
6587 "Trying to update display configuration for system/invalid process.");
6588 }
6589 return;
6590 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006591 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006592 final DisplayContent displayContent =
6593 mRootActivityContainer.getDisplayContent(displayId);
6594 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006595 // Call might come when display is not yet added or has been removed.
6596 if (DEBUG_CONFIGURATION) {
6597 Slog.w(TAG, "Trying to update display configuration for non-existing "
6598 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006599 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006600 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006601 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006602 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006603 if (process == null) {
6604 if (DEBUG_CONFIGURATION) {
6605 Slog.w(TAG, "Trying to update display configuration for invalid "
6606 + "process, pid=" + pid);
6607 }
6608 return;
6609 }
lumarkddc77fb2019-06-27 22:22:23 +08006610 process.mIsImeProcess = true;
Louis Chang677921f2019-12-06 16:44:24 +08006611 process.registerDisplayConfigurationListenerLocked(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006612 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006613 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006614
6615 @Override
6616 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006617 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006618 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006619 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6620 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006621 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006622 }
6623 }
6624 }
6625
6626 @Override
6627 public void clearPendingResultForActivity(IBinder activityToken,
6628 WeakReference<PendingIntentRecord> pir) {
6629 synchronized (mGlobalLock) {
6630 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6631 if (r != null && r.pendingResults != null) {
6632 r.pendingResults.remove(pir);
6633 }
6634 }
6635 }
6636
6637 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006638 public ActivityTokens getTopActivityForTask(int taskId) {
6639 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08006640 final Task task = mRootActivityContainer.anyTaskForId(taskId);
6641 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006642 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6643 + " Requested task not found");
6644 return null;
6645 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006646 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006647 if (activity == null) {
6648 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6649 + " Requested activity not found");
6650 return null;
6651 }
6652 if (!activity.attachedToProcess()) {
6653 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6654 + activity);
6655 return null;
6656 }
6657 return new ActivityTokens(activity.appToken, activity.assistToken,
6658 activity.app.getThread());
6659 }
6660 }
6661
6662 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006663 public IIntentSender getIntentSender(int type, String packageName,
6664 int callingUid, int userId, IBinder token, String resultWho,
6665 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6666 Bundle bOptions) {
6667 synchronized (mGlobalLock) {
6668 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6669 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6670 }
6671 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006672
6673 @Override
6674 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6675 synchronized (mGlobalLock) {
6676 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6677 if (r == null) {
6678 return null;
6679 }
6680 if (r.mServiceConnectionsHolder == null) {
6681 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6682 ActivityTaskManagerService.this, r);
6683 }
6684
6685 return r.mServiceConnectionsHolder;
6686 }
6687 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006688
6689 @Override
6690 public Intent getHomeIntent() {
6691 synchronized (mGlobalLock) {
6692 return ActivityTaskManagerService.this.getHomeIntent();
6693 }
6694 }
6695
6696 @Override
6697 public boolean startHomeActivity(int userId, String reason) {
6698 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006699 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006700 }
6701 }
6702
6703 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006704 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006705 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006706 synchronized (mGlobalLock) {
6707 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006708 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006709 }
Chilun8b1f1be2019-03-13 17:14:36 +08006710 }
6711
6712 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006713 public boolean startHomeOnAllDisplays(int userId, String reason) {
6714 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006715 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006716 }
6717 }
6718
Riddle Hsua0536432019-02-16 00:38:59 +08006719 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006720 @Override
6721 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006722 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006723 if (mFactoryTest == FACTORY_TEST_OFF) {
6724 return false;
6725 }
6726 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6727 && wpc.mName.equals(mTopComponent.getPackageName())) {
6728 return true;
6729 }
6730 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6731 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6732 }
6733 }
6734
6735 @Override
6736 public void updateTopComponentForFactoryTest() {
6737 synchronized (mGlobalLock) {
6738 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6739 return;
6740 }
6741 final ResolveInfo ri = mContext.getPackageManager()
6742 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6743 final CharSequence errorMsg;
6744 if (ri != null) {
6745 final ActivityInfo ai = ri.activityInfo;
6746 final ApplicationInfo app = ai.applicationInfo;
6747 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6748 mTopAction = Intent.ACTION_FACTORY_TEST;
6749 mTopData = null;
6750 mTopComponent = new ComponentName(app.packageName, ai.name);
6751 errorMsg = null;
6752 } else {
6753 errorMsg = mContext.getResources().getText(
6754 com.android.internal.R.string.factorytest_not_system);
6755 }
6756 } else {
6757 errorMsg = mContext.getResources().getText(
6758 com.android.internal.R.string.factorytest_no_action);
6759 }
6760 if (errorMsg == null) {
6761 return;
6762 }
6763
6764 mTopAction = null;
6765 mTopData = null;
6766 mTopComponent = null;
6767 mUiHandler.post(() -> {
6768 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6769 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006770 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006771 });
6772 }
6773 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006774
Riddle Hsua0536432019-02-16 00:38:59 +08006775 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006776 @Override
6777 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6778 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006779 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006780 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006781 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006782
6783 wpc.clearRecentTasks();
6784 wpc.clearActivities();
6785
6786 if (wpc.isInstrumenting()) {
6787 finishInstrumentationCallback.run();
6788 }
6789
Jorim Jaggid0752812018-10-16 16:07:20 +02006790 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006791 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006792 try {
6793 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6794 // If there was nothing to resume, and we are not already restarting
6795 // this process, but there is a visible activity that is hosted by the
6796 // process...then make sure all visible activities are running, taking
6797 // care of restarting this process.
6798 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6799 !PRESERVE_WINDOWS);
6800 }
6801 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006802 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006803 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006804 }
6805 }
6806 }
6807
6808 @Override
6809 public void closeSystemDialogs(String reason) {
6810 enforceNotIsolatedCaller("closeSystemDialogs");
6811
6812 final int pid = Binder.getCallingPid();
6813 final int uid = Binder.getCallingUid();
6814 final long origId = Binder.clearCallingIdentity();
6815 try {
6816 synchronized (mGlobalLock) {
6817 // Only allow this from foreground processes, so that background
6818 // applications can't abuse it to prevent system UI from being shown.
6819 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006820 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006821 if (!proc.isPerceptible()) {
6822 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6823 + " from background process " + proc);
6824 return;
6825 }
6826 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006827 mWindowManager.closeSystemDialogs(reason);
6828
Wale Ogunwaled32da472018-11-16 07:19:28 -08006829 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006830 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006831 // Call into AM outside the synchronized block.
6832 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006833 } finally {
6834 Binder.restoreCallingIdentity(origId);
6835 }
6836 }
6837
6838 @Override
6839 public void cleanupDisabledPackageComponents(
6840 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6841 synchronized (mGlobalLock) {
6842 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006843 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006844 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006845 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006846 mStackSupervisor.scheduleIdleLocked();
6847 }
6848
6849 // Clean-up disabled tasks
6850 getRecentTasks().cleanupDisabledPackageTasksLocked(
6851 packageName, disabledClasses, userId);
6852 }
6853 }
6854
6855 @Override
6856 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6857 int userId) {
6858 synchronized (mGlobalLock) {
6859
6860 boolean didSomething =
6861 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006862 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006863 null, doit, evenPersistent, userId);
6864 return didSomething;
6865 }
6866 }
6867
6868 @Override
6869 public void resumeTopActivities(boolean scheduleIdle) {
6870 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006871 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006872 if (scheduleIdle) {
6873 mStackSupervisor.scheduleIdleLocked();
6874 }
6875 }
6876 }
6877
Riddle Hsua0536432019-02-16 00:38:59 +08006878 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 @Override
6880 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006881 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006882 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6883 }
6884 }
6885
Riddle Hsua0536432019-02-16 00:38:59 +08006886 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006887 @Override
6888 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006889 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006890 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6891 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6892 }
6893 try {
6894 return mRootActivityContainer.attachApplication(wpc);
6895 } finally {
6896 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6897 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006898 }
6899 }
6900
6901 @Override
6902 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6903 try {
6904 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6905 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6906 }
6907 } catch (RemoteException ex) {
6908 throw new SecurityException("Fail to check is caller a privileged app", ex);
6909 }
6910
6911 synchronized (mGlobalLock) {
6912 final long ident = Binder.clearCallingIdentity();
6913 try {
6914 if (mAmInternal.shouldConfirmCredentials(userId)) {
6915 if (mKeyguardController.isKeyguardLocked()) {
6916 // Showing launcher to avoid user entering credential twice.
6917 startHomeActivity(currentUserId, "notifyLockedProfile");
6918 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006919 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006920 }
6921 } finally {
6922 Binder.restoreCallingIdentity(ident);
6923 }
6924 }
6925 }
6926
6927 @Override
6928 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6929 mAmInternal.enforceCallingPermission(
6930 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6931
6932 synchronized (mGlobalLock) {
6933 final long ident = Binder.clearCallingIdentity();
6934 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006935 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6936 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006937 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006938 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6939 UserHandle.CURRENT);
6940 } finally {
6941 Binder.restoreCallingIdentity(ident);
6942 }
6943 }
6944 }
6945
6946 @Override
6947 public void writeActivitiesToProto(ProtoOutputStream proto) {
6948 synchronized (mGlobalLock) {
6949 // The output proto of "activity --proto activities"
6950 // is ActivityManagerServiceDumpActivitiesProto
Jeffrey Huangcb782852019-12-05 11:28:11 -08006951 mRootActivityContainer.dumpDebug(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006952 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6953 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006954 }
6955 }
6956
6957 @Override
6958 public void saveANRState(String reason) {
6959 synchronized (mGlobalLock) {
6960 final StringWriter sw = new StringWriter();
6961 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6962 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6963 if (reason != null) {
6964 pw.println(" Reason: " + reason);
6965 }
6966 pw.println();
6967 getActivityStartController().dump(pw, " ", null);
6968 pw.println();
6969 pw.println("-------------------------------------------------------------------------------");
6970 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6971 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6972 "" /* header */);
6973 pw.println();
6974 pw.close();
6975
6976 mLastANRState = sw.toString();
6977 }
6978 }
6979
6980 @Override
6981 public void clearSavedANRState() {
6982 synchronized (mGlobalLock) {
6983 mLastANRState = null;
6984 }
6985 }
6986
6987 @Override
6988 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6989 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6990 synchronized (mGlobalLock) {
6991 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6992 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6993 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6994 dumpLastANRLocked(pw);
6995 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6996 dumpLastANRTracesLocked(pw);
6997 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6998 dumpActivityStarterLocked(pw, dumpPackage);
6999 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7000 dumpActivityContainersLocked(pw);
7001 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7002 if (getRecentTasks() != null) {
7003 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7004 }
7005 }
7006 }
7007 }
7008
7009 @Override
7010 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7011 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7012 int wakefulness) {
7013 synchronized (mGlobalLock) {
7014 if (mHomeProcess != null && (dumpPackage == null
7015 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7016 if (needSep) {
7017 pw.println();
7018 needSep = false;
7019 }
7020 pw.println(" mHomeProcess: " + mHomeProcess);
7021 }
7022 if (mPreviousProcess != null && (dumpPackage == null
7023 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7024 if (needSep) {
7025 pw.println();
7026 needSep = false;
7027 }
7028 pw.println(" mPreviousProcess: " + mPreviousProcess);
7029 }
7030 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7031 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7032 StringBuilder sb = new StringBuilder(128);
7033 sb.append(" mPreviousProcessVisibleTime: ");
7034 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7035 pw.println(sb);
7036 }
7037 if (mHeavyWeightProcess != null && (dumpPackage == null
7038 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7039 if (needSep) {
7040 pw.println();
7041 needSep = false;
7042 }
7043 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7044 }
7045 if (dumpPackage == null) {
7046 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007047 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007048 }
7049 if (dumpAll) {
7050 if (dumpPackage == null) {
7051 pw.println(" mConfigWillChange: "
7052 + getTopDisplayFocusedStack().mConfigWillChange);
7053 }
7054 if (mCompatModePackages.getPackages().size() > 0) {
7055 boolean printed = false;
7056 for (Map.Entry<String, Integer> entry
7057 : mCompatModePackages.getPackages().entrySet()) {
7058 String pkg = entry.getKey();
7059 int mode = entry.getValue();
7060 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7061 continue;
7062 }
7063 if (!printed) {
7064 pw.println(" mScreenCompatPackages:");
7065 printed = true;
7066 }
7067 pw.println(" " + pkg + ": " + mode);
7068 }
7069 }
7070 }
7071
7072 if (dumpPackage == null) {
7073 pw.println(" mWakefulness="
7074 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007075 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007076 if (mRunningVoice != null) {
7077 pw.println(" mRunningVoice=" + mRunningVoice);
7078 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7079 }
7080 pw.println(" mSleeping=" + mSleeping);
7081 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7082 pw.println(" mVrController=" + mVrController);
7083 }
7084 if (mCurAppTimeTracker != null) {
7085 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7086 }
7087 if (mAllowAppSwitchUids.size() > 0) {
7088 boolean printed = false;
7089 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7090 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7091 for (int j = 0; j < types.size(); j++) {
7092 if (dumpPackage == null ||
7093 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7094 if (needSep) {
7095 pw.println();
7096 needSep = false;
7097 }
7098 if (!printed) {
7099 pw.println(" mAllowAppSwitchUids:");
7100 printed = true;
7101 }
7102 pw.print(" User ");
7103 pw.print(mAllowAppSwitchUids.keyAt(i));
7104 pw.print(": Type ");
7105 pw.print(types.keyAt(j));
7106 pw.print(" = ");
7107 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7108 pw.println();
7109 }
7110 }
7111 }
7112 }
7113 if (dumpPackage == null) {
7114 if (mController != null) {
7115 pw.println(" mController=" + mController
7116 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7117 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007118 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7119 pw.println(" mLaunchingActivityWakeLock="
7120 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007121 }
7122
7123 return needSep;
7124 }
7125 }
7126
7127 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007128 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7129 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007130 synchronized (mGlobalLock) {
7131 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007132 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007133 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007134 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7135 if (mRunningVoice != null) {
7136 final long vrToken = proto.start(
7137 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7138 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7139 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007140 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007141 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7142 proto.end(vrToken);
7143 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007144 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007145 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007146 if (mController != null) {
7147 final long token = proto.start(CONTROLLER);
7148 proto.write(CONTROLLER, mController.toString());
7149 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7150 proto.end(token);
7151 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007152 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7153 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007154 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007155 }
7156
7157 if (mHomeProcess != null && (dumpPackage == null
7158 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007159 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007160 }
7161
7162 if (mPreviousProcess != null && (dumpPackage == null
7163 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007164 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007165 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7166 }
7167
7168 if (mHeavyWeightProcess != null && (dumpPackage == null
7169 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007170 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007171 }
7172
7173 for (Map.Entry<String, Integer> entry
7174 : mCompatModePackages.getPackages().entrySet()) {
7175 String pkg = entry.getKey();
7176 int mode = entry.getValue();
7177 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7178 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7179 proto.write(PACKAGE, pkg);
7180 proto.write(MODE, mode);
7181 proto.end(compatToken);
7182 }
7183 }
7184
7185 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007186 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007187 }
7188
7189 }
7190 }
7191
7192 @Override
7193 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7194 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7195 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007196 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7197 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007198 }
7199
7200 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007201 public void dumpForOom(PrintWriter pw) {
7202 synchronized (mGlobalLock) {
7203 pw.println(" mHomeProcess: " + mHomeProcess);
7204 pw.println(" mPreviousProcess: " + mPreviousProcess);
7205 if (mHeavyWeightProcess != null) {
7206 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7207 }
7208 }
7209 }
7210
7211 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007212 public boolean canGcNow() {
7213 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007214 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007215 }
7216 }
7217
Riddle Hsua0536432019-02-16 00:38:59 +08007218 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007219 @Override
7220 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007221 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007222 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007223 return top != null ? top.app : null;
7224 }
7225 }
7226
Riddle Hsua0536432019-02-16 00:38:59 +08007227 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007228 @Override
7229 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007230 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007231 if (mRootActivityContainer != null) {
7232 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007233 }
7234 }
7235 }
7236
7237 @Override
7238 public void scheduleDestroyAllActivities(String reason) {
7239 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007240 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007241 }
7242 }
7243
7244 @Override
7245 public void removeUser(int userId) {
7246 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007247 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007248 }
7249 }
7250
7251 @Override
7252 public boolean switchUser(int userId, UserState userState) {
7253 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007254 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007255 }
7256 }
7257
7258 @Override
7259 public void onHandleAppCrash(WindowProcessController wpc) {
7260 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007261 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007262 }
7263 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007264
7265 @Override
7266 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7267 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007268 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007269 }
7270 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007271
Riddle Hsua0536432019-02-16 00:38:59 +08007272 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007273 @Override
7274 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007275 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007276 }
7277
Riddle Hsua0536432019-02-16 00:38:59 +08007278 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007279 @Override
7280 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007281 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007282 }
7283
Riddle Hsua0536432019-02-16 00:38:59 +08007284 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007285 @Override
7286 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007287 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007288 }
7289
Riddle Hsua0536432019-02-16 00:38:59 +08007290 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007291 @Override
7292 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007293 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007294 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007295
7296 @Override
7297 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007298 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007299 mPendingTempWhitelist.put(uid, tag);
7300 }
7301 }
7302
7303 @Override
7304 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007305 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007306 mPendingTempWhitelist.remove(uid);
7307 }
7308 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007309
7310 @Override
7311 public boolean handleAppCrashInActivityController(String processName, int pid,
7312 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7313 Runnable killCrashingAppCallback) {
7314 synchronized (mGlobalLock) {
7315 if (mController == null) {
7316 return false;
7317 }
7318
7319 try {
7320 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7321 stackTrace)) {
7322 killCrashingAppCallback.run();
7323 return true;
7324 }
7325 } catch (RemoteException e) {
7326 mController = null;
7327 Watchdog.getInstance().setActivityController(null);
7328 }
7329 return false;
7330 }
7331 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007332
7333 @Override
7334 public void removeRecentTasksByPackageName(String packageName, int userId) {
7335 synchronized (mGlobalLock) {
7336 mRecentTasks.removeTasksByPackageName(packageName, userId);
7337 }
7338 }
7339
7340 @Override
7341 public void cleanupRecentTasksForUser(int userId) {
7342 synchronized (mGlobalLock) {
7343 mRecentTasks.cleanupLocked(userId);
7344 }
7345 }
7346
7347 @Override
7348 public void loadRecentTasksForUser(int userId) {
7349 synchronized (mGlobalLock) {
7350 mRecentTasks.loadUserRecentsLocked(userId);
7351 }
7352 }
7353
7354 @Override
7355 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7356 synchronized (mGlobalLock) {
7357 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7358 }
7359 }
7360
7361 @Override
7362 public void flushRecentTasks() {
7363 mRecentTasks.flush();
7364 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007365
7366 @Override
7367 public WindowProcessController getHomeProcess() {
7368 synchronized (mGlobalLock) {
7369 return mHomeProcess;
7370 }
7371 }
7372
7373 @Override
7374 public WindowProcessController getPreviousProcess() {
7375 synchronized (mGlobalLock) {
7376 return mPreviousProcess;
7377 }
7378 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007379
7380 @Override
7381 public void clearLockedTasks(String reason) {
7382 synchronized (mGlobalLock) {
7383 getLockTaskController().clearLockedTasks(reason);
7384 }
7385 }
7386
7387 @Override
7388 public void updateUserConfiguration() {
7389 synchronized (mGlobalLock) {
7390 final Configuration configuration = new Configuration(getGlobalConfiguration());
7391 final int currentUserId = mAmInternal.getCurrentUserId();
7392 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7393 configuration, currentUserId, Settings.System.canWrite(mContext));
7394 updateConfigurationLocked(configuration, null /* starting */,
7395 false /* initLocale */, false /* persistent */, currentUserId,
7396 false /* deferResume */);
7397 }
7398 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007399
7400 @Override
7401 public boolean canShowErrorDialogs() {
7402 synchronized (mGlobalLock) {
7403 return mShowDialogs && !mSleeping && !mShuttingDown
7404 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7405 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7406 mAmInternal.getCurrentUserId())
7407 && !(UserManager.isDeviceInDemoMode(mContext)
7408 && mAmInternal.getCurrentUser().isDemo());
7409 }
7410 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007411
7412 @Override
7413 public void setProfileApp(String profileApp) {
7414 synchronized (mGlobalLock) {
7415 mProfileApp = profileApp;
7416 }
7417 }
7418
7419 @Override
7420 public void setProfileProc(WindowProcessController wpc) {
7421 synchronized (mGlobalLock) {
7422 mProfileProc = wpc;
7423 }
7424 }
7425
7426 @Override
7427 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7428 synchronized (mGlobalLock) {
7429 mProfilerInfo = profilerInfo;
7430 }
7431 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007432
7433 @Override
7434 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7435 synchronized (mGlobalLock) {
7436 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7437 }
7438 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007439
7440 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007441 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7442 boolean reducedResolution) {
7443 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7444 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007445 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007446
7447 @Override
7448 public boolean isUidForeground(int uid) {
7449 synchronized (mGlobalLock) {
7450 return ActivityTaskManagerService.this.isUidForeground(uid);
7451 }
7452 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007453
7454 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007455 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007456 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007457 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007458 }
7459 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007460
7461 @Override
7462 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007463 // Translate package names into UIDs
7464 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007465 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007466 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7467 if (uid >= 0) {
7468 result.add(uid);
7469 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007470 }
7471 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007472 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007473 }
7474 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007475 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007476}